Advertisement
rfmonk

functools_wraps.py

Jan 15th, 2014
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.12 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3.  
  4. import functools
  5.  
  6.  
  7. def show_details(name, f):
  8.     """Show details of a callable object."""
  9.     print '%s:' % name
  10.     print ' object:', f
  11.     print ' __name__:',
  12.     try:
  13.         print f.__name__
  14.     except AttributeError:
  15.         print '(no __name__)'
  16.     print ' __doc__', repr(f.__doc__)
  17.     print
  18.     return
  19.  
  20.  
  21. def simple_decorator(f):
  22.     @functools.wraps(f)
  23.     def decorated(a='decorated defaults', b=1):
  24.         print ' decorated:', (a, b)
  25.         print ' ',
  26.         f(a, b=b)
  27.         return
  28.     return decorated
  29.  
  30.  
  31. def myfunc(a, b=2):
  32.     "myfunc() is not complicated"
  33.     print ' myfunc:', (a, b)
  34.     return
  35.  
  36. # The raw function
  37. show_details('myfunc', myfunc)
  38. myfunc('unwrapped, default b')
  39. myfunc('unwrapped, passing b', 3)
  40. print
  41.  
  42. # Wrap explicitly
  43. wrapped_myfunc = simple_decorator(myfunc)
  44. show_details('wrapped_myfunc', wrapped_myfunc)
  45. wrapped_myfunc()
  46. wrapped_myfunc('args to wrapped', 4)
  47. print
  48.  
  49.  
  50. # Wrap with decorator syntax
  51. @simple_decorator
  52. def decorated_myfunc(a, b):
  53.     myfunc(a, b)
  54.     return
  55.  
  56. show_details('decorated_myfunc', decorated_myfunc)
  57. decorated_myfunc()
  58. decorated_myfunc('args to decorated', 4)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement