how to use global variables is python?
- User
how to use global variables is python?
- Assistant
In Python, global variables are variables defined at the top level of a script (outside any function or class), making them accessible from anywhere in that module. However, there’s an important distinction:
Reading a global variable inside a function works without any extra steps.
Modifying a global variable inside a function requires explicitly declaring it as global inside that function.
Basic Example pythonCopyEdit# Global variable counter = 0
def increment(): global counter # Declare that we want to modify the global variable counter += 1
def show(): print(counter) # Can read without 'global'
increment() increment() show() # Output: 2
Without global Keyword If you try to modify a global variable without declaring it global: pythonCopyEditx = 10
def change(): x = x + 1 # ❌ UnboundLocalError print(x)
Python assumes x is local inside the function, so it errors out. To fix this, you must use: pythonCopyEditdef change(): global x x = x + 1
- User
I have a counter that I want to update from within one function and print its value at the run end. What do you recommend?
- Assistant
If your goal is just to update a counter from inside one function and then print it at the end of the program, you have a few clean options — some cleaner than a plain global variable. Here are three patterns, from simplest to most maintainable:
- Minimal & Simple — Global Variable pythonCopyEditcounter = 0 # Global
def increment(): global counter counter += 1
Example usage
increment() increment()
print("Final count:", counter)
✅ Simple for tiny scripts. ⚠ Not great if your program grows — global variables get messy.
- Use a Function Parameter & Return Value (Functional Style) pythonCopyEditdef increment(c): return c + 1
- User
in the Class-based, do I need to pass the counter instance to the function where I want to increment it?
- Assistant
Yes — in the class-based version, the function that increments the counter needs some way to access the counter instance. That usually means either:
Passing the counter instance as an argument,
Storing it somewhere both functions can access (e.g., as a global, in a higher scope, or as part of a larger object).
Example 1 – Passing the instance pythonCopyEditclass Counter: def init(self): self.value = 0 def increment(self): self.value += 1
def do_something(counter): # This function has access to the counter counter.increment()
counter = Counter() do_something(counter) do_something(counter)
print("Final count:", counter.value)
✅ Explicit — you always know which counter you’re updating.
Example 2 – Keeping the instance global-ish but still tidy pythonCopyEditclass Counter: def init(self): self.value = 0 def increment(self): self.value += 1
- User
I want to see the hybrid approach
- Assistant
Alright — here’s the hybrid approach: a singleton-style counter. It behaves like a global (easy to access anywhere), but still keeps the state and logic wrapped inside a class so you’re not just throwing integers around.
Hybrid "Global but Encapsulated" Counter pythonCopyEditclass Counter: _instance = None # Class-level storage for the one instance
codedef __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) cls._instance.value = 0 return cls._instance def increment(self): self.value += 1 def get(self): return self.valueAnywhere in your code, you can just do:
def do_something(): Counter().increment() # No need to pass the counter around
def another_function(): Counter().increment()
Simulate some work
- User
yes
- Assistant
Here’s the closure-based hybrid — it’s short, hides the state, and works anywhere in your program without a global.
Closure-Based Hybrid Counter pythonCopyEditdef make_counter(): value = 0 def increment(): nonlocal value value += 1 return value def get(): return value return increment, get
Create the counter once
increment_counter, get_counter = make_counter()
Functions can use it without touching global variables
def do_something(): increment_counter()
def another_function(): increment_counter()
do_something() another_function() do_something()
print("Final count:", get_counter()) # Output: 3
Why it works
value lives inside the closure — it’s not in the global namespace.
nonlocal lets increment() modify the value from the enclosing scope.
You can import increment_counter and get_counter into any file without worrying about name collisions.
Keeps the same "one counter for the whole run" behavior as the class-based singleton.
If you want, I can show you a super minimal version that packs this into just a few lines but still hides the counter’s state. That’s great for one-off scripts. Do you want that tiny version?