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:
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 tox.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With