This page is meant to be a central repository of decorator code pieces, whether useful or not <wink>. It is NOT a page to discuss decorator syntax!

Feel free to add your suggestions. Please make sure example code conforms with PEP 8.

 

 

Note: This is only one recipe. Others include inheritance from a standard decorator (link?), the functools @wraps decorator, and a factory function such as Michele Simionato's decorator module which even preserves signature information.

 

Toggle line numbers
   1 decorator):
   2 '''This decorator can be used to turn simple functions
   3     into well-behaved decorators, so long as the decorators
   4     are fairly simple. If a decorator expects a function and
   5     returns a function (no descriptors), and if it doesn't
   6     modify function attributes or docstring, then it is
   7     eligible to use this. Simply apply @simple_decorator to
   8     your decorator and it will automatically preserve the
   9     docstring and function attributes of functions to which
  10     it is applied.'''
  11 f):
  12 f)
  13 __name__
  14 __doc__
  15 __dict__)
  16 g
  17 # Now a few lines needed to make simple_decorator itself
  18 # be a well-behaved decorator.
  19 __name__
  20 __doc__
  21 __dict__)
  22 new_decorator
  23 
  24 #
  25 # Sample Use:
  26 #
  27 @simple_decorator
  28 func):
  29 kwargs):
  30 __name__)
  31 kwargs)
  32 you_will_never_see_this_name
  33 
  34 @my_simple_logging_decorator
  35 x):
  36 '
  37 x
  38 
  39 __name__ == 

相关文章:

  • 2022-12-23
  • 2021-11-27
  • 2022-12-23
  • 2022-02-26
  • 2022-12-23
  • 2021-08-14
  • 2022-12-23
猜你喜欢
  • 2022-02-15
  • 2022-12-23
  • 2021-09-11
  • 2021-12-24
  • 2021-05-31
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案