Alex Rivera | Logout

A get() like method for checking for Python attributes

Asked 2008-12-10T09:49:39.903
97

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'

Edit
Report

1 Answer

7

For checking if a key is in a dictionary you can use in: 'key' in dictionary.

For checking for attributes in object use the hasattr() function: hasattr(obj, 'attribute')

answered 2008-12-10T10:01:28.133

Your Answer