The global keyword in Python allows a function to reference and modify a variable from the global (module-level) scope instead of creating a local variable with the same name. Without global, assigning to a variable inside a function creates a local variable by default — even if a global variable with the same name exists. Using global declares that the name refers to the global variable, enabling both reading and writing from inside the function. In 2026, global is still valid but considered a code smell in most modern Python — it breaks encapsulation, makes functions less predictable/testable, increases coupling, and can lead to subtle bugs in concurrent or large codebases. Best practice is to avoid globals entirely, preferring function parameters, return values, class attributes, closures, or module-level constants with clear intent.
Here’s a complete, practical guide to the global keyword in Python: how it works, reading vs writing, common pitfalls, alternatives to globals, real-world patterns, and modern best practices with type hints, refactoring, and pandas/Polars integration.
Basic usage — global lets you modify a global variable from inside a function.
x = 5 # global variable
def add_to_x(y: int):
global x # declare x refers to global
x += y # modifies the global x
print("Before:", x) # Before: 5
add_to_x(3)
print("After:", x) # After: 8
Reading globals without global is allowed — only assignment creates a local unless global is used.
x = 10
def read_global():
print(x) # reads global ? 10 (no global needed)
def assign_global():
global x
x = 20 # modifies global
def assign_local():
x = 30 # creates local x, global unchanged
read_global() # 10
assign_local()
print(x) # still 10
assign_global()
print(x) # 20
Classic pitfall — forgetting global when assigning causes UnboundLocalError or silent local creation.
count = 0
def increment():
count += 1 # UnboundLocalError: local variable 'count' referenced before assignment
print(count)
# Fix
def safe_increment():
global count
count += 1
print(count)
Real-world pattern: avoiding globals in pandas/Polars pipelines — pass state explicitly via parameters or return values, use closures or classes for shared state.
# Bad: global config
global_config = {"threshold": 0.5}
def process_data(df):
return df[df['value'] > global_config["threshold"]]
# Better: pass config explicitly
def process_data(df, threshold: float = 0.5):
return df[df['value'] > threshold]
# Or use closure/factory
def make_processor(threshold: float):
def processor(df):
return df[df['value'] > threshold]
return processor
process_above_05 = make_processor(0.5)
cleaned = process_above_05(df)
Best practices make global usage safe, readable, and avoidable. Avoid global entirely in modern Python — pass values as arguments, return results, use class attributes, module constants (ALL_CAPS), or dependency injection. Modern tip: use Polars for immutable-by-default DataFrames — pass config via parameters or closures, no need for globals. Add type hints — def func(config: dict) -> pd.DataFrame — makes dependencies explicit. Use nonlocal in nested functions instead of global — better encapsulation. Use contextvars for per-context global-like state (async/thread-local). Use functools.lru_cache or module-level memoization — avoid globals for caching. Log global usage — logging.warning("Using global X") — flag for refactoring. Refactor globals incrementally — inject via parameters or class init. Use pytest fixtures or unittest.mock.patch — test code without real globals. Prefer immutable configs — frozen dataclass or types.MappingProxyType — prevents accidental mutation.
The global keyword lets functions modify module-level variables — but it’s a code smell in modern Python. In 2026, avoid globals: pass parameters, return values, use closures/classes, contextvars, or dependency injection. Master alternatives to global, and you’ll write decoupled, testable, predictable code that’s easy to maintain and scale.
Next time you reach for global — refactor it away. It’s Python’s cleanest way to say: “Make dependencies explicit — no hidden state.”