type function does not subtype

Lenard Lindstrom nada at nowhere.xxx
Wed Mar 26 14:35:38 EST 2003


"Tim Peters" wrote > [Tim]
> ... how would you create an instance?  the natural "def"
> notation doesn't have a way to specify a base class).

import operator
from new import function

class myfunction(function):
    def __init__(self, fn, x):
        if not operator.isNumberType(x):
            raise TypeError, "x not numeric"
        self.x = x
        newfn = self._wrap(fn)
        super(myfunction, self).__init__(newfn.func_code,
                                         globals(),
                                         newfn.func_name,
                                         newfn.func_defaults,
                                         newfn.func_closure)

    def _wrap(self, fn):
        def newfn(y):
            return fn(self.x + y)
        return newfn

    def setx(self, x):
        if not operator.isNumberType(x):
            raise TypeError, "x not numeric"
        self.x = x

    def getx(self):
        return self.x

def addsomething(x):
    return x + 42

addsomethingmore = myfunction(addsomething, 10)

The example _wrap method is rudimentary. A truly powerfully wrapper would
reproduce the arguments of the function being wrapped. But no, permitting
subtyping of function is not absolutely necessary. The above example works
with a function standin class. So I suppose all I am really suggesting is an
abstract function class, a contract saying a callable object will stand up
to introspection. Then the inspect module functions can check for this as
well as type function.

--
Lenard Lindstrom
"<%s@%s.%s>" % ("len-l.", "telus", "net")







More information about the Python-list mailing list