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.

+3


source to share


2 answers


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

+4


source


The main reason is that you are overriding the __getattr__ method



bizarre.odd will be called as expected when you remove the fancy .__ getattr __.

+1


source







All Articles