hasattr() or "x in y"?

Grant Edwards invalid at invalid.invalid
Fri Mar 11 17:00:41 EST 2016


On 2016-03-11, Charles T. Smith <cts.private.yahoo at gmail.com> wrote:
> From the performance point of view, which is better:

> - hasattr()
> - x in y

Dunno, is red an even or odd color?  How many pancakes does it take to
cover a doghouse?

>>> "x" in "asdf"
False
>>> "x" in "xyz"
True

>>> "asdf".hasattr("x")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'hasattr'
>>> "xyz".hasattr("x")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'hasattr'

Since they behave differently, perhaps the question ought to be "which
does what you want to do?"

-- 
Grant Edwards               grant.b.edwards        Yow! I had pancake makeup
                                  at               for brunch!
                              gmail.com            



More information about the Python-list mailing list