[Python-3000] defop ?
Guido van Rossum
guido at python.org
Wed Nov 22 21:47:29 CET 2006
On 11/22/06, Antoine Pitrou <solipsis at pitrou.net> wrote:
> 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)
I'm not sure how/when __call__ would be used.
Shouldn't you implement a __get__ descriptor instead?
> 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)
Aha, cool. You forgot to add that now the method name chosen must be
unique. This works fine to describe @defop, and I like it better than
using sys._getframe(). But it doesn't really work for the defop
syntax, unless that makes up a unique (random?) name for each
occurrence.
I guess there's also the issue of invoking it in the wrong context.
Maybe that should be a pychecker issue.
--
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-3000
mailing list