Why does the python property decorator feed on this exception?
Doesn't print anything when I run this code. What for? No exceptions are thrown, nothing in the if ... elif ... else structure is executed.
Environment: Python 2.7.
d= {"x":1}
class bizarre(object):
def __init__(self):
self.metadata = {}
def __getattr__(self, name):
return self.metadata.get(name, None)
@property
def odd(self):
if False:
print '1'
elif self.fake.get("blah", ''):
print '2'
else:
print '3'
b=bizarre()
b.odd
The previous answer , as suggested by BrenBarn , contains the information needed to answer my question, although not directly. But now I can answer my own question:
The property decorator uses AttributeError
as a signal from the __getattr__
getter to call , so if your getter throws an attribute error, it will be caught and you won't see it.
Thanks lemonhead and mission.liao for pandering to my ignorance.
source to share
Ok, I figured out what's going on here:
elif self.fake.get("blah", ''):
print '2'
This is a problematic line. self.fake
None
, so the launch None.get('blah')
calls AttributeError
. However, since this is inside a property, python treats it as if the property does not exist, and therefore in turn calls __getattr__
which does not print anything
source to share