Advertisement
lessientelrunya

functools and wraps

Apr 6th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.68 KB | None | 0 0
  1. # For debugging, the stacktrace prints you the function __name__
  2. def foo():
  3.     print("foo")
  4.  
  5. print(foo.__name__)
  6. #outputs: foo
  7.  
  8. # With a decorator, it gets messy    
  9. def bar(func):
  10.     def wrapper():
  11.         print("bar")
  12.         return func()
  13.     return wrapper
  14.  
  15. @bar
  16. def foo():
  17.     print("foo")
  18.  
  19. print(foo.__name__)
  20. #outputs: wrapper
  21.  
  22. # "functools" can help for that
  23.  
  24. import functools
  25.  
  26. def bar(func):
  27.     # We say that "wrapper", is wrapping "func"
  28.     # and the magic begins
  29.     @functools.wraps(func)
  30.     def wrapper():
  31.         print("bar")
  32.         return func()
  33.     return wrapper
  34.  
  35. @bar
  36. def foo():
  37.     print("foo")
  38.  
  39. print(foo.__name__)
  40. #outputs: foo
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement