Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does python property decorator eat this exception? [duplicate]

Nothing prints when I run this code. Why? 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 suggested by BrenBarn has the information needed to answer my question, though not directly. But I can answer my own question now:

The property decorator uses AttributeError as a signal from the getter to call __getattr__, so if your getter throws an attribute error, it will be caught and you won't see it.

Thank you lemonhead and mission.liao for indulging my ignorance.

like image 574
gluejar Avatar asked Nov 26 '25 17:11

gluejar


1 Answers

Okay, I figured out what is happening here:

 elif self.fake.get("blah", ''):
     print '2'

This is the problematic line. self.fake is None, so running None.get('blah') raises an AttributeError. However, since this is inside a property, python treats this as if the property does not exist, and so in turn calls __getattr__, which does not print anything

like image 116
lemonhead Avatar answered Nov 28 '25 17:11

lemonhead



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!