Can't extend function type
Diez B. Roggisch
deets at nospam.web.de
Fri Oct 7 04:25:22 EDT 2005
Paul Rubin wrote:
> Oh well. I had wanted to be able to define two functions f and g, and
> have f*g be the composition of f and g.
>
> >>> func_type = type(lambda: None)
> >>> class composable_function(func_type):
> ... def __mult__(f,g):
> ... def c(*args, **kw):
> ... return f(g(*args, **kw))
> ... return c
> ...
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> TypeError: Error when calling the metaclass bases
> type 'function' is not an acceptable base type
> >>>
>
> Seems like a wart to me.
Well - function inheritance is not known so far in python - and in no
other language I know.
How do you expect to create f and g, even if above construct would work?
Basdically you want __mult__ being part of f or g when python encounters
something like this
f * g
But then how did you plan to declare f?
def f(composable_function)(x):
pass
obviously won't work.
So the only way to achieve this with current semantics is to make f anf
g objects with a call methods. In that very moment, you're done - as
extending from object is no problem :)
class ComposeableFunction(object):
def __call__(self, *args, **kwargs):
return self.second(self.first(*args, **kwargs))
def __mul__(self, other):
nc = ComposeableFunction()
nc.first = other
nc.second = self
return nc
class f(ComposeableFunction):
def __call__(self, x):
return x * 2
class g(ComposeableFunction):
def __call__(self, x):
return x + 2
f = f()
g = g()
print f(4)
print g(4)
print (f*g)(4)
Diez
More information about the Python-list
mailing list