Maybe i’m just up too late.
I have an object that is a thin wrapper around a dictionary. It will pretend to have a property for any key in the dictionary, and return None if a nonexistent key is referenced.
I want to get back only the unique, “truthy” values for three possible keys. (not None). the object may not have one or more of the keys. Or, it may have the same value in two or three of the keys.
This code does what I want:
set(getattr(obj, field) for field in ['field1', 'field2', 'field3'] if getattr(obj, field))
I just don’t like the look of repeating getattr() twice. I feel like i’m overlooking an obviously better way to do this.
You could filter out the
Nonevalues afterwards:Or you could just forget about the object. This is probably the way I would do it: