introduction to python decorators

Post on 20-May-2015

918 Views

Category:

Technology

9 Downloads

Preview:

Click to see full reader

DESCRIPTION

Presentation held at the Amsterdam Python Meetup Group

TRANSCRIPT

Python DecoratorsIntroduction to Python decorators

Rik van Achterberg | 2013-12-04

You might have seen them

Some theory

● Introduced in Python 2.4.

● Decorators can be used to implement the

decorator pattern.

● Decorators are similar to annotations in

Java/C#.

● When compared to C, decorators are comparable

to preprocessor macros.

● Decorators are possible thanks to functions,

like everything else, being objects.

Decorators replace functions

Function being replaced by class

Function being replaced by (inner) function

Decorators are just syntactic sugar

● A decorator is a function or class that

takes a function as an argument and

returns a replacement callable.

● The ‘@object’ syntax above functions is

not magic;

● It just provides a clean notation.

Identical behaviour with and without

decorators

Adding ‘logging’ argument:

How decorators are being called

Beginner’s mistakeThis function based sleep decorator lacks

nesting.

Calls broken_sleep_decorator(say_hello) upon program initialization;

so sleep(1) is always called.

Function is not replaced

Working sleep decorator

Executessay_hello = sleep_decorator(say_hello)

Calls wrapper(“Byte”)

Call is equal to:sleep_decorator(say_hello)(“Byte”)

Defines ‘wrapper’ and returns it as replacement function

Calls original function

Tunable sleep decorator

Calls tunable_sleep_decorator(seconds=1)(say_hello)

Calls wrapper(“Byte”)

Call is equal to:tunable_sleep_decorator(seconds=1)(say_hello)(“Byte”)

Accepts decorator arguments

Accepts function argument

Accepts arguments for function

Calls original function

Function vs Class decorators

● They can be written to have near

identical behaviour;

● However, classes allow storage of

state.

● It depends on the situation, really.

Function vs. class decorators

● Basic function vs. class example

● Note the difference in return values

Function vs. Class decoratorsA counter that stores state

Debug decoratorCall function with args, surrounded by

print statements

Basic benchmark decorator

Retry decorator

Further reading

● http://www.python.org/dev/peps/pep-0318/

● https://wiki.python.org/moin/PythonDecorators

● https://wiki.python.org/moin/PythonDecoratorLibrary

● http://www.artima.com/weblogs/viewpost.jsp?thread=240808

● http://pythonconquerstheuniverse.wordpress.com/2012/04/29/python-decorators/

● http://stackoverflow.com/questions/739654/how-can-i-make-a-chain-of-function-decorators-in-

python/1594484#1594484

● http://www.ibm.com/developerworks/library/l-cpdecor/

code examples from this presentation:

@rikva/decorators

top related