290 likes | 827 Views
Graeme Cross MPUG, March 2011. An intro to Python decorators. Housekeeping. The audience: new – intermediate Python programmers who have not used decorators This talk (and example code) is online at: hg clone https://gjcross@bitbucket.org/gjcross/talks. Interior decorating, Python style.
E N D
Graeme Cross MPUG, March 2011 An intro to Python decorators
Housekeeping • The audience: new – intermediate Python programmers who have not used decorators • This talk (and example code) is online at: hg clone https://gjcross@bitbucket.org/gjcross/talks
Interior decorating, Python style • Decorators modify or extend functions, methods or classes • That’s it! • They are not special, just convenient • Simple syntax: @decorator
Decorators and decorators • Python 2.4: function/method decorators • Python 2.6: class decorators • Python’s decorator != GOF Decorator pattern • Note: this talk will just cover function/method decorators (not class decorators)
Why bother? • Decorators help with: • Readability • Less lines of code • Explicit behaviour • Code maintenance • Minimising code duplication • Robust design • Separation of concerns • Widely used in Python libraries
Out of the box... • Python has a range of built-in decorators • For example: @property @staticmethod @classmethod
Defining a decorator def decorator(f) # do something with f return f @decorator def myfunc(x): # my function’s code here...
An example... • Two examples of how to use class properties: • property.py • decorator_prop.py
Typical uses • Mimic Eiffel’s preconditions/postconditions • Check values and/or types • Cache results • Record function results, entry and exit times/states/values • Simplify synchronisation, locking • Enable debugging, logging, tracing and profiling
Roll your own! • An example of defining our own decorator • If we have a computationally intensive algorithm: • Seen the input before? • No: Calculate and cache the result (takes a while) • Yes: Return the cached result (fast) • Example: • cache.py
Want to know more? • http://wiki.python.org/moin/PythonDecorators • http://wiki.python.org/moin/PythonDecoratorLibrary • http://www.python.org/dev/peps/pep-0318/ • “Learning Python”, 4th edition, chapter 38 • http://www.ibm.com/developerworks/linux/library/l-cpdecor.html • http://code.activestate.com/recipes/langs/python/tags/decorator/