Lambda forms and scoping

andrew cooke andrew at acooke.org
Mon Mar 23 01:38:01 CET 2009


alex goretoy wrote:
> Sorry to have confused yall. What I meant was that you can do something
> like
> this, where the fucntion isn't called until it is bount to () with the
> right
> params
>
>>>> def a():
> ...     print "inside a"
> ...
>>>> def b():
> ...     print "inside b"
> ...
>>>> def c(a,b):
> ...     a()
> ...     b()
> ...
>>>> d={c:(a,b)}
>>>> d[c][0]()
> inside a
>>>> d[c][1]()
> inside b
>>>> d[c(d[c][0],d[c][1])]
> inside a
> inside b
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> KeyError: None
>
> where function a and b are bound in function c


what on earth are you talking about?  you would get exactly the same
result with:

>>> def alpha():
...   print('in alpha')
...
>>> def beta():
...   print('in beta')
...
>>> def c(a, b):
...   a()
...   b()
...
>>> bollox=42
>>> d={bollox:(alpha, beta)}
>>> d[bollox][0]()
in alpha
>>> d[bollox][1]()
in beta
>>> d[c(d[bollox][0](),d[bollox][1]())]
in alpha
in beta
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in c
TypeError: 'NoneType' object is not callable

which is just the combination of:

>>> c(d[bollox][0],d[bollox][1])
in alpha
in beta
>>> d[None]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: None

"d" is only used, in "d[c(d[bollox][0](),d[bollox][1]())]" as a completely
normal lookup via bollox, and then to give an error when looking-up "None"
(the return value from c).

there is no special "binding" process.

andrew





More information about the Python-list mailing list