Advanced Python decorators, generators, context managers

Advanced Python

decorators, generators, context managers

Zbigniew Jdrzejewski-Szmek

Institute of Experimental Physics University of Warsaw

Python Summer School St Andrews, September 11, 2011

Version AP_version_2011 This work is licensed under the Creative Commons CC BY-SA 3.0 License.

1 / 63

Outline

1 Generators yield as a statement yield as an expression

2 Decorators Decorators returning the original function Decorators returning a new function Class decorators Examples

3 Exceptions Going further than try..except

4 Context Managers Writing to a file, again Exceptions and context managers Generators as context managers

2 / 63

Generators

Generators

3 / 63

Generator functions

Generators yield as a statement

>>> def gen(): ... print '--start' ... yield 1 ... print '--middle' ... yield 2 ... print '--stop'

>>> g = gen() >>> g.next() --start 1 >>> g.next() --middle 2 >>> g.next() --stop Traceback (most recent call last

... StopIteration

4 / 63

Generators yield as a statement

Simple generator function

def countdown(n): print "Counting down from", n while n > 0: yield n n -= 1

>>> list(countdown(10)) Counting down from 10 [10 9 8 7 6 5 4 3 2 1]

5 / 63

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download