def...return
Functions are declared using def
. Here is a typical Python function:
>>> def f(a, b):
... return a + b
...
>>> print f(4, 2)
6
There is no need (or way) to specify types of the arguments or the return type(s). In this example, a function f
is defined that can take two arguments.
Functions are the first code syntax feature described in this chapter to introduce the concept of scope, or namespace. In the above example, the identifiers a
and b
are undefined outside of the scope of function f
:
>>> def f(a):
... return a + 1
...
>>> print f(1)
2
>>> print a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
Identifiers defined outside of function scope are accessible within the function; observe how the identifier a
is handled in the following code:
>>> a = 1
>>> def f(b):
... return a + b
...
>>> print f(1)
2
>>> a = 2
>>> print f(1) # new value of a is used
3
>>> a = 1 # reset a
>>> def g(b):
... a = 2 # creates a new local a
... return a + b
...
>>> print g(2)
4
>>> print a # global a is unchanged
1
If a
is modified, subsequent function calls will use the new value of the global a
because the function definition binds the storage location of the identifier a
, not the value of a
itself at the time of function declaration; however, if a
is assigned-to inside function g
, the global a
is unaffected because the new local a
hides the global value. The external-scope reference can be used in the creation of closures:
>>> def f(x):
... def g(y):
... return x * y
... return g
...
>>> doubler = f(2) # doubler is a new function
>>> tripler = f(3) # tripler is a new function
>>> quadrupler = f(4) # quadrupler is a new function
>>> print doubler(5)
10
>>> print tripler(5)
15
>>> print quadrupler(5)
20
Function f
creates new functions; and note that the scope of the name g
is entirely internal to f
. Closures are extremely powerful.
Function arguments can have default values, and can return multiple results:
>>> def f(a, b=2):
... return a + b, a - b
...
>>> x, y = f(5)
>>> print x
7
>>> print y
3
Function arguments can be passed explicitly by name, and this means that the order of arguments specified in the caller can be different than the order of arguments with which the function was defined:
>>> def f(a, b=2):
... return a + b, a - b
...
>>> x, y = f(b=5, a=2)
>>> print x
7
>>> print y
-3
Functions can also take a runtime-variable number of arguments:
>>> def f(*a, **b):
... return a, b
...
>>> x, y = f(3, 'hello', c=4, test='world')
>>> print x
(3, 'hello')
>>> print y
{'c':4, 'test':'world'}
Here arguments not passed by name (3, ‘hello’) are stored in the tuple a
, and arguments passed by name (c
and test
) are stored in the dictionary b
.
In the opposite case, a list or tuple can be passed to a function that requires individual positional arguments by unpacking them:
>>> def f(a, b):
... return a + b
...
>>> c = (1, 2)
>>> print f(*c)
3
and a dictionary can be unpacked to deliver keyword arguments:
>>> def f(a, b):
... return a + b
...
>>> c = {'a':1, 'b':2}
>>> print f(**c)
3
lambda
lambda
provides a way to create a very short unnamed function very easily:
>>> a = lambda b: b + 2
>>> print a(3)
5
The expression “lambda
[a]:[b]“ literally reads as “a function with arguments [a] that returns [b]“. The lambda
expression is itself unnamed, but the function acquires a name by being assigned to identifier a
. The scoping rules for def
apply to lambda
equally, and in fact the code above, with respect to a
, is identical to the function declaration using def
:
>>> def a(b):
... return b + 2
...
>>> print a(3)
5
The only benefit of lambda
is brevity; however, brevity can be very convenient in certain situations. Consider a function called map
that applies a function to all items in a list, creating a new list:
>>> a = [1, 7, 2, 5, 4, 8]
>>> map(lambda x: x + 2, a)
[3, 9, 4, 7, 6, 10]
This code would have doubled in size had def
been used instead of lambda
. The main drawback of lambda
is that (in the Python implementation) the syntax allows only for a single expression; however, for longer functions, def
can be used and the extra cost of providing a function name decreases as the length of the function grows. Just like def
, lambda
can be used to curry functions: new functions can be created by wrapping existing functions such that the new function carries a different set of arguments:
>>> def f(a, b): return a + b
>>> g = lambda a: f(a, 3)
>>> g(2)
5
There are many situations where currying is useful, but one of those is directly useful in web2py: caching. Suppose you have an expensive function that checks whether its argument is prime:
>>> def isprime(number):
... for p in range(2, number):
... if (number % p) == 0:
... return False
... return True
This function is obviously time consuming.
Suppose you have a caching function cache.ram
that takes three arguments: a key, a function and a number of seconds.
>>> value = cache.ram('key', f, 60)
The first time it is called, it calls the function f()
, stores the output in a dictionary in memory (let’s say “d”), and returns it so that value is:
>>> value = d['key'] = f()
The second time it is called, if the key is in the dictionary and not older than the number of seconds specified (60), it returns the corresponding value without performing the function call.
>>> value = d['key']
How would you cache the output of the function isprime for any input? Here is how:
>>> number = 7
>>> seconds = 60
>>> print cache.ram(str(number), lambda: isprime(number), seconds)
True
>>> print cache.ram(str(number), lambda: isprime(number), seconds)
True
The output is always the same, but the first time cache.ram
is called, isprime
is called; the second time it is not.
Python functions, created with either
def
orlambda
allow re-factoring existing functions in terms of a different set of arguments.cache.ram
andcache.disk
are web2py caching functions.