Dictionary type access to list of instances

Jason Orendorff jason at jorendorff.com
Mon Feb 25 19:52:13 EST 2002


Brian Kelley wrote:
> In this usage, getattr will raise an Attribute error if property doesn't 
> exist which might not be what you want.
> 
> Here is an attempt using list comprehensions and the built-in list.index 
> function.  I have created a NotEqual class so that getattr can return a 
> default value is never equal to any other instance.  This is because 
> None might be a valid value for a property.
> 
> class NotEqual: [...]
> 
> def get(inputList, property, value, default=NotEqual()):
>      try:
>          properties = [getattr(x, property, default) for x in inputList]
>          return inputList[properties.index(value)]
>      [...]

Here are some alternatives.  (Each must be wrapped in a for loop.)

  (1)   if hasattr(x, property) and getattr(x, property) == value:
             return x

  (2)   try:
            if getattr(x, property) == value:
                return x
        except AttributeError:
            pass  # x doesn't have that property; skip it

  (3)   if getattr(x, property, not value) == value:
             return x

I'm fond of the last one.  No builtin value will have
"value == not value", and user-defined types will typically
avoid it too.

## Jason Orendorff    http://www.jorendorff.com/




More information about the Python-list mailing list