1

In Python function decorators are again functions that are first class citizens, which creates the expectation of assigning and passing around flexibly. In below example

def auth_token_not_expired(function):
    @auth_token_right
    def wrapper(req):
        # Some validations
        return function(req)
    return wrapper

Now I tried assigning this decorator function to another variable as alias

login_required = auth_token_not_expired

Upon inspecting the assignment happens successfully however when I invoke it using @login_required syntax it causes NameError

Exception Type: NameError
Exception Value:    
name 'login_required' is not defined

How do we register this login_required variable too as decorator?

nehem
  • 12,775
  • 6
  • 58
  • 84
  • 3
    You can do what you are trying to do (I checked Python 2.7 and 3.4). Are you sure you are in the right scope? Where exactly are you doing the assignment to `login_required`? – Matt Hall Nov 22 '15 at 13:41

1 Answers1

2

You are in the wrong scope.

Adapting the example from How to make a chain of function decorators?

def makeitalic(fn):
    def wrapped():
        return "<i>" + fn() + "</i>"
    return wrapped

@makeitalic
def hello():
    return "hello world"

hello() ## returns <i>hello world</i>

Now do the assignment:

mi = makeitalic

@mi
def helloit():
    return "hello world"

helloit() ## returns <i>hello world</i>
Community
  • 1
  • 1
Matt Hall
  • 7,614
  • 1
  • 23
  • 36