[Tutor] nested function definition
Tue Apr 29 04:40:02 2003
On Tue, Apr 29, 2003 at 02:37:54AM -0500, Norvell Spearman wrote:
> In the Python tutorial, section 5.1.3, ``Functional Programming Tools,''
> is the following code:
> >>> def sum(seq):
> ... def add(x,y): return x+y
> ... return reduce(add, seq, 0)
> >>> sum(range(1, 11))
> >>> sum()
> Which are the advantages or disadvantages (if any) of defining one
> function in the definition of another? Defining add(x, y) outside the
> definition of sum(seq) doesn't appear to change the behavior of either.
> Thanks for any answers.
When you are using nested function definitions you define the nested function
in the other function's scope. That is in the example above the function add is
defined in the function sum's local scope. This means that the function add
only can be used inside sum. It is not visible at all outside sum.
The most obvious uses for this is to define small "fire and forget" functions
that you use once inside an other function. For example as above when you need
one function argument to a function. If you plan to use the function add in an
other function you should declare it globally so it can be used everywhere,
otherwise you will have to rewrite your code for that function.
The advantages of this is that if you need a function somewhere (for example as
argument to an other function) you can easily define it locally, use it and
forget about it and you don't have to clutter the global namespace. The
disadvantage (if you can call it that) is that the function isn't usable or
visible outside the enclosing function.
Hope my rambling helps :)