简体   繁体   中英

Python: behaviour of decorator with wrapper

I don´t understand why the line "cache = {}" is executed only the first time i call the function multiply(x, y). After that, that line is ignored. This makes the program work well, but i don´t understand that behaviour.

def memoize(func):

     cache = {}
     print("cache")

     @functools.wraps(func)
     def wrapper(*args):
         if args in cache:
             return cache[args]

         result = func(*args)
         cache[args] = result

         return result

     return wrapper

 @memoize
 def multiply(x, y):
     return x * y

 print(multiply(2, 3))
 print(multiply(2, 3))

The result is:

 cache
 6
 6

So the lines "cache = {}" and "print("cache")" were only executed the frist time. Thanks

The part of the decorator code which is "executed everytime" is the wrapper function. The code outside that wrapper function is executed just when the operator is applied -

This nothing magic or "new" - just see the order things are and what is called when - the only thing out of normal execution order which cold be called just a bit magic is the decoration itself- just remember that:

 @memoize
 def multiply(x, y):
     return x * y

is just the same thing as:

def multiply(x, y):
     return x * y

multiply = memoize(multiply)

Also, if you are trying to understand decorators, leave the functools.wraps call out of it for now. It is good for production code, and for filling in small details: it disguises your wrapper function as the inner function it decorates (for example, the function wrapper __name__ attribute is set to multiply in this example), but is an unnecessary complication when trying to understand decorators.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM