46
|
Python Pocket Reference
is roughly equivalent to the following nondecorator code:
def f(): ...
f = A(B(C(f)))
Decorators must appear on the line before a function defini-
tion, and cannot be on the same line (meaning
@A def f(): ...
is illegal). Decorators can only be applied to function defini-
tions, either at the module level or inside a class; they cannot
be applied to class definitions. Decorators also take argu-
ment lists:
@foo(1,2,3)
def f(): ...
In this case foo must be a function returning a function
(known as a metafunction).
The return Statement
return [expression]
The return statement exits the enclosing function and
returns an
expression value as the result of the call to the
function. The
expression defaults to None if it’s omitted.
Hint: return a tuple for multiple-value function results.
The yield Statement
yield expression
The yield statement suspends function state and returns an
expression. On the next iteration, the function’s prior state is
restored, and control resumes immediately after the
yield
statement. Use a return statement with no value to end the
iteration, or simply fall off the end of the function:
def generate_ints(N):
for i in xrange(N):
yield i
The yeild statement is standard as of Version 2.3 and later;
in Version 2.2, enable it with
from __future__ import
generators
.

Get Python Pocket Reference, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.