lambda closure question

Steven Bethard steven.bethard at gmail.com
Sat Feb 19 13:10:56 EST 2005


Carl Banks wrote:
> You may not be aware of it, but what you're trying to do is called
> "currying"; you might want to search the Python Cookbook for recipes on
> it.

Or look for "partial function application" which has been argued to be 
the correct term for this use...  Also see PEP 309:

http://www.python.org/peps/pep-0309.html

With an appropriately defined "partial" (I've taken the one from the PEP 
and added the descriptor machinery necessary to make it work as an 
instancemethod):

-------------------- functional.py --------------------
class partial(object):
     def __init__(*args, **kwargs):
         self = args[0]
         try:
             self.fn = args[1]
         except IndexError:
             raise TypeError('expected 2 or more arguments, got ' %
                             len(args))
         self.args = args[2:]
         self.kwargs = kwargs
     def __call__(self, *args, **kwargs):
         if kwargs and self.kwargs:
             d = self.kwargs.copy()
             d.update(kwargs)
         else:
             d = kwargs or self.kwargs
         return self.fn(*(self.args + args), **d)
     def __get__(self, obj, type=None):
         if obj is None:
             return self
         return partial(self, obj)

-------------------------------------------------------

py> class C(object):
...     pass
...
py> def func(self, arg):
...     return arg
...
py> lst = ['a', 'b', 'c']
py> for item in lst:
...     setattr(C, item, functional.partial(func, arg=item))
...
py> c = C()
py> c.a(), c.b(), c.c()
('a', 'b', 'c')

STeVe



More information about the Python-list mailing list