Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I was reading about hasattr, there I saw one motto in Python that says that is Easier to ask for forgiveness than permission where I normally agree.

I tried to do a performance test in this case with a python code:

import timeit

definition="""\

class A(object):

    a = 1

a = A()

"""

stm="""\

hasattr(a, 'a')

"""

print timeit.timeit(stmt=stm, setup=definition, number=10000000)

stm="""\

getattr(a, 'a')

"""

print timeit.timeit(stmt=stm, setup=definition, number=10000000)

With the results:

$ python test.py

hasattr(a, 'a')

1.26515984535

getattr(a, 'a')

1.32518696785

With this, I analyzed that the getattr is slower than hasattr, but in the official documentation, it says that it calls getattr.

So why in the documentation we say that hasattr calls getattr and we seem to inspire the users to use getattr instead of hasattr when it really isn´t due to performance? 

Please log in to answer this question.

Related questions

0 votes
1 answer
asked Sep 26, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
asked Jan 19, 2021 in Python by ashely (50.2k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...