Text of wiki.python.org › python › archive › PythonDecoratorLibrary.html as Styx crawled it on Nov 19, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

Python Decorator Library - Python Wiki

Python Wiki Python Wiki / Python Wiki / Archive / Python Decorator Library View as Markdown Python Decorator Library ¶ Legacy Wiki Page This page was migrated from the old MoinMoin-based wiki. Information may be outdated or no longer applicable. For current documentation, see python.org . 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 . Creating Well-Behaved Decorators / “Decorator decorator” ¶ 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. 1 def simple_decorator ( 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 def new_decorator ( f ): 12 g = decorator ( f ) 13 g . __name__ = f . __name__ 14 g . __doc__ = f . __doc__ 15 g . __dict__ . update ( f . __dict__ ) 16 return g 17 # Now a few lines needed to make simple_decorator itself 18 # be a well-behaved decorator.

19 new_decorator . __name__ = decorator . __name__ 20 new_decorator . __doc__ = decorator . __doc__ 21 new_decorator . __dict__ . update ( decorator . __dict__ ) 22 return new_decorator 23 24 # 25 # Sample Use: 26 # 27 @simple_decorator 28 def my_simple_logging_decorator ( func ): 29 def you_will_never_see_this_name ( * args , ** kwargs ): 30 print 'calling {} ' . format ( func . __name__ ) 31 return func ( * args , ** kwargs ) 32 return you_will_never_see_this_name 33 34 @my_simple_logging_decorator 35 def double ( x ): 36 'Doubles a number.' 37 return 2 * x 38 39 assert double . __name__ == 'double' 40 assert double . __doc__ == 'Doubles a number.' 41 print double ( 155 ) Property Definition ¶ These decorators provide a readable way to define properties: 1 import sys 2 3 def propget ( func ): 4 locals = sys . _getframe ( 1 ) . f_locals 5 name = func . __name__ 6 prop = locals . get ( name ) 7 if not isinstance ( prop , property ): 8 prop = property ( func , doc = func . __doc__ ) 9 else : 10 doc = prop . __doc__ or func . __doc__ 11 prop = property ( func , prop . fset , prop . fdel , doc ) 12 return prop 13 14 def propset ( func ): 15 locals = sys . _getframe ( 1 ) . f_locals 16 name = func . __name__ 17 prop = locals . get ( name ) 18 if not isinstance ( prop , property ): 19 prop = property ( None , func , doc = func . __doc__ ) 20 else : 21 doc = prop . __doc__ or func . __doc__ 22 prop = property ( prop . fget , func , prop . fdel , doc ) 23 return prop 24 25 def propdel ( func ): 26 locals = sys . _getframe ( 1 ) . f_locals 27 name = func . __name__ 28 prop = locals . get ( name ) 29 if not isinstance ( prop , property ): 30 prop = property ( None , None , func , doc = func . __doc__ ) 31 else : 32 prop = property ( prop . fget , prop . fset , func , prop . __doc__ ) 33 return prop 34 35 # These can be used like this: 36 37 class Example ( object ): 38 39 @propget 40 def myattr ( self ): 41 return self . _half * 2 42 43 @propset 44 def myattr ( self , value ): 45 self . _half = value / 2 46 47 @propdel 48 def myattr ( self ): 49 del self . _half Here’s a way that doesn’t require any new decorators: 1 class Example ( object ): 2 @apply # doesn't exist in Python 3 3 def myattr (): 4 doc = '''This is the doc string.''' 5 6 def fget ( self ): 7 return self . _half * 2 8 9 def fset ( self , value ): 10 self . _half = value / 2 11 12 def fdel ( self ): 13 del self . _half 14 15 return property ( ** locals ()) 16 #myattr = myattr() # works in Python 2 and 3 Yet another property decorator: 1 try : 2 # Python 2 3 import __builtin__ as builtins 4 except ImportError : 5 # Python 3 6 import builtins 7 8 def property ( function ): 9 keys = 'fget' , 'fset' , 'fdel' 10 func_locals = { 'doc' : function . __doc__ } 11 def probe_func ( frame , event , arg ): 12 if event == 'return' : 13 locals = frame . f_locals 14 func_locals . update ( dict (( k , locals . get ( k )) for k in keys )) 15 sys . settrace ( None ) 16 return probe_func 17 sys . settrace ( probe_func ) 18 function () 19 return builtins . property ( ** func_locals ) 20 21 #====== Example ======================================================= 22 23 from math import radians , degrees , pi 24 25 class Angle ( object ): 26 def __init__ ( self , rad ): 27 self . _rad = rad 28 29 @property 30 def rad (): 31 '''The angle in radians''' 32 def fget ( self ): 33 return self . _rad 34 def fset ( self , angle ): 35 if isinstance ( angle , Angle ): 36 angle = angle . rad 37 self . _rad = float ( angle ) 38 39 @property 40 def deg (): 41 '''The angle in degrees''' 42 def fget ( self ): 43 return degrees ( self . _rad ) 44 def fset ( self , angle ): 45 if isinstance ( angle , Angle ): 46 angle = angle . deg 47 self . _rad = radians ( angle ) Memoize ¶ Here’s a memoizing class.

1 import collections 2 import functools 3 4 class memoized ( object ): 5 '''Decorator. Caches a function's return value each time it is called. 6 If called later with the same arguments, the cached value is returned 7 (not reevaluated). 8 ''' 9 def __init__ ( self , func ): 10 self . func = func 11 self . cache = {} 12 def __call__ ( self , * args ): 13 if not isinstance ( args , collections . Hashable ): 14 # uncacheable. a list, for instance.

15 # better to not cache than blow up. 16 return self . func ( * args ) 17 if args in self . cache : 18 return self . cache [ args ] 19 else : 20 value = self . func ( * args ) 21 self . cache [ args ] = value 22 return value 23 def __repr__ ( self ): 24 '''Return the function's docstring.''' 25 return self . func . __doc__ 26 def __get__ ( self , obj , objtype ): 27 '''Support instance methods.''' 28 return functools . partial ( self . __call__ , obj ) 29 30 @memoized 31 def fibonacci ( n ): 32 "Return the nth fibonacci number." 33 if n in ( 0 , 1 ): 34 return n 35 return fibonacci ( n - 1 ) + fibonacci ( n - 2 ) 36 37 print fibonacci ( 12 ) Alternate memoize as nested functions ¶ Here’s a memoizing function that works on functions, methods, or classes, and exposes the cache publicly.

1 # note that this decorator ignores **kwargs 2 def memoize ( obj ): 3 cache = obj . cache = {} 4 5 @functools . wraps ( obj ) 6 def memoizer ( * args , ** kwargs ): 7 if args not in cache : 8 cache [ args ] = obj ( * args , ** kwargs ) 9 return cache [ args ] 10 return memoizer Here’s a modified version that also respects kwargs. 1 def memoize ( obj ): 2 cache = obj . cache = {} 3 4 @functools . wraps ( obj ) 5 def memoizer ( * args , ** kwargs ): 6 key = str ( args ) + str ( kwargs ) 7 if key not in cache : 8 cache [ key ] = obj ( * args , ** kwargs ) 9 return cache [ key ] 10 return memoizer Alternate memoize as dict subclass ¶ This is an idea that interests me, but it only seems to work on functions: 1 class memoize ( dict ): 2 def __init__ ( self , func ): 3 self . func = func 4 5 def __call__ ( self , * args ): 6 return self [ args ] 7 8 def __missing__ ( self , key ): 9 result = self [ key ] = self . func ( * key ) 10 return result 11 12 # 13 # Sample use 14 # 15 16 >>> @memoize 17 ... def foo ( a , b ): 18 ... return a * b 19 >>> foo ( 2 , 4 ) 20 8 21 >>> foo 22 {( 2 , 4 ): 8 } 23 >>> foo ( 'hi' , 3 ) 24 'hihihi' 25 >>> foo 26 {( 2 , 4 ): 8 , ( 'hi' , 3 ): 'hihihi' } Alternate memoize that stores cache between executions ¶ Additional information and documentation for this decorator is available on Github .

1 import pic

The rest of this page is on the live site.