Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decorator NameError

Consider this simple decorator demo:

class DecoratorDemo():

    def _decorator(f):
        def w( self ) :
            print( "now decorated")
            f( self )
        return w

    @_decorator
    def bar( self ) :
        print ("the mundane")

d = DecoratorDemo()
d.bar()

Running this gives the expected output:

now decorated
the mundane

The type for d.bar and d._decorator confirm as <class 'method'> if I add the following two lines to the end of above code.

print(type(d.bar))
print(type(d._decorator))

Now if i modify the above code to define bar method before defining the _decorator method, I get the error

     @_decorator
NameError: name '_decorator' is not defined

Why is it that the ordering of the methods is relevant in the above case ?

like image 525
bhaskarc Avatar asked Mar 24 '26 08:03

bhaskarc


1 Answers

Because the decorated method is not actually a 'method declaration' as it seems. What the decorator syntax suger hides is this:

def bar( self ) :
    print ("the mundane")
bar = _decorator(bar)

If you put these lines before the definition of _decorator, the name error doesn't come as a surprise. Like @Daniel Roseman said, the class body is just code, that is executed top to bottom.

like image 132
NeoWang Avatar answered Mar 26 '26 22:03

NeoWang



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!