type function does not subtype
Lenard Lindstrom
nada at nowhere.xxx
Sat Mar 29 14:59:53 EST 2003
"Lenard Lindstrom" wrote
> Would someone please explain why subtyping of type 'function' is not
> permitted in Python 2.3?
This is an update on subtyping type function. The module below defines a
subtype of a function with one static variable that can be changed by method
setx().
# functionsubtype, Demonstrates function subtyping
import operator
from new import function
class myfunction(function):
def __new__(cls, fn, x):
# Function objects are initialized by __new__.
if not operator.isNumberType(x):
raise TypeError, "x not numeric"
mutable_x = [x]
newfn = cls._wrap(fn, mutable_x)
self = function.__new__(cls,
newfn.func_code,
globals(),
newfn.func_name,
newfn.func_defaults,
newfn.func_closure)
self.mutable_x = mutable_x
return self
def _wrap(fn, mutable_x):
def newfn(y):
return fn(mutable_x[0] + y)
return newfn
_wrap = staticmethod(_wrap)
def setx(self, x):
if not operator.isNumberType(x):
raise TypeError, "x not numeric"
self.mutable_x[0] = x
def getx(self):
return self.mutable_x[0]
The following session used the above module.
Python 2.3a2 (#39, Mar 28 2003, 15:43:16) [MSC v.1200 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from functionsubtype import myfunction
>>> def fn(x):
... return x
...
>>> addx = myfunction(fn, 42)
>>> addx(0)
42
>>> addx.getx()
42
>>> addx.setx(99)
>>> addx(0)
99
>>> addx(100)
199
>>> type(addx)
<class 'functionsubtype.myfunction'>
>>> isinstance(addx, type(fn))
True
>>> import inspect
>>> inspect.getargspec(addx)
(['y'], None, None, None)
Python 2.3a2 provides a tp_new slot method for function. I used type tuple
as a model for filling in the rest. Preliminary profiling shows a call to a
function subtype is 13 percent slower that a function call, but 16 percent
faster that calling an object with a static __call__ method.
Most of the above session can be done without subtyping function. Only
isinstance() and inspect.getargspec() would fail. If anything comes from
these postings it should be a more general purpose form of
inspect.getargspec() which handles all callable objects.
Thanks to everyone who answered my questions and participated in the
discussion that followed.
--
Lenard Lindstrom
"<%s@%s.%s>" % ("len-l.", "telus", "net")
More information about the Python-list
mailing list