Skip to content

Instantly share code, notes, and snippets.

@slinkp
Created October 28, 2013 19:34
Show Gist options
  • Save slinkp/7203134 to your computer and use it in GitHub Desktop.
Save slinkp/7203134 to your computer and use it in GitHub Desktop.
Python: getattr() vs. hasattr()
Beware of hasattr(). It will return False on *any* exception. This is rarely what you want.
>>> class Thing(object):
... @property
... def foo(self):
... return self.this_will_raise_attribute_error
... @property
... def bar(self):
... return 1 / 0 # ZeroDevisionError...
>>>
>>> t = Thing()
If you access those directly, you get the expected exceptions:
>>> t.foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in foo
AttributeError: 'Thing' object has no attribute 'something_else_that_does_not_exist'
>>> t.bar
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in bar
ZeroDivisionError: integer division or modulo by zero
However, 'hasattr' output is misleading:
>>> hasattr(t, 'foo') # this is to be expected
False
>>> hasattr(t, 'bar') # whaaa?
False
Both of these properties exist, but hasattr makes it look like they don't,
if accessing them raises any exception whatsoever.
If you don't want to swallow arbitrary exceptions (and you probably should not),
then getattr() is safer:
>>> hasattr(t, 'bar')
False
>>> getattr(t, 'bar', None) is None
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in bar
ZeroDivisionError: integer division or modulo by zero
>>> getattr(t, 'foo', None) is None
True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment