How to create functors?

Robert Dailey rcdailey at gmail.com
Tue Aug 18 17:50:22 EDT 2009


On Aug 18, 4:30 pm, "Jan Kaliszewski" <z... at chopin.edu.pl> wrote:
> 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.

Good point, I'm too used to C++ (Can't define functions in local
scope). I never thought of that. In C++ I use boost::bind() fairly
extensively and I carry over those habits to python.

>
> IMHO def is mostly more readable (see my previous mail...).
>
> 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).

Thanks for the info.



More information about the Python-list mailing list