Partially evaluated functions

Cliff Crawford cjc26 at nospam.cornell.edu
Tue Jun 19 23:37:09 EDT 2001


* Neil Schemenauer <nas at python.ca> menulis:
| This works in 2.1 (a little more magic is needed for older
| Pythons):
| 
| >>> from __future__ import nested_scopes
| >>> def conv(b, c):
| ...   return lambda a: (a + b) * c
| ... 
| >>> faren2cel = conv(-32., 5./9)
| >>> faren2cel
| <function <lambda> at 0x810f45c>
| >>> faren2cel(10)
| -12.222222222222223
| >>> faren2cel(-40)
| -40.0

Or you could do

faren2cel = lambda a: conv(a, -32.0, 5.0/9)

if you didn't want to redefine conv().

Another way to do it would be to create a class which can keep track of
which arguments have already been assigned to, something like this:

import inspect
class Schoenfinkelizer:
    def __init__(self, func, **kwargs):
        self.func = func
        self.args = {}
        # get list of argument names
        self.argnames = inspect.getargspec(func)[0]
        for arg in self.argnames:
            self.args[arg] = kwargs.get(arg, None)
    def __call__(self, *remainingargs):
        args = []
        for arg in self.argnames:
            if self.args[arg]:
                args.append(self.args[arg])
            else:
                args.append(remainingargs[0])
                # hopefully the right number of args was passed!
                remainingargs = remainingargs[1:]
        return apply(self.func, args)

faren2cel = Schoenfinkelizer(conv, b=-32.0, c=5.0/9)
faren2cel(-40)


But that would be overkill..:)


-- 
Cliff Crawford                   http://www.sowrong.org/
"Cliff, you're a god.  I want to bear your child." -- Ed



More information about the Python-list mailing list