views:

41

answers:

1

Specifically, how are free variables bound at definition for methods of a class? It is probably something like this:

  1. enclosing function (temporary) scope => generate closure
  2. global (permanent) scope => generate no closure (just look it up when the method body executes)
  3. raise UnboundLocalError()

Here are two examples:

globalname = 0
class Test(object):
    def method(self):
        print globalname
        print Test

def outer():
    localname = 1
    class Test(object):
        def method(self):
            print globalname
            print localname
            print Test
    return Test

Test().method.__func__.__closure__
# None
outer()().method.__func__.__closure__
# (<cell at 0xb7d655b4: type object at 0x82412bc>, <cell at 0xb7d655cc: int object at 0x81b20b0>)

I couldn't find much documentation on specifically how they are treated at definition time. Is the above explanation correct?

+2  A: 

Python assumes a variable is local if and only if it is assigned to, within the current code block. So

spam = 0
def ham:
    print( spam )

will make spam a global variable, but

spam = 0
def ham:
    spam = 0
    print( spam )

will make a separate variable, local to ham. A closure grabs all the variables local to the enclosing scope. In your first example, there are no local variables so no closure; in the second, localname is assigned to and thus method is a closure.

As always in Python, there are ways around this assumption. The global keyword declares a variable as global (!), so e.g.

spam = 0
def ham:
    global spam
    spam = 0
    print( spam )

will not be a closure. Py3k introduces the nonlocal keyword, which tells Python to look upwards through the scopes until it finds the variable name and refer to that.

katrielalex
P.S. This is basically the only thing I think is nonintuitive about Python.
katrielalex