简体   繁体   中英

How interpreter of Python recognize undefined global variable in function?

How interpreter of Python recognize undefined global variable ( a ) in function in the following code ?

def show():
    print(a)

a = 1
show()

Python is interactive language, so it processes each line of code line by line.

Given this, it should throw an error at the line with undefined variable ( print(a) ). However, it works without error.

How does interpreter of Python recognize the undefined varriable( a ) ? Or is it just recognized as letters until show function is called?

I converted the above code to bytecode, but I didn't understand well it...

When you define your function inside a python interpreter, python treats it as a sort of black box. It initializes the variables that are not defined inside and outside the function as free variables . Then, it stores a reference to the function inside the global table (you can access it using globals() ). This global table holds the values for global variables and global function references.
When you define the variable a python stores it inside the global dictionary as well. Just like the function before it.
After that when you call your function, python sees a variable a . It knows that the variable is free , therefore, must be declared inside the global variable by now. Then it looks up the global table and uses the value that is stored.

Python is run line by line, and in saying that, it will skip over the function until the function is called. So even though it's line by line, it's still running afterwards.

Use of global keyword:

To access a global variable inside a function, there is no need to use global keyword. As a is not assigned inside the function, python will look at the global scope. We use global keyword to assign a new value to the global variable.

This example throws an error -

def show():
    a = a + 5
    print(a)

a = 1
show()

Error:

UnboundLocalError: local variable 'a' referenced before assignment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM