On 12/29/2013 12:33 PM, Steven D'Aprano wrote:
def adder_factory(n):
def plus(arg):
return arg + n
return plus # returns the function itself
If you call adder_factory(), it returns a function:
py> adder_factory(10)
<function adder_factory.<locals>.plus at 0xb7af6f5c>
What good is this? Watch carefully:
py> add_two = adder_factory(2)
py> add_three = adder_factory(3)
py> add_two(100)
102
py> add_three(100)
103
The factory lets you programmatically create functions on the fly.
add_two() is a function which adds two to whatever argument it gets.
add_three() is a function which adds three to whatever argument it gets.
We can create an "add_whatever" function without knowing in advance what
"whatever" is going to be:
py> from random import randint
py> add_whatever = adder_factory(randint(1, 10))
py> add_whatever(200)
205
py> add_whatever(300)
305
So now you see the main reason for nested functions in Python: they let
use create a function where you don't quite know exactly what it will do
until runtime. You know the general form of what it will do, but the
precise details aren't specified until runtime.
little complement:
Used that way, a function factory is the programming equivalent of parametric
functions, or function families, in maths:
add : v --> v + p
Where does p come from? it's a parameter (in the sense of maths), or an "unbound
varaible"; while 'v' is the actual (bound) variable of the function. Add
actually defines a family of parametric functions, each with its own 'p'
parameter, adding p to their input variable (they each have only one). The
programming equivalent of this is what Steven demonstrated above. However, there
is much confusion due to (funny) programming terminology:
* a math variable is usually called parameter
* a math parameter is usually called "upvalue" (not kidding!)
* a parametric function, or function family (with undefinite param) is called
function factory (this bit is actually semantically correct)
* a member of function family (with definite param) is called (function) closure
(every parametric expression is actually a closure, eg "index = index + offset",
if offset is not locally defined)
Denis
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor