Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check for a missing attribute?

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

Right now I do

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

while I think I should be doing

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

Is there any difference between the two approaches, and which one should be preferred?

I am looking for the following criteria:

  • Consistency with multiple inheritance
  • Portability across python versions
  • Limited overhead
like image 833
00__00__00 Avatar asked Oct 25 '25 03:10

00__00__00


1 Answers

Both of those approaches 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 state the following:

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


Regarding speed, my tests show that hasattr is a little faster. The results with 1 million iterations were:

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's also no need to worry about compatibility with python versions; attribute access and hasattr are available in every version of python.


In the end, it comes down to preference. Choose whichever you find more readable.

like image 55
Aran-Fey Avatar answered Oct 26 '25 18:10

Aran-Fey