Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save JokerMartini/728eb6370bbf344fe180 to your computer and use it in GitHub Desktop.
Save JokerMartini/728eb6370bbf344fe180 to your computer and use it in GitHub Desktop.
Python: Collect attribute from a list of objects where attribute exists
existing_names = [getattr(x, "name", "") for x in nodes if type(x).__name__ == node_class]
values = [ getattr(x.data, "age", "") for x in nodes ]
>> ['5', '7', '12']
# However if the attribute 'age' is not there it returns this
>> ['5', '', '7', '', '12']
values = [ getattr(x.data, 'age', '') for x in nodes ]
values = filter(bool, values)
>> ['5', '7', '12']
# or use these options
values = [ getattr(x.data, 'age') for x in nodes if hasattr(x.data, 'age')]
values = [ x.data.age for x in nodes if hasattr(x.data, 'age')]
values = [ x.data.age for x in nodes if hasattr(x, 'data') and hasattr(x.data, 'age') ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment