Python 3.14: asyncio get_event_loop RuntimeError and forkserver
The implicit event loop is gone and Linux workers now start with forkserver. Both break code that relied on inherited state.

Introduction & Quick Summary
Symptom. A CLI tool or a test suite that worked on Python 3.13 fails on 3.14 before doing any work:
RuntimeError: There is no current event loop in thread 'MainThread'.
TypeError: 'NotImplementedType' object is not callable
RuntimeError: context has already been set
File "/usr/lib/python3.14/multiprocessing/forkserver.py", line ...Or the warning you ignored for two releases becomes a SyntaxWarning on import: 'return' in a 'finally' block.
Cause. Python 3.14 removes the implicit event loop, changes the default multiprocessing start method on Linux from fork to forkserver, makes bool(NotImplemented) an error, and warns when control flow leaves a finally block. Each is small, and each breaks a different category of code: library wrappers, worker pools, comparison helpers, and cleanup blocks.
Fix. Own the loop, pass state to workers explicitly, and compare with is.
# before
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
# after
asyncio.run(main())# inside a running loop
loop = asyncio.get_running_loop()import multiprocessing as mp
def worker(item, config):
return item * config["factor"]
if __name__ == "__main__":
ctx = mp.get_context("forkserver")
with ctx.Pool(4) as pool:
print(pool.map(worker, range(4), [{"factor": 2}] * 4))Core Mechanics, Signatures & Reproducible Setup
asyncio.get_event_loop() used to create a loop on first call in the main thread and print a deprecation warning; 3.14 makes it raise instead. The function is not deprecated for the case where a loop is running — get_running_loop() covers that — it is deprecated as an implicit constructor. The documented replacements are asyncio.run() at the top, get_running_loop() inside coroutines, and an explicit asyncio.Runner when you need several top-level calls on one loop.
Reproduce each break in a single file:
import asyncio
import multiprocessing as mp
async def main():
await asyncio.sleep(0)
return "ok"
# 1. implicit loop
try:
asyncio.get_event_loop()
except RuntimeError as e:
print("loop:", e)
# 2. bool of NotImplemented
try:
if NotImplemented:
pass
except TypeError as e:
print("notimplemented:", e)
# 3. default start method
print("start method:", mp.get_start_method())
# 4. control flow in finally
def f():
try:
return 1
finally:
return 2 # SyntaxWarning on importThe output tells you which of the four your codebase depends on. Then upgrade the layers that create loops on your behalf, which is where most production failures live: pytest-asyncio fixtures, Celery workers, gRPC servers, and synchronous wrappers around async client libraries.
Key Comparison Table
| API or behaviour | Python 3.13 | Python 3.14 | Replacement |
|---|---|---|---|
asyncio.get_event_loop() without a loop | creates one | raises RuntimeError | asyncio.run() |
asyncio.get_running_loop() | unchanged | unchanged | use inside coroutines |
| Child watcher classes | deprecated | removed | loop internals manage subprocesses |
multiprocessing default on Linux | fork | forkserver | pass state to the worker |
bool(NotImplemented) | True with a warning | TypeError | x is NotImplemented |
int(obj) fallback | calls __trunc__ | needs __int__ or __index__ | implement the right dunder |
return in finally | allowed | SyntaxWarning | restructure |
except (A, B): without parentheses | tolerated | accepted and encouraged | PEP 758 syntax |
| Where the loop was created | What breaks | Fix |
|---|---|---|
| CLI entry point | first call raises | asyncio.run(main()) |
Library __init__ | import-time loop cached | create lazily inside the coroutine |
| pytest fixture | no loop for the fixture | pytest-asyncio 1.x, asyncio_mode = auto |
| Gunicorn worker hook | preload_app has no loop | create the loop in post_fork |
| Celery task wrapper | get_event_loop in a thread | asyncio.run() per task |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. Libraries that cached a loop at import time
A module-level loop = asyncio.get_event_loop() now fails on import, which turns into ImportError with a RuntimeError cause and looks like a packaging problem. The fix is to defer:
# before
_loop = asyncio.get_event_loop()
def run(coro):
return _loop.run_until_complete(coro)
# after
def run(coro):
try:
asyncio.get_running_loop()
except RuntimeError:
return asyncio.run(coro)
raise RuntimeError("run() cannot be used inside a running loop")That error message matters: silently creating a second loop inside a running one is how RuntimeError: This event loop is already running used to happen, and 3.14 removes the accident without removing the bug.
2. forkserver does not inherit your globals
The default fork gave every child a copy of the parent's memory, which is why worker functions could read a module-level model, logger or connection. forkserver starts a fresh server process that imports the target module, so anything not pickled into the arguments is missing:
# fails under forkserver: _model is None in the child
_model = load_model()
def predict(x):
return _model.predict(x)Two correct shapes: pass the object as an argument (it must be picklable), or initialise inside the worker with an initializer.
def init_worker(path):
global _model
_model = load_model(path)
with ctx.Pool(4, initializer=init_worker, initargs=("model.bin",)) as pool:
pool.map(predict, batch)fork is still available via mp.get_context("fork"), but it is unsafe with threads and should be treated as a temporary pin with a task attached.
3. The finally warning that hides an exception
A return in finally discards the in-flight exception, so a real failure becomes a silent success. The warning names the line, and with -W error it stops the import:
def read(path):
f = open(path)
try:
return f.read()
finally:
f.close()
return None # would swallow any error from read()Restructure so the cleanup has no control flow of its own; with open(path) as f: return f.read() is the same intent in one line.
4. NotImplemented comparisons
Rich comparison methods return NotImplemented to defer to the other operand. Code that tested truthiness now raises:
class Version:
def __eq__(self, other):
if not isinstance(other, Version):
return NotImplemented
return self.major == other.major
# inside a caller
result = a.__eq__(b)
if result is NotImplemented: # correct
...The same applies to __lt__ and friends, and to any helper that used if not result to mean "unsupported".
5. Free-threaded builds are a separate interpreter
python3.14t exists, and importing a C extension that has not been ported silently re-enables the GIL for that module, so there is no error and no speedup. Check before you plan a migration:
python3.14 -c "import sys; print(sys._is_gil_enabled())"
uv venv --python 3.14tTreat the free-threaded build as an experiment until every extension in your dependency tree ships a cp314t wheel.
6. Verifying a 3.14 image before the cutover
Run the suite with deprecations as errors, and install binary wheels only so a missing wheel fails in CI rather than at runtime:
uv pip install --only-binary :all: -r requirements.txt
pytest -W error::DeprecationWarning -W error::SyntaxWarning
python -X dev -c "import app"-X dev enables the development mode checks, which surface unclosed resources and deprecated calls that a normal run hides. Compare the two pytest JSON reports with the text diff tool after the upgrade; a test that changes from pass to skip is often a fixture that could not create a loop.
Common Compilation/Runtime Mistakes & Version Gotchas
- Pinning
asyncio.set_event_loop(new_loop())at import. It restores the old accident and breaks as soon as two threads import the module. - Calling
asyncio.run()inside a coroutine. It raises by design; useawait. - Assuming
pytest-asynciostill works. Version 1.x changed fixture loop handling for 3.14. - Debugging a
forkserverfailure as a pickling error only. A missing global raisesAttributeErrorin the child, not a pickle error. - Suppressing the
finallywarning. It hides a swallowed exception, which is a real bug. - Using
if not resulton a comparison protocol.TypeErrorat runtime, and it was always wrong. - Upgrading the interpreter but not the base image. CI and production then disagree about
sys.version_info.
Format the JSON output of a failing test report with the JSON formatter to read the traceback without noise.
Reference: What's new in Python 3.14 and the asyncio event loop documentation.
Official references
primary documentationThe Python documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesasyncpg DuplicatePreparedStatement on PgBouncer and Supabase
asyncpg caches prepared statements per connection while a transaction pooler rotates connections underneath it. The cache setting, pool sizing and retry that fix it.
Python Tabulate: Markdown Grid Headers and Alignment
Use Python's tabulate library to format Markdown tables, set custom headers, and control column alignment with pipe and grid formats.
Django select_related and prefetch_related: Fix N+1 Queries
Learn how to eliminate N+1 queries in Django with select_related and prefetch_related, including practical examples, when to use each, and common pitfalls.
Python f-string format specifier: syntax and examples
How to use Python f-string format specifiers for alignment, numeric precision, grouping, and sign control, with practical examples.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.