Advanced Python Techniques: Decorators

3 downloads 16410 Views 596KB Size Report
Advanced Python Techniques: Decorators. Tomo Popović. Žabljak 2015. Page 2. Python Programming Language ... Can be used to implement loggers, timers,.
Advanced Python Techniques: Decorators

Tomo Popović Žabljak 2015

Python Programming Language ●

Extremely popular in recent years



Open Source



Great community



Supported by both the universities and industry

IT'15 Conference Žabljak, © 2015 Copyright T. Popovic

Decorators ● ●



Easy to use Can be used to implement loggers, timers, format conversions, frameworks Example of the use:

IT'15 Conference Žabljak, © 2015 Copyright T. Popovic

Objects in Python

IT'15 Conference Žabljak, © 2015 Copyright T. Popovic

Functions as objects ●

Functions are first class objects: –

They have types



They can be elements of data structures (lists)



They can appear in expressions ● ●

As part of an assignment statement As arguments to a function

IT'15 Conference Žabljak, © 2015 Copyright T. Popovic

Closures ●

A closure is a first class function



A closure can be stored as a variable



A closure has an ability to access other variables local to the scope in which it was created

IT'15 Conference Žabljak, © 2015 Copyright T. Popovic

Decorators: Definition ●



A decorator is typically a function that takes another function as an argument, referred to as decorated function, and then returns a new function. The returned function replaces or augments the behavior of the decorated function.

IT'15 Conference Žabljak, © 2015 Copyright T. Popovic

Implementation using classes

IT'15 Conference Žabljak, © 2015 Copyright T. Popovic

Implementation using functions

IT'15 Conference Žabljak, © 2015 Copyright T. Popovic

Decorators with Arguments

IT'15 Conference Žabljak, © 2015 Copyright T. Popovic

An example: execution timer

IT'15 Conference Žabljak, © 2015 Copyright T. Popovic

Conclusions ●







A decorator is a callable object that accepts one argument, which is a reference to the function being decorated. It returns a reference to a function which augments the behavior of the decorated function. This paper illustrates implementing of decorators using Python classes or functions. Decorators with arguments are described as well. Multiple decorators can be applied to a single function. Hopefully, the work will inspire further exploration of decorators and other Python techniques.

IT'15 Conference Žabljak, © 2015 Copyright T. Popovic

Learn More

IT'15 Conference Žabljak, © 2015 Copyright T. Popovic