What is Python variable scope

When a variable is defined in the program, the variable has a scope, and the scope of the variable is called its scope.

There are two types of variables according to the location of the defined variables:

  1. Local variables: Variables defined in a function, including parameters, are called local variables.
  2. Global variables: Variables defined outside the function and in the global scope are called global variables.

When each function is executed, the system allocates a "temporary memory space" for the function, and all local variables are stored in this temporary memory space. When the function is executed, this memory space is released, and these local variables become invalid. Therefore, the local variables can no longer be accessed after leaving the function.

Global variables mean that they can be accessed in all functions.

Whether in the local scope of the function or in the global scope, there may be multiple variables, and each variable "holds" the value of the variable. From this point of view, whether in the local scope or the global scope, these variables and their values are like an "invisible" dictionary, where the variable name is the key of the dictionary, and the variable value is the value of the dictionary.

In fact, Python provides the following three utility functions to get the "variable dictionary" in the specified range:

globals(): This function returns a "variable dictionary" composed of all variables in the global scope.

locals(): This function returns a "variable dictionary" composed of all variables in the current local scope.

vars(object): Get the "variable dictionary" composed of all variables in the specified object range. If the object parameter is not passed in, vars() and locals() have exactly the same effect.

globals() and locals() seem completely different, but they are actually related. There are roughly two points about the difference and connection between these two functions:

locals() always gets the "variable dictionary" composed of all the variables in the current local scope. Therefore, if you call the locals() function in the global scope (outside the function), you will also get the “variables” composed of all the variables in the global scope. Dictionary"; and globals() always gets the "variable dictionary" composed of all variables in the global scope no matter where it is executed.

Generally speaking, the "variable dictionary" obtained using locals() and globals() should only be accessed and should not be modified. But in fact, whether you use globals() or locals() to obtain the "variable dictionary" in the global scope, it can be modified, and this modification will really change the global variable itself: but the locals obtained through locals() The "variable dictionary" within the scope will not affect local variables even if it is modified.

The following program demonstrates how to use the locals() and globals() functions to access the "variable dictionary" in the local scope and the global scope:

def test():
 age =20
 # Direct access to age local variables
 print(age) #Output 20
 # Access "variable array" in the local scope of the function
 print(locals()) # {'age':20}
 # Access the age variable through the "variable array" in the local scope of the function
 print(locals()['age']) # 20
 # Change the value of age variable through the "variable array" in the local scope of the locals function
 locals()['age']=12
 # Access the value of the age variable again
 print('xxx', age) #Still output 20
 # Modify x global variables through the globals function
 globals()['x']=19
x =5
y =20print(globals()) # {...,'x':5,'y':20}
# Use the locals function in the global access to access the "variable array" of global variables
print(locals()) # {...,'x':5,'y':20}
# Direct access to x global variables
print(x) # 5
# Access x global variables through the "variable array" of global variables
print(globals()['x']) # 5
# Assign values to x global variables through the "variable array" of global variables
globals()['x']=39print(x) #Output 39
# Use the locals function to assign values to x global variables in the global scope
locals()['x']=99print(x) #Output 99

It can be clearly seen from the above program that the locals() function is used to access the "variable dictionary" composed of all variables in a specific scope, and the globals() function is used to access the "variable dictionary" composed of global variables in the global scope. .

Global variables can be accessed in all functions by default, but if a variable with the same name as the global variable is defined in the function, the local variable will hide the global variable. For example, the following program:

name ='Charlie'
def test():
 # Direct access to the name global variable
 print(name) # Charlie
test()print(name)

In the above program, line 4 directly accesses the name variable, which is allowed, and the program will output Charlie at this time. If you add the following line of code after this:

name ='Monkey King'

Run the program again, you will see the following error:

UnboundLocalError : local variable ‘name' referenced before assignment

This error indicates that the name variable accessed by the bold code has not been defined. What is the reason for this? This is precisely because the program adds a line of code "name='Sun Wukong'" in the test() function.

Python syntax stipulates that when assigning values to non-existent variables within a function, the default is to redefine new local variables. Therefore, this line of code is equivalent to redefining the name local variable, so that the name global variable is masked, so the program will report an error.

To avoid this problem, you can modify the above program in the following two ways:

Access to obscured global variables. If you want the program to still be able to access the name global variable, and you can redefine the name local variable in the function, that is, you can access the masked global variable in the function, you can use the globals() function to achieve this, change the above program The following form is sufficient:

name ='Charlie'
def test():
 # Direct access to the name global variable
 print(globals()['name']) # Charlie
 name ='Monkey King'test()print(name) # Charlie

Declare global variables in the function. In order to avoid assigning values to global variables in functions (not redefining local variables), you can use the global statement to declare global variables. Therefore, the program can be changed to the following form:

name ='Charlie'
def test():
 # Declare that name is a global variable, and subsequent assignment statements will not redefine local variables
 global name
 # Direct access to the name global variable
 print(name) # Charlie
 name ='Monkey King'test()print(name) # Monkey King

After adding the "global name" declaration, the program will treat the name variable as a global variable, which means that the statement assigning a value to the name after the test() function only assigns a value to the global variable, rather than redefining the local variable.

Knowledge point expansion:

Variable scope of python3

**Scope: **refers to the text area of the python program that the namespace can directly access, where'directly accessible' means: a reference to a name (unqualified), it will try to find the name in the namespace;

So far, this article on what is the scope of Python variables is introduced. For more detailed explanations of the scope of Python variables, please search for the previous articles of ZaLou.Cn or continue to browse the related articles below. Hope you will support ZaLou more in the future. Cn!

Recommended Posts

What is Python variable scope
What is the scope of python variables
What is introspection in python
What is object-oriented in python
In-depth understanding of Python variable scope
What is list comprehension in python
What is the use of Python
Python 3.9 is here!
What is the id function of python
What system is good for self-study python
What is the prospect of python development
What is a sequence table in Python
Is a number in python a variable type
What is the function body of python
What is the function of adb in python
What is the difference between python and pycharm
Why python is popular
Python is short-crawling music
Python is slowly fading
What can Python do
What is the difference between synchronous and asynchronous Python?
What is the advantage of python over corporate language
What are python class attributes
Is python an interpreted language?
Python parsing variable length structure
Python is short-world epidemic map
What databases can python use
What can python collections do
Python is short _SVM test
Is python code case sensitive
What is the difference between a python script and a web page
Is there function overloading in python
Python deep copy is not perfect
What does rc1 mean in python
Python judges that it is empty
Python is a cross-platform language code
What does def in python do
​What are the numbers in Python?
Everything in Python is an object
Is python suitable for data mining
Is python crawler easy to learn