Partially evaluated functions
Andrew Dalke
dalke at acm.org
Tue Jun 19 21:26:35 EDT 2001
Venkatesh Prasad Ranganath asked:
>Is partially evaluated functions possible in python? If there has been a
>discussion about it, where can I find the jist of the discussion?
>
>def conv(a, b, c):
> return (a + b) * c
>
>faren2cel = conv(b = -32, c = 5 / 9)
Here's a hack solution for unnamed parameters:
class Curry:
def __init__(self, func, *args):
self.func = func
self.args = args
self.n = func.func_code.co_argcount
def __call__(self, *args):
args = self.args + args
if len(args) == self.n:
return apply(self.func, args)
if len(args) > self.n:
raise TypeError("too many arguments; expected %d, got %d" % \
(self.n, len(args)))
return apply(Curry, (self.func,) + args)
>>> def conv(a, b, c):
... return (b + c) * a
...
>>> conv = Curry(conv)
>>> f2c = conv(5./9., -32)
>>> f2c(32)
0.0
>>> f2c(-40)
-40.0
>>> f2c(82)
27.7777777778
>>> f2c(212)
100.0
>>>
This only works for Python functions since straight C interface code
doesn't provide enough information to know how many parameters are
needed.
I leave as an exercise for the student on how to support named arguments.
(Hint: see the various doc extraction programs on how to get a list of
parameter names and default values. It's only tedious not hard.)
:)
Andrew
dalke at acm.org
More information about the Python-list
mailing list