开发者

What is the search order for free variables in Python?

开发者 https://www.devze.com 2023-01-09 09:55 出处:网络
Specifically, how are free variables bound at definition for methods of a class?It is probably something like this:

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 e开发者_运维百科xecutes)
  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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消