Re: Can't extend function type
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

Re: Can't extend function type

From: Diez B. Roggisch <deets@nospam.web.de>
Date: Fri Oct 07 2005 - 10:25:22 CEST

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
Received on Sat Oct 15 04:15:05 2005