Understanding the global Statement in Python
The article explains how Python's global statement declares variables as global within a function, allowing modification of module‑level variables and preventing UnboundLocalError, with examples of incorrect usage, correct usage, multiple globals, and class‑based alternatives.
When a function needs to modify a variable defined outside its scope, Python requires the global statement to declare that variable as global; otherwise the interpreter treats assignments as creating a new local variable, leading to errors such as UnboundLocalError.
Example of the error:
count = 1
def cc():
count = count + 1
cc()
# UnboundLocalError: local variable 'count' referenced before assignmentCorrect usage with global:
def cc():
global count
count = count + 1
print(count)
cc()
# 2Multiple variables can be declared in one statement, separated by commas:
num = 0
def cc():
global count, num
count = count + 1
num = num + 2
print(count, num)
cc()
# 3 2Alternatively, a class attribute can serve a similar purpose:
class C:
count = 3
def cc():
C.count = C.count + 1
print(C.count)
cc()
# 4The global statement therefore acts like passing a variable into a function, allowing the function to read and modify the variable defined in the outer (module) scope.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
