Understanding Variable Scope and Global Variables in Django and DRF
Python's variable scope rules interact in surprising ways with Django's request/response cycle, so let's unpack the essentials.
May 5, 2025 · 1 min read · Som

Python's scoping rules are simple until you put them inside a long-lived web process. In Django and DRF, a module-level "global" is shared across requests on the same worker — which is a subtle source of hard-to-reproduce bugs.
The trap: module-level state
# views.py
counter = 0 # shared across ALL requests handled by this worker
def track(request):
global counter
counter += 1 # not per-user, not per-request
...
Because the worker process persists, counter leaks state between unrelated
requests and between users.
Where state should live instead
| Need | Right home |
|---|---|
| Per-request data | The request object / local variables |
| Per-user data | Session or database |
| Shared cross-process | Cache (Redis) or database |
Rule of thumb
Keep view logic stateless. If something must persist, push it to a store that's built for concurrency — never a module global.