abidibo.net

Posted in "decorator"

Decorators with Python

decorator patterns python

Decorators in python can be quite easy to use and understand, but flexible decorators using the new syntax introduced by python 2.4 can be a bit more complex.

Here I'll try to explain (especially to myself) the world of decorators in python, starting from simple cases and ending with complex ones. Ideas and notions taken from the Pro Django book by Marty Alchin.

Decorators without extra arguments

Let's create a simple cache decorator you can use to store complex operations:

>>> def cache(func):
...   cache_dict = {}
...   def wrapper(*args, **kwargs):
...     key = '%s-%s' % (repr(args), repr(kwargs))
...     if key not in cache_dict:
...       cache_dict[key] = func(*args, **kwargs)
...       print 'cached'
...     return cache_dict[key]
...   return wrapper

A simple decorator function takes ...

read the full post


  • 1

Your Smartwatch Loves Tasker!

Your Smartwatch Loves Tasker!

Now available for purchase!

Featured