[Python-3000] defop ?
Antoine Pitrou
solipsis at pitrou.net
Wed Nov 22 21:40:53 CET 2006
Le mercredi 22 novembre 2006 à 11:52 -0800, Guido van Rossum a écrit :
> but how on earth is the defop syntax of the @defop decorator going to
> generate this? I can't see any way to implement it without having
> access to the class object, but that doesn't exist yet at the time
> defop or @defop executes. The best I can think of is for @defop to use
> sys._getframe() to access the dict in which the class body is being
> evaluated, find or create a list __defop_deferred__ there, and append
> the tuple(<expr>, <function>) to it. Then the metaclass (i.e., type)
> should look for this list, and if it exists, do the registrations.
Let's say @defop is implemented as follows:
class DefOpDescriptor:
def __init__(self, genfunc, implfunc):
self.genfunc = genfunc
self.implfunc = implfunc
def __call__(self, *args, **kargs):
# Directly call the implementation (why not)
self.implfunc(*args, **kargs)
def __with_class__(self, cls):
""" Register self.implfunc as an implementation
of generic function self.genfunc for class cls. """
self.genfunc.when(cls)(self.implfunc)
def defop(genfunc):
def decorate(implfunc):
return DefOpDescriptor(genfunc, implfunc)
return decorate
And then in the metaclass (i.e., type), if an attribute "attr" has a
__with_class__ method, execute attr.__with_class__(cls).
(this could perhaps be used for other things than defop)
More information about the Python-3000
mailing list