Global Keyword Usage Boundaries
๐ท๏ธ Functions / Variable Scope
๐ง Context Introduction
In Python, variables defined outside of any function are called global variables. They can be accessed from anywhere in your code. However, when you want to modify a global variable inside a function, Python requires you to explicitly declare your intention using the global keyword. Without it, Python will treat any assignment inside a function as creating a new local variable, even if a global variable with the same name exists.
Understanding where and when to use the global keyword is essential for writing clean, predictable code and avoiding subtle bugs.
โ๏ธ What Does the global Keyword Do?
The global keyword tells Python: "I want to use the variable that exists at the module level, not create a new local one."
- Without
global: Assigning to a variable inside a function creates a new local variable. - With
global: Assigning to a variable inside a function modifies the global variable.
๐ต๏ธ When Must You Use global?
You must use the global keyword when you want to reassign (change the value of) a global variable inside a function.
Example of when global is required:
- You have a variable counter = 0 defined at the top of your script.
- Inside a function, you want to do counter = counter + 1.
- Without
global, Python will think you are creating a new local variable namedcounter, and you will get an UnboundLocalError because you are referencing it before assignment.
Example of when global is NOT required:
- You only want to read the value of a global variable inside a function.
- You are modifying a mutable object (like a list or dictionary) that is stored in a global variable, but you are not reassigning the variable itself.
๐ Comparison Table: With vs. Without global
| Scenario | Code Behavior | global Needed? |
|---|---|---|
| Reading a global variable inside a function | Python looks up the global value automatically | โ No |
| Modifying a global list/dictionary (e.g., my_list.append(5)) | The object is mutated, but the variable reference stays the same | โ No |
| Reassigning a global variable (e.g., my_var = 10) | Python creates a new local variable unless global is declared |
โ Yes |
| Using a global variable in a nested function | You must declare global in the innermost function where reassignment happens |
โ Yes |
๐ ๏ธ Practical Boundaries of the global Keyword
Here are the key boundaries and rules you must follow:
- Scope boundary: The
globalkeyword only works within the function where it is declared. It does not propagate to nested functions automatically. - Declaration must come first: The
globalstatement must appear before any reference to the variable inside the function. - Multiple variables: You can declare multiple global variables in one line: global var1, var2, var3
- No effect on reading: You never need
globaljust to read a variable's value. - Module-level only:
globalrefers to the module-level scope. It cannot refer to variables in enclosing functions (usenonlocalfor that).
๐งช Common Pitfalls to Avoid
- Pitfall 1: Forgetting
globalwhen reassigning โ This causes an UnboundLocalError because Python sees the assignment and assumes the variable is local. - Pitfall 2: Using
globalunnecessarily โ If you only read a global variable, addingglobalis redundant and can confuse readers. - Pitfall 3: Assuming
globalworks across modules โ Theglobalkeyword only applies to the current module. To share variables across modules, use imports. - Pitfall 4: Overusing global variables โ Relying too heavily on
globalmakes code harder to debug and test. Consider passing values as arguments or using return values instead.
โ Best Practices for Engineers
- Limit global variable usage โ Prefer passing data through function arguments and return values. This makes your functions self-contained and easier to test.
- Use constants instead โ If a global value never changes, define it in UPPER_CASE and treat it as a constant. You won't need
globalfor constants. - Group related globals โ If you must use globals, consider storing them in a dictionary or a dedicated configuration object.
- Document your intent โ If you use
global, add a comment explaining why it is necessary. This helps other engineers understand the design choice. - Prefer
returnvalues โ Instead of modifying a global variable inside a function, have the function return the new value and let the caller update the global.
๐ Summary
The global keyword is a powerful tool, but it comes with strict boundaries. Use it only when you need to reassign a variable that lives at the module level. For reading values or mutating objects, global is not required. By respecting these boundaries and following best practices, you will write Python code that is clear, predictable, and maintainable.
The global keyword in Python allows you to modify a variable that exists at the module level from inside a function, but its usage is restricted to specific boundaries.
๐ง Example 1: Global keyword inside a simple function
This example shows how to use global to modify a top-level variable from within a function.
count = 0
def increment():
global count
count = count + 1
increment()
increment()
print(count)
๐ค Output: 2
๐ง Example 2: Global keyword only works inside the function where it's declared
This example shows that global must be declared in every function that wants to modify the global variable.
value = 10
def change_value():
global value
value = 20
def try_change():
value = 30 # This creates a local variable, does not affect global
change_value()
try_change()
print(value)
๐ค Output: 20
๐ง Example 3: Global keyword cannot be used inside nested functions
This example shows that global inside a nested function refers to the module-level scope, not the enclosing function's scope.
x = 100
def outer():
x = 200
def inner():
global x
x = 300
inner()
outer()
print(x)
๐ค Output: 300
๐ง Example 4: Global keyword with multiple variables in one statement
This example shows that you can declare multiple global variables in a single global statement.
a = 1
b = 2
c = 3
def update_all():
global a, b, c
a = a + 10
b = b + 20
c = c + 30
update_all()
print(a, b, c)
๐ค Output: 11 22 33
๐ง Example 5: Global keyword used in a practical configuration scenario
This example shows a practical pattern where a global configuration flag is toggled from inside a function.
debug_mode = False
def toggle_debug():
global debug_mode
debug_mode = not debug_mode
def log_message(msg):
if debug_mode:
print(f"[DEBUG] {msg}")
else:
print(msg)
log_message("Starting process")
toggle_debug()
log_message("Debug is now active")
toggle_debug()
log_message("Debug is off again")
๐ค Output: Starting process
๐ค Output: [DEBUG] Debug is now active
๐ค Output: Debug is off again
Comparison Table: Global keyword boundaries
| Boundary | Allowed? | Explanation |
|---|---|---|
| Inside a top-level function | โ Yes | Declares intent to modify a module-level variable |
| Inside a nested function | โ Yes (but refers to module scope) | Does NOT refer to enclosing function's variables |
| Outside a function | โ No | global is only valid inside function bodies |
| With multiple variables | โ Yes | Use global a, b, c to declare several at once |
| To create a new global variable | โ Yes | If the variable doesn't exist, global creates it at module level |
๐ง Context Introduction
In Python, variables defined outside of any function are called global variables. They can be accessed from anywhere in your code. However, when you want to modify a global variable inside a function, Python requires you to explicitly declare your intention using the global keyword. Without it, Python will treat any assignment inside a function as creating a new local variable, even if a global variable with the same name exists.
Understanding where and when to use the global keyword is essential for writing clean, predictable code and avoiding subtle bugs.
โ๏ธ What Does the global Keyword Do?
The global keyword tells Python: "I want to use the variable that exists at the module level, not create a new local one."
- Without
global: Assigning to a variable inside a function creates a new local variable. - With
global: Assigning to a variable inside a function modifies the global variable.
๐ต๏ธ When Must You Use global?
You must use the global keyword when you want to reassign (change the value of) a global variable inside a function.
Example of when global is required:
- You have a variable counter = 0 defined at the top of your script.
- Inside a function, you want to do counter = counter + 1.
- Without
global, Python will think you are creating a new local variable namedcounter, and you will get an UnboundLocalError because you are referencing it before assignment.
Example of when global is NOT required:
- You only want to read the value of a global variable inside a function.
- You are modifying a mutable object (like a list or dictionary) that is stored in a global variable, but you are not reassigning the variable itself.
๐ Comparison Table: With vs. Without global
| Scenario | Code Behavior | global Needed? |
|---|---|---|
| Reading a global variable inside a function | Python looks up the global value automatically | โ No |
| Modifying a global list/dictionary (e.g., my_list.append(5)) | The object is mutated, but the variable reference stays the same | โ No |
| Reassigning a global variable (e.g., my_var = 10) | Python creates a new local variable unless global is declared |
โ Yes |
| Using a global variable in a nested function | You must declare global in the innermost function where reassignment happens |
โ Yes |
๐ ๏ธ Practical Boundaries of the global Keyword
Here are the key boundaries and rules you must follow:
- Scope boundary: The
globalkeyword only works within the function where it is declared. It does not propagate to nested functions automatically. - Declaration must come first: The
globalstatement must appear before any reference to the variable inside the function. - Multiple variables: You can declare multiple global variables in one line: global var1, var2, var3
- No effect on reading: You never need
globaljust to read a variable's value. - Module-level only:
globalrefers to the module-level scope. It cannot refer to variables in enclosing functions (usenonlocalfor that).
๐งช Common Pitfalls to Avoid
- Pitfall 1: Forgetting
globalwhen reassigning โ This causes an UnboundLocalError because Python sees the assignment and assumes the variable is local. - Pitfall 2: Using
globalunnecessarily โ If you only read a global variable, addingglobalis redundant and can confuse readers. - Pitfall 3: Assuming
globalworks across modules โ Theglobalkeyword only applies to the current module. To share variables across modules, use imports. - Pitfall 4: Overusing global variables โ Relying too heavily on
globalmakes code harder to debug and test. Consider passing values as arguments or using return values instead.
โ Best Practices for Engineers
- Limit global variable usage โ Prefer passing data through function arguments and return values. This makes your functions self-contained and easier to test.
- Use constants instead โ If a global value never changes, define it in UPPER_CASE and treat it as a constant. You won't need
globalfor constants. - Group related globals โ If you must use globals, consider storing them in a dictionary or a dedicated configuration object.
- Document your intent โ If you use
global, add a comment explaining why it is necessary. This helps other engineers understand the design choice. - Prefer
returnvalues โ Instead of modifying a global variable inside a function, have the function return the new value and let the caller update the global.
๐ Summary
The global keyword is a powerful tool, but it comes with strict boundaries. Use it only when you need to reassign a variable that lives at the module level. For reading values or mutating objects, global is not required. By respecting these boundaries and following best practices, you will write Python code that is clear, predictable, and maintainable.
Interactive Views
You are currently in ๐ All-in-One mode. Use the tabs at the top to switch to ๐ Theory Only or ๐ป Code Only views.
The global keyword in Python allows you to modify a variable that exists at the module level from inside a function, but its usage is restricted to specific boundaries.
๐ง Example 1: Global keyword inside a simple function
This example shows how to use global to modify a top-level variable from within a function.
count = 0
def increment():
global count
count = count + 1
increment()
increment()
print(count)
๐ค Output: 2
๐ง Example 2: Global keyword only works inside the function where it's declared
This example shows that global must be declared in every function that wants to modify the global variable.
value = 10
def change_value():
global value
value = 20
def try_change():
value = 30 # This creates a local variable, does not affect global
change_value()
try_change()
print(value)
๐ค Output: 20
๐ง Example 3: Global keyword cannot be used inside nested functions
This example shows that global inside a nested function refers to the module-level scope, not the enclosing function's scope.
x = 100
def outer():
x = 200
def inner():
global x
x = 300
inner()
outer()
print(x)
๐ค Output: 300
๐ง Example 4: Global keyword with multiple variables in one statement
This example shows that you can declare multiple global variables in a single global statement.
a = 1
b = 2
c = 3
def update_all():
global a, b, c
a = a + 10
b = b + 20
c = c + 30
update_all()
print(a, b, c)
๐ค Output: 11 22 33
๐ง Example 5: Global keyword used in a practical configuration scenario
This example shows a practical pattern where a global configuration flag is toggled from inside a function.
debug_mode = False
def toggle_debug():
global debug_mode
debug_mode = not debug_mode
def log_message(msg):
if debug_mode:
print(f"[DEBUG] {msg}")
else:
print(msg)
log_message("Starting process")
toggle_debug()
log_message("Debug is now active")
toggle_debug()
log_message("Debug is off again")
๐ค Output: Starting process
๐ค Output: [DEBUG] Debug is now active
๐ค Output: Debug is off again
Comparison Table: Global keyword boundaries
| Boundary | Allowed? | Explanation |
|---|---|---|
| Inside a top-level function | โ Yes | Declares intent to modify a module-level variable |
| Inside a nested function | โ Yes (but refers to module scope) | Does NOT refer to enclosing function's variables |
| Outside a function | โ No | global is only valid inside function bodies |
| With multiple variables | โ Yes | Use global a, b, c to declare several at once |
| To create a new global variable | โ Yes | If the variable doesn't exist, global creates it at module level |