How to create functors?
Jan Kaliszewski
zuo at chopin.edu.pl
Tue Aug 18 17:30:19 EDT 2009
Dnia 18-08-2009 o 22:51:19 Robert Dailey <rcdailey at gmail.com> napisaĆ(a):
> The example I gave earlier is a bit contrived, the real example
> fundamentally requires a lambda since I am actually passing in local
> variables into the functions the lambda is wrapping. Example:
>
> def MyFunction():
> localVariable = 20
> CreateTask( lambda: SomeOtherFunction( localVariable ) ) # CreateTask
> () executes the functor internally
Lambda in Python is a sintactic sugar for some simple situations. But you
*always* can replace it with def, e.g.:
def MyFunction():
localVariable = 20
def TaskFunction():
SomeOtherFunction(localVariable)
CreateTask(TaskFunction)
If we say about You can also use functools.partial:
import functools
def MyFunction():
localVariable = 20
CreateTask(functools.partial(SomeOtherFunction, localVariable)
...which (especially) makes sense if passed function is supposed to be
callend many times.
> This is more or less like the real scenario I'm working with. There
> are other (more personal) reasons why I prefer to avoid 'def' in this
> case. I want to keep the functor as central to the code that needs it
> as possible to improve code readability.
IMHO def is mostly more readable (see my previous mail...).
> Thanks for the help everyone. I guess in Python 3.0 the print()
> function will not require the import from __future__ to work in this
> particular case?
Print as a function is a standard feature of Py 3.x so it doesn't
require it (see: http://docs.python.org/3.1/whatsnew/3.0.html ).
Regards,
*j
--
Jan Kaliszewski (zuo) <zuo at chopin.edu.pl>
More information about the Python-list
mailing list