Skip to content Skip to sidebar Skip to footer

Cheking If An Object Has An Attribute, Without Relying On '__getattr__'

Is there a way to check if an object has an attribute, that doesn't rely on __getattr__ or object implementation specifics? Consider the code below. I want Proxy to delegate to Wra

Solution 1:

The built-in hasattr() function

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

The inspect module has the getattr_static() method, which can be used to

Retrieve attributes without triggering dynamic lookup via the descriptor protocol, __getattr__() or __getattribute__()".

Using this method, you could define a hasattr_static() method similarly to hasattr(), but calling inspect.getattr_static(object, name) instead of getattr(object, name):

import inspect


defhasattr_static(object, name):
    try:
        inspect.getattr_static(object, name)
        returnTrueexcept AttributeError:
        returnFalse

And then use this in the __setattr__() method of your Proxy class as a check:

def__setattr__(self, attr, value):
    if hasattr_static(self, attr):
        object.__setattr__(self, attr, value)
    elifhasattr(self.wrapped, attr):
        setattr(self.wrapped, attr, value)
    else:
        object.__setattr__(self, attr, value)

Alternatively, you coud use the dir() function instead of __dict__ to retrieve a list of attributes of your object, or use inspect.getmembers().

Post a Comment for "Cheking If An Object Has An Attribute, Without Relying On '__getattr__'"