Code Quality

Global Variables in Python: Why They Cause Bugs

Global variables create hidden dependencies that make code hard to test and reason about. When any function can modify a global, the program's state becomes unpredictable.


❌ Problematic Global State

user_count = 0

def register_user(name):
    global user_count
    user_count += 1
    print(f'Registered {name}, total: {user_count}')

def reset():
    global user_count
    user_count = 0  # Silent side effect!

✅ Refactored as Class

class UserRegistry:
    def __init__(self):
        self._count = 0

    def register(self, name):
        self._count += 1
        print(f'Registered {name}, total: {self._count}')

    def reset(self):
        self._count = 0
💡

Pro tip: Encapsulate state in a class or pass it as function parameters. This makes dependencies visible, testable, and replaceable.

Paste this code into LearnCodeGuide

Detect Python vulnerabilities and bugs automatically with AI-powered analysis.

Analyze Python Code →

Related Guides

Python Dead CodePython Mutable Default ArgumentPython Long Function