python: how binding works

前端 未结 5 1639
难免孤独
难免孤独 2021-01-04 13:26

I am trying to understand, how exactly variable binding in python works. Let\'s look at this:

def foo(x):
    def bar():
        print y
    return bar

y =          


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-04 14:14

    The issue that you are alluding to is one of lexical vs dynamic scoping of variables in python. To be explicit, python defines the following four scopes.

    1. The innermost scope, which is searched first, contains the local names
    2. The scopes of any enclosing functions, which are searched starting with the nearest enclosing scope, contains non-local, but also non-global names
    3. the next-to-last scope contains the current module’s global names
    4. the outermost scope (searched last) is the namespace containing built-in names

    In the first example, where "y" is defined outside of the function bar, python searched for the innermost scope and moved up the chain until it found the global variable "y" in the module

    In the second example, where "x" is being defined by function foo(x), x belongs to the scope of an enclosing function, when its being printed inside bar. In pure terms, a closure has been defined.

    For further study on scoping in python, I found the following article a great read

提交回复
热议问题