The global Keyword in Python 2026 – Best Practices for Writing Functions
The global keyword allows a function to modify a variable defined in the global (module) scope. While powerful, it should be used sparingly. In 2026, modern Python code prefers cleaner alternatives whenever possible.
TL;DR — Key Takeaways 2026
globaldeclares that a variable inside a function refers to the global scope- It is needed only when you want to **assign** to a global variable
- Overusing
globalmakes code harder to understand and test - Prefer returning values, using classes, or dependency injection instead
1. Basic Usage of global
counter = 0
def increment():
global counter # Declare we want to modify the global variable
counter += 1
return counter
print(increment()) # 1
print(increment()) # 2
print(counter) # 2
2. Why global is Usually Not Recommended
# ❌ Bad practice - using global
count = 0
def bad_increment():
global count
count += 1
# ✅ Better approach - return value
def good_increment(current_count: int) -> int:
return current_count + 1
# Even better - use a class
class Counter:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
return self.count
3. Best Practices in 2026
- Use
globalonly when absolutely necessary (very rare in modern code) - Prefer returning values from functions instead of modifying globals
- Use classes or modules with state when you need persistent data
- Consider dependency injection or context managers for shared state
- If you must use
global, document it clearly with comments
Conclusion
The global keyword exists for a reason, but in 2026 it is considered a code smell in most situations. Professional Python developers avoid it by returning values, using classes, or applying better design patterns. Clean functions should not have hidden side effects on global state.
Next steps:
- Search your codebase for
globaland refactor to use return values or classes - Related articles: Writing Functions in Python 2026 • Defining a Function Inside Another Function in Python 2026