metaclass and customization with parameters

Alex Martelli aleaxit at yahoo.com
Wed Oct 6 13:02:20 EDT 2004


Robert Brewer <fumanchu at amor.org> wrote:
   ...
> > > > >>> class MyClass:
> > > > ...         for i in range(10):
> > > > ...                 def newmethod(self,i=i):
> > > > ...                         print "I'm method #%d" % i
> > > > ...                 newname = "method%d" % i
> > > > ...                 locals()[newname] = newmethod
   ...
> Hmmm. I would have guessed that i isn't available to the class until the
> class statement is finished executing; that is, when newmethod is

Nope, just add a 'print i' before the 'def' here to see this (but even
the use in the i=i should show that already, no?)

> defined, there is not yet any MyClass class object in which to look up
> i. Therefore, newmethod uses LOAD_GLOBAL. But I'm just guessing.

Nope -- there isn't a class object, but there IS a locals dictionary (of
the temporary anonymous function object which wraps the class body's
codeobject during execution of the classbody as part of the 'class'
statement) and that's where i gets looked up in the classbody itself...
but NOT in nested functions -- to keep compatibility with past versions
of Python, is _my_ guess...


Alex



More information about the Python-list mailing list