N
N
Nicholas V2018-02-13 16:10:53
Python
Nicholas V, 2018-02-13 16:10:53

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')

>>> yeee
- and so no:
def talk(func):            
    print(word)

@talk
def func(word):
    pass

func('yeee')

NameError: name 'word' is not defined
Well, i.e. where does wrap get the word from if it doesn't seem to be in the scope of talk?..

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2018-02-13
@Amunrah

Python expands the construct @talkinto 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 question

Ask a Question

731 491 924 answers to any question