2

What does "Decorated function definitions do not result in temporary name binding" mean?

I am now studying decorators in Python, and this sentence really confused me.

1
  • We're going to need to see the context. Commented Dec 3, 2017 at 4:09

1 Answer 1

4

I think it's saying that the decorated function is never actually assigned to anything in the namespace before the decorator is applied. When you write a function with a decorator, the function you write is passed to the decorator as an argument, and the object the decorator returns is then treated as the function. Here's a quick example:

def dec(func):
  print('times_two' in globals())
  def _inner(*args, **kwargs):
    print("Decorated")
    return func(*args, **kwargs)
  return _inner

@dec
def times_two(x):
  return x*2

print('times_two' in globals())

You can see this running here. The print in dec says False, because the name "times_two" isn't bound to anything before the decorator is done "decorating" the function.

Sign up to request clarification or add additional context in comments.

7 Comments

"A function definition may be wrapped by one or more decorator expressions. Decorator expressions are evaluated when the function is defined, in the scope that contains the function definition. The result must be a callable, which is invoked with the function object as the only argument. The returned value is bound to the function name instead of the function object. Multiple decorators are applied in nested fashion. For example, the following code" Are these two statements same??
@HongliBu Which two statements?
The statements in my question and comment
They're both true, but they're not the same. Basically, it's easy to imagine a scenario in which there would be some way of calling times_two in the above example such that it doesn't also print "Decorated", accessing the function before the decorator is applied. The current implementation of generators guarantees that this will never happen. That's what the statement in your question is saying. The statement in your comment is an explanation of what a decorator is without touching on the above argument.
"The returned value is bound to the function name instead of the function object." might be argued as saying the same as the statement in the question, only much clearer. Anyway, excellent answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.