[Tutor] Functions returning multiple values

Kent Johnson kent37 at tds.net
Mon Feb 22 15:29:28 CET 2010


On Mon, Feb 22, 2010 at 9:13 AM, Giorgio <anothernetfellow at gmail.com> wrote:

> And, i have some difficulties understanding the other "strange" example in
> that howto. Just scroll down to: "However, the point is that the value
> of x is picked up from the environment at the time when the function is
> defined. How is this useful? Let’s take an example — a function which
> composes two other functions."
> He is working on a function that compose other 2 functions. This is the
> final solution
> def compose(fun1, fun2):
>     def inner(x, fun1=fun1, fun2=fun2):
>         return fun1(fun2(x))
>     return inner
> But also tries to explain why this example:
> # Wrong version
> def compose(fun1, fun2):
>     def inner(x):
>         return fun1(fun2(x))
>     return inner
> def fun1(x):
>     return x + " world!"
> def fun2(x):
>     return "Hello,"
> sincos = compose(sin,cos)  # Using the wrong version
> x = sincos(3)
> Won't work. Now, the problem is that the "inner" function gets fun1 and fun2
> from other 2 functions.
> My question is: why? inner is a sub-function of compose, where fun1 and fun2
> are defined.

It does work:
In [6]: def compose(fun1, fun2):
   ...:     def inner(x):
   ...:         return fun1(fun2(x))
   ...:     return inner
   ...:

In [7]: def fun1(x):
   ...:         return x + " world!"
   ...:

In [8]: def fun2(x):
   ...:         return "Hello,"
   ...:

In [9]: from math import sin, cos

In [10]: sincos = compose(sin,cos)  # Using the wrong version

In [11]:

In [12]: x = sincos(3)

In [13]:

In [14]: x
Out[14]: -0.8360218615377305

That is a very old example, from python 2.1 or before where nested
scopes were not supported. See the note "A Note About Python 2.1 and
Nested Scopes" - that is now the default behaviour.

Kent


More information about the Tutor mailing list