Python – How do I check for missing properties?

How do I check for missing properties?… here is a solution to the problem.

How do I check for missing properties?

I have to check if foo is a property of myclass.

It’s me now

def myclass():
    try:
        self.foo
    except AttributeError:
        self.foo = 'default'

When I thought I should do it

if not hasattr(self,'foo'):
    self.foo = 'default'

Is there any difference between these two methods? Which one should be preferred?

I’m looking for the following:

  • Consistency with multiple inheritance
  • Portability across Python versions
  • Limited overhead

Solution

The two methods are functionally equivalent.

from the hasattr docs :

hasattr(object, name)

The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if
not. (This is implemented by calling getattr(object, name) and seeing
whether it raises an AttributeError or not.)

and the getattr docs are described below:

getattr(x, 'foobar') is equivalent to x.foobar


Regarding speed, my tests showed that Hasattr is slightly faster. The result of 1 million iterations is:

hasattr: 0.6325701880014094 seconds
try:     0.8206841319988598 seconds

Unless you’re writing highly optimized code, there’s no need to worry about such a small difference. There is also no need to worry about compatibility with Python versions; Property access and hasattr are available in every version of Python.


In the end, it comes down to preference. Choose the one you think is more readable.

Related Problems and Solutions