H4 Tech Solutions Logo
All articles

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

Understanding Variable Scope and Global Variables in Django and DRF

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

NeedRight home
Per-request dataThe request object / local variables
Per-user dataSession or database
Shared cross-processCache (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.

Subscribe

Get new articles, white papers, and repos from H4Tech in your inbox.

Follow along via Subscribe via RSS