dynamic functions

Gustavo Cordova gcordova at hebmex.com
Thu May 16 10:04:38 EDT 2002


There is a way to do this using lambda,
except that you have to reference
explicitly the function you're going
to include, to bind a reference to it
locally to an argument of the lambda.

>>> func = lambda x: x == 'something'
>>> func = lambda x, f=func: f(x) or x == 'another'
>>> func = lambda x, f=func: f(x) or x == 'look here'
>>>
>>> f(1)
0
>>> f(3.141592654)
0
>>> f('something')
1
>>> f('another')
1
>>> f('look here')
1


This works, while the others didn't, because we're
binding a reference to func (whatever it may be at
the time of compilation) using a default argument
for the subsequent definition of func, and obviating
the need to look up 'func' upon the execution of
the lambda expressions.

Anyway, it might be useful.

-gustavo





More information about the Python-list mailing list