Why doesn't Python's nonlocal keyword like the global scope?

前端 未结 4 1296
一生所求
一生所求 2021-02-01 21:08

In Python 3.3.1, this works:

i = 76

def A():
    global i
    i += 10

print(i) # 76
A()
print(i) # 86

This also works:

def en         


        
4条回答
  •  [愿得一人]
    2021-02-01 21:27

    It depends upon the Boundary cases:

    nonlocals come with some senstivity areas which we need to be aware of. First, unlike the global statement, nonlocal names really must have previous been assigned in an enclosing def's scope when a nonlocal is evaluated or else you'll get an error-you cannot create them dynamically by assigning them anew in the enclosing scope. In fact, they are checked at function definition time before either or nested function is called

    >>>def tester(start):
          def nested(label):
             nonlocal state   #nonlocals must already exist in enclosing def!
             state = 0
             print(label, state)
          return nested
    SyntaxError: no binding for nonlocal 'state' found
    
    >>>def tester(start):
          def nested(label):
              global state   #Globals dont have to exits yet when declared
              state = 0      #This creates the name in the module now
              print(label, state)
          return nested
    
    >>> F = tester(0)
    >>> F('abc')
    abc 0
    >>> state
    0
    

    Second, nonlocal restricts the scope lookup to just enclosing defs; nonlocals are not looked up in the enclosing module's global scope or the built-in scope outside all def's, even if they are already there:

    for example:-

    >>>spam = 99
    >>>def tester():
          def nested():
             nonlocal spam  #Must be in a def, not the module!
             print('current=', spam)
             spam += 1
          return nested
    SyntaxError: no binding for nonlocal 'spam' found
    

    These restrictions make sense once you realize that python would not otherwise generally know enclosing scope to create a brand-new name in. In the prior listing, should spam be assigned in tester, or the module outside? Because this is ambiguous, Python must resolve nonlocals at function creation time, not function call time.

提交回复
热议问题