In Python, if you want to modify a global variable from inside a function, you must explicitly declare it as global
inside that function.
If you only read a global variable, you don’t need global
—but the moment you assign to it, Python assumes it’s a new local variable unless told otherwise.
Here’s an example:
# Global variable
counter = 0
def increment():
global counter # Tell Python: "Use the global variable, not a new local one"
counter += 1
def show_counter():
print(counter) # Just reading, so no `global` needed
increment()
increment()
show_counter() # Output: 2
Key points:
Use global var_name
inside the function to write to a global variable.
Reading doesn’t require global
, but if you both read and write in the same function, you must declare it.
Overusing globals can make code harder to debug—often passing values as function parameters is better.
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?