Get () method for checking Python attributes

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

I would like to do the same for object.attribute . That is, I already have an object to return False if it has not been set, but then it gives me errors like

AttributeError: 'bool' object does not have attribute 'attribute'

+45
python attributes
Dec 10 '08 at 9:49
source share
3 answers

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

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

(Where default_value is optional, throwing an exception without an attribute if not found.)

In your example, you will pass False .

+74
Dec 10 '08 at 14:27
source share

Do you mean hasattr() maybe?

 hasattr(object, "attribute name") #Returns True or False 

Python.org doc - Built-in functions - hasattr ()

You can also do this, which is a bit more cluttered and does not work for methods.

 "attribute" in obj.__dict__ 
+15
Dec 10 '08 at 9:59
source share

To check for a key in a dictionary, you can use in : 'key' in dictionary .

To check attributes in an object, use the hasattr() function: hasattr(obj, 'attribute')

+6
Dec 10 '08 at 10:01
source share



All Articles