Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A get() like method for checking for Python attributes

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'

like image 226
jamtoday Avatar asked Dec 10 '08 09:12

jamtoday


People also ask

How do you check attributes in Python?

We can use hasattr() function to find if a python object obj has a certain attribute or property. hasattr(obj, 'attribute'): The convention in python is that, if the property is likely to be there, simply call it and catch it with a try/except block.

What are attributes and methods in Python?

A variable stored in an instance or class is called an attribute. A function stored in an instance or class is called a method.

How do you access the attributes of a class in Python?

Accessing the attributes of a classgetattr() − A python method used to access the attribute of a class. hasattr() − A python method used to verify the presence of an attribute in a class. setattr() − A python method used to set an additional attribute in a class.

What are Python attributes?

Python class attributes are variables of a class that are shared between all of its instances. They differ from instance attributes in that instance attributes are owned by one specific instance of the class only, and are not shared between instances.


1 Answers

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.

like image 193
Brian Avatar answered Oct 13 '22 11:10

Brian