Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Concurrency & parallelismSeniorOccasionalTheory

Are Python's built-in data structures like `list` and `dict` thread-safe?

Answer

Individual built-in operations that map to a single bytecode instruction, like `list.append()` or a single dict key assignment, are effectively atomic in the default GIL-enabled CPython build and will not corrupt the underlying data structure — though this has never been a formal language-level guarantee, only an incidental consequence of how the reference implementation happens to work. In Python 3.14's free-threaded build, the GIL is gone entirely, and built-in containers instead rely on their own internal fine-grained locking to stay structurally safe, so the mechanism differs even though simple single-operation safety still generally holds. Either way, this does not make the type "thread-safe" in a general sense: any sequence of multiple operations that needs to happen as one logical unit, such as "check if a key exists, then insert if not," is not atomic as a whole and is still subject to race conditions between the individual steps. The recommended practice is to identify the invariant your code actually needs and protect it with explicit synchronization — a `Lock`, a queue, or clear single-owner access — rather than relying on any interpreter's incidental atomicity.

Strong answer includes

  • single-instruction-style operations are effectively atomic in the default GIL build, but that was never a formal guarantee
  • free-threaded 3.14 uses its own internal locking instead of the GIL for that safety
  • multi-step logical operations are never atomic as a whole; protect real invariants with explicit locks

Practical example

Python example
if key not in cache: cache[key] = compute()

can still run

Python example
compute()

twice from two threads, because the check and the assignment are two separate atomic steps, not one.

#threading#race-conditions

Sources

threading — Thread-based parallelismPython Software Foundation · Locks, thread safety and thread-local stateData modelPython Software Foundation · Dunder methods, object identity, attribute lookup and the descriptor and context manager protocols