style question - hasattr

I

ian

In old python code i would use 'has_key' to determine if an element
was present in a dictionary.

Python 3.0 will even removed 'has_key'. The reason for removal is that
using the 'in' operator is a cleaner syntax and having two ways to
achieve the same result is against the principle of the language.

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?

Which style is preferred??
 
T

Terry Reedy

| In old python code i would use 'has_key' to determine if an element
| was present in a dictionary.
|
| Python 3.0 will even removed 'has_key'. The reason for removal is that
| using the 'in' operator is a cleaner syntax and having two ways to
| achieve the same result is against the principle of the language.
|
| 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?

Yes, the construction of the dir.
And I think there may be slight differences between the two.

tjr
 
M

Miles

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?
.... def __getattr__(self, name): pass
....
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top