metaclass and customization with parameters

Gustavo Niemeyer niemeyer at conectiva.com
Wed Oct 6 10:20:52 EDT 2004


Hello Alex!

> > Of course, in your example, not using the 'i=i' trick would be a
> > problem, since the 'i' variable is lost, and inside the method a
> > global is looked for, creating an error.
>
> True, the opcode for i is indeed a LOAD_GLOBAL.  Why _that_ should be
> the case is anything but an 'of course' to _me_, though, as we just

Sorry, my intention was to say that removing "i=i" would be
clearly a problem, not that the whole issue was clear.

> showed that i is a +local+.  newmethod is not seen as a nested function
> of the anonymous function built from the codeobject's that's the
> classbody.  I _think_ there's some adhoccery in the Python compiler (not
> the easiest part of Python to read and understand, so I apologize for
> any potential confusion here) to specifically ensure that -- I guess
> it's for backwards compatibility with old Python versions which didn't
> have nested scopes, otherwise any barename in a method would refer first

In this case, the external closure must be the global scope, otherwise,
code like this:

class C:
    var = 1
    def method(self):
      print var

Would show self.__class__.var, when it shouldn't.

> to the classbody (acting as its 'outer function') which could shadow
> globals.  A bit confusing for an "of course", nevertheless;-).

Again, I'm sorry. My "of course" should be more closely related to the
fact that removing "i=i" would be a problem, as was my original
intention.  Even if the internal 'i' was bound to a closure, as you
seem to belive would be the expected behavior, the OP's code would end
up doing the wrong thing.

Here is an example:

>>> def func():
...   l = []
...   for i in range(10):
...     def subfunc():
...       print i
...     l.append(subfunc)
...   return l
...
>>> for subfunc in func():
...   subfunc()
...
9
9
9
9
[...]

-- 
Gustavo Niemeyer
http://niemeyer.net



More information about the Python-list mailing list