function operators
Hans Nowak
wurmy at earthlink.net
Mon Nov 26 21:12:55 EST 2001
"James A. H. Skillen" wrote:
>
> Has anyone ever wished that Python had operators defined on functions?
> For example, suppose you want the function f(x) = cos(x) + sin(x).
> You could do:
>
> def f(x):
> return cos(x) + sin(x)
>
> or
>
> f = lambda x: cos(x) + sin(x)
>
> but wouldn't:
>
> f = cos + sin
>
> be *much* nicer?
Here's some code that implements this behavior... I didn't test it very
well, but the general idea seems to work. Requires 2.1.
---begin---
# composable_functions.py
from __future__ import nested_scopes
class ComposableFunction:
def __init__(self, f):
self.f = f
def __call__(self, *args, **kwargs):
return apply(self.f, args, kwargs)
def __add__(self, other):
assert isinstance(other, ComposableFunction)
def glue(*args):
return self.f(*args) + other.f(*args)
return glue
def test1():
import math
sin = ComposableFunction(math.sin)
cos = ComposableFunction(math.cos)
print sin(100), cos(100)
sincos = sin + cos
print sincos
print sin(100) + cos(100)
print sincos(100)
if __name__ == "__main__":
test1()
---end---
More information about the Python-list
mailing list