When is the existence of nonlocal variables checked?

后端 未结 2 1106
刺人心
刺人心 2020-12-06 17:53

I am learning Python and right now I am on the topic of scopes and nonlocal statement. At some point I thought I figured it all out, but then nonlocal came and broke everyth

2条回答
  •  一向
    一向 (楼主)
    2020-12-06 18:21

    First, understand that python will check your module's syntax and if it detects something invalid it raises a SyntaxError which stops it from running at all. Your first example raises a SyntaxError but to understand exactly why is pretty complicated although it is easier to understand if you know how __slots__ works so I will quickly introduce that first.


    When a class defines __slots__ it is basically saying that the instances should only have those attributes so each object is allocated memory with space for only those, trying to assign other attributes raises an error

    class SlotsTest:
        __slots__ = ["a", "b"]
    
    x = SlotsTest()
    
    x.a = 1 ; x.b = 2
    x.c = 3 #AttributeError: 'SlotsTest' object has no attribute 'c'
    

    The reason x.c = 3 can't work is that there is no memory space to put a .c attribute in.

    If you do not specify __slots__ then all instances are created with a dictionary to store the instance variables, dictionaries do not have any limitations on how many values they contain

    class DictTest:
        pass
    
    y = DictTest()
    y.a = 1 ; y.b = 2 ; y.c = 3
    print(y.__dict__) #prints {'a': 1, 'b': 2, 'c': 3}
    

    Python functions work similar to slots. When python checks the syntax of your module it finds all variables assigned (or attempted to be assigned) in each function definition and uses that when constructing frames during execution.

    When you use nonlocal x it gives an inner function access to a specific variable in the outer function scope but if there is no variable defined in the outer function then nonlocal x has no space to point to.

    Global access doesn't run into the same issue since python modules are created with a dictionary to store its attributes. So global x is allowed even if there is no global reference to x

提交回复
热议问题