why is 'ord' seen as an unassigned variable here?

后端 未结 2 507
隐瞒了意图╮
隐瞒了意图╮ 2020-12-07 03:19

I hope it\'s not a duplicate (and at the same time it\'s difficult to tell, given the amount of questions with such errors, but which are basic mistakes), but I don\'t under

2条回答
  •  庸人自扰
    2020-12-07 03:48

    Just to demonstrate what's going on with the compiler:

    def f():
        if False:
            ord = None
        c = ord('a')
    
      4           0 LOAD_FAST                0 (ord)
                  3 LOAD_CONST               1 ('a')
                  6 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
                  9 STORE_FAST               1 (c)
                 12 LOAD_CONST               0 (None)
                 15 RETURN_VALUE
    

    Access to a is using LOAD_FAST, which is used for local variables.

    If you set ord to None outside your function, LOAD_GLOBAL is used instead:

    if False:
        ord = None
    def f():
        c = ord('a')
    
      4           0 LOAD_GLOBAL              0 (ord)
                  3 LOAD_CONST               1 ('a')
                  6 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
                  9 STORE_FAST               0 (c)
                 12 LOAD_CONST               0 (None)
                 15 RETURN_VALUE
    

提交回复
热议问题