Answer the question
In order to leave comments, you need to log in
How do variables work in a decorator?
I can't figure out why:
- this is how the function sees the variable:
def talk(func):
def wrap(word):
print(word)
return wrap
@talk
def func(word):
pass
func('yeee')
yeeedef talk(func):
print(word)
@talk
def func(word):
pass
func('yeee')
NameError: name 'word' is not defined
Answer the question
In order to leave comments, you need to log in
Python expands the construct @talk
into func = talk(func)
. Since the talk function returns a wrap function, after the "unwrapping" is complete, you get func = wrap
, and by calling func(word)
you are actually calling wrap(word)
.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question