__Getattr__ property and compatibility issue with AttributeError
I just ran into unexpected behavior. It's a simple class with a method __getattr__
and a property attribute with a typo inside:
class A(object):
def __getattr__(self, attr):
if not attr.startswith("ignore_"):
raise AttributeError(attr)
@property
def prop(self):
return self.some_typo
a = A() # Instantiating
a.ignore_this # This is ignored
a.prop # This raises an Attribute Error
This is the expected output (the one I get if __getattr__
commented out):
AttributeError: 'A' object has no attribute 'some_typo'
And this is what I get:
AttributeError: prop
I know this has to do with __getattr__
dexterity AttributeError
, but is there a good and clean workaround for this problem? Because I can assure you this is a debugging nightmare ...
source to share
You can simply create a post with a better exception:
class A(object):
def __getattr__(self, attr):
if not attr.startswith("ignore_"):
raise AttributeError("%r object has not attribute %r" % (self.__class__.__name__, attr))
@property
def prop(self):
return self.some_typo
a=A()
a.ignore_this
a.prop
EDIT : Calling __getattribute__
from the base class of the object solves the problem
class A(object):
def __getattr__(self, attr):
if not attr.startswith("ignore_"):
return self.__getattribute__(attr)
@property
def prop(self):
return self.some_typo
source to share