Specifically, how are free variables bound at definition for methods of a class? It is probably something like this:
- enclosing function (temporary) scope => generate closure
- global (permanent) scope => generate no closure (just look it up when the method body executes)
- 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?
Python assumes a variable is local if and only if it is assigned to, within the current code block. So
will make spam a global variable, but
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,localnameis assigned to and thusmethodis a closure.As always in Python, there are ways around this assumption. The
globalkeyword declares a variable as global (!), so e.g.will not be a closure. Py3k introduces the
nonlocalkeyword, which tells Python to look upwards through the scopes until it finds the variable name and refer to that.