
I. Understanding global in Python
global keyword lets you modify global variables (全局变量) inside functions. Without it, assignments create local variables (局部变量) instead.
1. Scope Basics in Python
Every variable in Python has a defined scope (作用域) – the region of code where it is accessible.
- Global scope: Variables defined outside any function
- Local scope: Variables defined inside a function
# Global variablex = 10
def my_function(): # Local variable (different from global x) x = 5 print("Inside function:", x)
my_function() # Output: Inside function: 5print("Outside function:", x) # Output: Outside function: 10x inside the function is completely separate from the global x. This is Python's way of preventing accidental modification of global variables.2. The Problem: Modifying Global Variables
When you try to modify a global variable inside a function without declaring it as global, Python creates a new local variable instead.
counter = 0
def increment(): # This creates a NEW local variable 'counter' counter += 1 # ❌ ERROR!
# increment() # Uncommenting this line causes UnboundLocalErrorPitfall: This code raises UnboundLocalError: local variable ‘counter’ referenced before assignment because Python sees the assignment and treats counter as a local variable, but it’s being referenced before it’s defined.
3. The Solution: Using global
The global keyword tells Python: “This variable belongs to the global scope”.
counter = 0 # Global variable
def increment(): global counter # Declare that we're using the global counter counter = counter + 1 print(f"Counter is now: {counter}")
increment() # Output: Counter is now: 1increment() # Output: Counter is now: 2print(f"Global counter: {counter}") # Output: Global counter: 2global statement must come before any use of the variable in the function.4. Multiple Global Variables
You can declare multiple global variables in a single statement:
name = "Python"version = 3.9year = 2023
def update_info(): global name, version, year name = "Python 3" version = 3.11 year = 2024
update_info()print(f"{name} {version} ({year})") # Output: Python 3 3.11 (2024)5. Global vs Local: A Comparison
| Aspect | Local Variable | Global Variable |
|---|---|---|
| Scope (作用域) | Inside function only | Throughout the module |
| Declaration | Automatic on assignment | global keyword required inside functions |
| Read access | Direct access | Direct access (without global for reading) |
| Write access | Direct assignment | Requires global declaration |
| Memory (内存) | Created when function runs | Created when module loads |
| Best practice | Preferred for temporary values | Use sparingly, prefer parameters |
6. Reading Global Variables (Without global)
Interesting fact: You can read global variables without the global keyword:
message = "Hello, World!"
def show_message(): # No 'global' needed for reading print(message) # This works!
show_message() # Output: Hello, World!Warning: This only works for reading (读取). The moment you try to assign a value, Python treats it as a local variable unless you use global.
7. Nested Functions and global
The global keyword always refers to the module-level (模块级别) scope, not the enclosing function scope.
x = "global x"
def outer(): x = "outer x"
def inner(): global x # This refers to the module-level 'x', not outer's 'x' x = "changed by inner"
inner() print("outer x:", x) # Output: outer x: outer x
outer()print("global x:", x) # Output: global x: changed by innernonlocal keyword instead, which we'll cover in a separate note.8. Mutable Objects: A Special Case
For mutable objects (可变对象) like lists and dictionaries, you can modify their contents without using global:
my_list = [1, 2, 3]my_dict = {"count": 0}
def modify_mutable(): # No 'global' needed - we're modifying, not reassigning my_list.append(4) my_dict["count"] += 1 print("Inside function:", my_list, my_dict)
modify_mutable()print("Outside function:", my_list, my_dict)# Output: Outside function: [1, 2, 3, 4] {'count': 1}Pitfall: This works because we’re modifying (修改) the object, not reassigning (重新赋值) the variable. If we tried my_list = [4, 5, 6], that would require global.
Use
global only when you must modify a module-level variable from inside a function; otherwise, pass values as parameters and return results for cleaner, more maintainable code.