Which magic method does hasattr call?

Question:

Which magic method method does hasattr call?

getattr(__o, name) can also be called as __o.__getattr__(name)

setattr(__o, name) can also be called as __o.__setattr__(name)

But what is the equivalent for hasattr?

I know the associated magic method for the in keyword is __contains__.

Answers:

There is no specific dunder method for hasattr(). It’s essentially equivalent to:

def hasattr(object, name):
    try:
        getattr(object, name)
        return True
    except AttributeError:
        return False

So it’s dependent on the same dunder methods used by getattr().

Answered By: Barmar

The documentation for hasattr specifically states that

This is implemented by calling getattr(object, name) and seeing whether it raises an AttributeError or not.

That means that the __getattr__ and __getattribute__ are the dunders you are most concerned about.

Answered By: Mad Physicist
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.