Name
The def Statement
Synopsis
defname
([arg
,arg
=value
,... *arg
, **arg
]):suite
Makes new functions. Creates a function object and assigns it to
variable name
. Each call to a function
object generates a new, local scope, where assigned names are local
to the function call by default (unless declared global). See also Section 1.9 later in the book.
Arguments are passed by assignment; in a def
header, they may be defined by any of the formats in Table 1-14.
Table 1-14. Argument definition formats
Argument format |
Interpretation |
---|---|
arg |
Simple name, matched by name or position |
arg=value |
Default value if |
*arg |
Collects extra positional |
**arg |
Collects extra keyword |
Mutable default argument values are evaluated once at
def
statement time, not on each call, so may
retain state between calls (but classes are better state-retention
tools):
>>> def grow(a, b=[]): ... b.append(a) ... print b ... >>> grow(1); grow(2) [1] [1, 2]
lambda expressions
Functions may also be created with the lambda
expression form: lambda
arg
,
arg
,...:
expression
. In lambda
,
arg
is as in def
,
expression
is the implied return value,
and the generated function is simply returned as the
lambda
result to be called later, instead of being
assigned to a variable. Because lambda
is an
expression, not a statement, it may be used in places that a
def
cannot be (e.g., within an argument list of a
call).
Get Python Pocket Reference, Second 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.