Why is 'ord' treated as an unassigned variable here?

I hope this is not a duplicate (and at the same time it is difficult to say, given the number of questions with such errors, but which are the main errors), but I do not understand what is happening here.

def f():
    c = ord('a')

f()

It works, there is no error ( ordconverts a character to ASCII code, it is built-in). Now:

if False:
    ord = None
def f():
    c = ord('a')

f()

It also starts, an error ( orddoes not overwrite, the condition is always false). Now:

def f():
    if False:
        ord = None
    c = ord('a')

f()

I get (in the line where c = ord('a'))

UnboundLocalError: local variable 'ord' referenced before assignment

It seems that just a reference to the left operand makes it a local variable, even if the code is not running.

Obviously, I can get around this, but I was very surprised, given that the dynamic aspect of python allows you to define an integer variable and define it as a string on the next line.

, , if?

-, - -, ?

( Python 2.7 Python 3.4)

+4
2

, -; .

Python , . , ( , ), ( global nonlocal). Binding and Naming .

, , , , , . ( : , Python , , , . , , , ...)

, -, if False: ord=None, ord - .

: ord = , ord , - , , , , , UnboundLocalError.


:

  • , ,
  • , ,
  • , ,
  • , ,

, - . LEGB scoping done Lisp -style , ord , Python . , <23 > , "undefined" , , , , Python , , , .


, :

CPython , . . co_varnames, ord - co_varnames[1]. LOAD_FAST 1 STORE_FAST 1 LOAD_NAME STORE_GLOBAL . LOAD_FAST 1 f_locals[1] . f_locals NULL Python, a LOAD_FAST NULL, UnboundLocalError.

+6

, , :

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

a LOAD_FAST, .

ord None , LOAD_GLOBAL:

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
+1

Source: https://habr.com/ru/post/1695481/


All Articles