Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand python global variables, local variables and namespaces

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the knowledge of "how to understand python global variables, local variables and namespaces". In the actual case operation process, many people will encounter such difficulties. Next, let Xiaobian lead you to learn how to deal with these situations! I hope you can read carefully and learn something!

Python is idiosyncratic in the way it uses global and local variables. While in many or most other programming languages variables are treated as global unless otherwise declared, Python treats variables the opposite way. If not stated otherwise, they are local. The driving reason behind this approach is that global variables are generally bad practice and should be avoided. In most cases where you want to use global variables, it is best to use arguments to put values into functions or return values to take them out. Like many other program constructs, Python imposes good programming habits by design.

Therefore, when you define variables in a function definition, by default they are local variables to the function. That is, whatever you do with such variables in the body of the function does not affect other variables outside the function, even if they have the same name. In other words, the function body is the scope of a variable, i.e., the enclosing context in which the name is associated with its value.

All variables have a block scope where they are declared and defined. They can only be used after the declaration point.

To put it simply: variables do not and cannot be declared in the way they are declared in programming languages such as Java or C. Variables in Python are implicitly declared by defining them, i.e. the first time a value is assigned to a variable, the variable is declared and automatically has the data type of the object that must be assigned to it.

Global and local variables in functions

In the following example, we want to demonstrate how global values can be used within a function body:

def f (): print ( s ) s = "I love Paris in summer! " f ()

Output:

I love Paris in summer!

Before calling function f(), the variable s is defined as the string "I love Paris in summer! "。The body of f() consists only of the "print(s)" statement. Since there is no local variable s, i.e. no assignment to s, the value of the global variable s will be used. So the output will be the string "I love Paris in summer! "。The question is, what happens if we change the value of s in the function f()? Does it also affect global variables? We tested this in the following code:

def f (): S = "I love London! " Print ( s ) s = "I love Paris! " f () Print ( s )

Output:

I love London!

I love Paris!

What if we combine the first example with the second example, i.e. we first access s using the print() function, hoping to get a global value, and then assign it a new value? To assign a value to it means--as we said earlier--to create a local variable s. Therefore, we will treat s as a global variable and a local variable in the same scope, i.e., the function body. Fortunately, Python does not allow this ambiguity. Therefore, it raises errors, as we can see in the following example:

def f (): print ( s ) S = "I love London! " Print ( s )s = "I love Paris! " f ()

Output:

UnboundLocalError Traceback (last call last)

in

5

6 s = "I love Paris! "

----> 7 f ( )

in f ()

1 def f ( ) :

----> 2 print ( s )

3 s = "I

Love London! " 4 Print ( s )

5

UnboundLocalError: Reference to local variable "s" before assignment

Variables cannot be both local and global within a function. Since s is assigned inside f(), Python decides that we need a local variable, so the first print statement before s is defined throws the error message above. Any variable changed or created inside a function is local if it is not declared global. To tell Python that we want to use global variables, we must explicitly state this using the keyword "global," as shown in the following example:

def f (): global s print ( s ) s = "Only in spring, but London is great too! " Print ( s )s = "I am looking for courses in Paris! " f () Print ( s )

Output:

I am looking for courses in Paris!

Only in spring, but London is great too!

Only in spring, but London is great too!

Local variables of a function cannot be accessed externally after the function call is complete. This is a continuation of the previous example:

def f (): s = "I'm globally unknown" Print ( s ) f () Print ( s )

Output:

I'm unknown around the world.

Only in spring, but London is great too!

The following example shows wild combinations of local and global variables and function parameters:

def foo ( x , y ): Global a a = 42 x , y = y , x b = 33 b = 17 c = 100 Print ( a , b , x , y )a , b , x , y = 1 , 15 , 3 , 4 foo ( 17 , 4 ) Print ( a , b , x , y )

Output:

42 17 4 17

42 15 3 4

Global variables in nested functions

If we use the global keyword in nested functions, we will now examine what happens. The following example shows how the variable "city" can be used in various scopes:

def f (): city = "Hamburg" def g (): global city city = "Geneva" print ( "call before g:" + city ) print ( "now call g:" ) g () print ( "after call g: " + city)f () print ( "value of main city: " + city )

Output:

Before calling g: burger

Now call g:

After calling g: Hamburg

Main city value: Geneva

We can see that the global statement in nested function g does not affect the variable "city" of function f, i.e. it retains its value "Hamburg." We can also infer from this example that after calling f(), there is a variable 'city' in the module namespace with the value 'Geneva'. This means that the global keyword in nested functions does not affect the namespace of its enclosing namespace! This is consistent with what we found in the previous chapter: a variable defined inside a function is local unless it is explicitly marked as global. In other words, we can reference a variable name in any enclosing scope, but we can only rebind the variable name in local scope by assignment, or in module global scope by using global declarations. We also need a way to access variables in other scopes. The way to do this is non-locally defined, which we will explain in the next chapter.

non-local variables

Python 3 introduces nonlocal variables as a new type of variable. Nonlocal variables have a lot in common with global variables. One difference from global variables is that a module-scoped variable, that is, a variable that is not defined inside a function, cannot be changed by using a non-local statement. We demonstrate this in the following two examples:

def f (): global city Print ( city )city = "Frankfurt" f ()

Output:

Frankfurt

The program is correct and returns "Frankfurt" as output. We will change Global to Non-Local in the following program:

def f (): non-local city Print ( city )city = "Frankfurt" f ()

Output:

Document "," second

Non-local cities

^

Syntax error: No binding found for non-local 'city'

This indicates that non-local bindings can only be used inside nested functions. Nonlocal variables must be defined in the enclosing function scope. Variables cannot be defined in nested scopes if they are not defined in the enclosing function scope. This is another difference from the "global" semantics.

def f (): city = "Munich" def g (): nonlocal city city = "Zurich" print ( "call before g:" + city ) print ( "now call g:" ) g () print ( "after call g: " + city)city = "Stuttgart" f () print ( "'city' in main:" + city )

Output:

Call before g: Munich

Now call g:

After dialing g: Zurich

Main "city": Stuttgart

In the previous example, the variable 'city' was defined before calling g. Without a definition, we get an error:

HD F (): #city = "Munich" High definition g ^(): Foreign cities City = "Zurich" Print ("Call before: " + City) Print ("Call G: Now") g ^ () Print ("call after g: " + city )city = "Stuttgart" f () print ( "'city' in main:" + city )

Output:

Document "," 4th

Non-local cities

^

Syntax error: No binding found for non-local 'city'

The program works fine-if we change "non-local" to "global," with or without the 'city = "Munich"' line inside f -:

def f (): #city = "Munich" def g (): global city city = "Zurich" print ( "Before call g:" + city ) print ( "Calling g now:" ) g () print ( "After calling g:" ) calling g: " + city )city = "Stuttgart" f () print ( "'city' in main:" + city )

Output:

Before calling: Stuttgart

Now call g:

After dialing g: Zurich

Main "city": Zurich

However, there is one big difference: the value of global x has now changed!

"How to understand python global variables, local variables and namespaces" is introduced here, thank you for reading. If you want to know more about industry-related knowledge, you can pay attention to the website. Xiaobian will output more high-quality practical articles for everyone!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report