A get() like method for checking for Python attributes

PythonAttributes

Python Problem Overview


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'

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

Do you mean hasattr() perhaps?

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 doesn't work for methods.

"attribute" in obj.__dict__

Solution 3 - Python

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')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjamtodayView Question on Stackoverflow
Solution 1 - PythonBrianView Answer on Stackoverflow
Solution 2 - PythonZoomulatorView Answer on Stackoverflow
Solution 3 - PythonunbeknownView Answer on Stackoverflow