style question - hasattr
Miles
semanticist at gmail.com
Wed Apr 9 00:41:27 EDT 2008
On Tue, Apr 8, 2008 at 10:21 PM, ian <ian.team.python at saltmob.com> wrote:
> Ok, so what about 'hasattr' ??
> hasattr(myObject,'property')
> seems equivalent to
> 'property' in dir(myObject)
>
> I would suggest that using the 'in' is cleaner in this case also. Is
> there a performance penalty here? Or is there reason why the two are
> not actually the same?
>>> class HasAll(object):
... def __getattr__(self, name): pass
...
>>> hasattr(HasAll(), 'spam')
True
>>> 'spam' in dir(HasAll())
False
>From the docs: "Because dir() is supplied primarily as a convenience
for use at an interactive prompt, it tries to supply an interesting
set of names more than it tries to supply a rigorously or consistently
defined set of names, and its detailed behavior may change across
releases. ... [hasattr] is implemented by calling getattr(object,
name) and seeing whether it raises an exception or not."
http://docs.python.org/lib/built-in-funcs.html
> Which style is preferred??
Don't test for the existence of the attribute if you're going to get
it when it exists; just go ahead and get it.
try:
x = myObject.property
except AttributeError:
x = None
- Miles
More information about the Python-list
mailing list