A get() like method for checking for Python attributes

jamtoday picture jamtoday · Dec 10, 2008 · Viewed 44.5k times · Source

If I had a dictionary dict and I wanted to check for dict['key'] I could either do so in a try block (bleh!) or use the get() method, with False as a default value.

I'd like to do the same thing for object.attribute. That is, I already have object to return False if it hasn't been set, but then that gives me errors like

AttributeError: 'bool' object has no attribute 'attribute'

Answer

Brian picture Brian · Dec 10, 2008

A more direct analogue to dict.get(key, default) than hasattr is getattr.

val = getattr(obj, 'attr_to_check', default_value)

(Where default_value is optional, raising an exception on no attribute if not found.)

For your example, you would pass False.