Sub topic 14
Migrating and testing existing code
This chapter assumes you know the threading module, locks, and the earlier chapters on data races, synchronization, and extension compatibility. It gives a practical order of work for moving an existing project to the free-threaded build and for testing it there.
Start with an inventory
Before you change any code, list what your project depends on.
- Pure-Python code that uses threads or shares mutable state.
- Third-party packages with C, C++, or Rust extensions.
- Your own C extensions.
A free-threaded interpreter re-enables the GIL when it imports an extension module that does not declare support. The first check is therefore whether the GIL stays off after all your imports.
import sys
import sysconfig
# Import everything your application uses first
import json # replace with your real imports
print("Free-threaded build:", sysconfig.get_config_var("Py_GIL_DISABLED"))
print("GIL enabled:", sys._is_gil_enabled())If this prints GIL enabled: True on a free-threaded build, an imported extension turned the GIL back on. Bisect your imports to find which one. Then check whether that package publishes free-threaded wheels, or whether a newer version does.
Make the migration path
The steps below keep the risk small.
- Run your existing test suite on the free-threaded build with
PYTHON_GIL=1. This separates build problems from threading problems. - Run the suite again with
PYTHON_GIL=0. New failures now point to races or unsupported extensions. - Fix shared state by using locks, queues, thread-local data, or immutable data.
- Add concurrency tests, described below.
- Measure performance against your current setup before you commit.
PYTHON_GIL=1 python3.13t -m pytest
PYTHON_GIL=0 python3.13t -m pytestFind code that only worked because of the GIL
Under the GIL, some unsynchronized code appeared to work. Look for these patterns:
- Module-level counters, caches, and registries that several threads update.
- Check-then-act sequences, such as
if key not in cache: cache[key] = compute(). - Lazy initialization of globals.
- Iterating over a list or dict while another thread changes it.
Individual operations on built-in containers stay safe, but a sequence of operations is not. Wrap the whole sequence in a lock.
import threading
_cache = {}
_cache_lock = threading.Lock()
def get_value(key, compute):
with _cache_lock:
if key not in _cache:
_cache[key] = compute(key)
return _cache[key]This holds the lock during compute. That is simple and correct. If compute is slow, switch to a design where each key has its own lock.
Test for races
Race conditions are timing dependent, so one passing run proves little. Use these tactics:
- Run concurrency tests many times, for example in a loop of 100 or more iterations.
- Start threads together with a
threading.Barrier, so they contend at the same moment. - Use more threads than cores to force unusual interleavings.
- Assert on final state, such as totals and invariants, not on timing.
import threading
def test_counter_is_consistent():
counter = 0
lock = threading.Lock()
barrier = threading.Barrier(8)
def work():
nonlocal counter
barrier.wait()
for _ in range(50_000):
with lock:
counter += 1
threads = [threading.Thread(target=work) for _ in range(8)]
for t in threads:
t.start()
for t in threads:
t.join()
assert counter == 8 * 50_000
test_counter_is_consistent()
print("ok")Remove the lock from this test and run it on python3.13t. On a free-threaded build it can fail, which shows the test is able to catch the bug.
Keep both builds working
Many projects must still support standard builds. Add the free-threaded build to your CI matrix next to the standard one. Run the same tests on both, and keep the locks in place, since they are harmless under the GIL.
Exercise
Your test suite passes on python3.13t with PYTHONGIL=1 but fails intermittently with PYTHONGIL=0. What does this suggest, and what is your next step?
Show answer
It suggests the code has data races that the GIL used to hide, or that a dependency is not safe without the GIL. Find the shared mutable state touched by several threads, such as check-then-act sequences or global caches, and protect it with a lock, a queue, or thread-local data. Then rerun the concurrency tests many times with a Barrier to confirm the failures are gone.