Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readPython
#Python#asyncio#multiprocessing#Migration
An event loop ring with a missing starter and forked workers outside it, headline NO CURRENT LOOP

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
code
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.

python
# before loop = asyncio.get_event_loop() loop.run_until_complete(main()) # after asyncio.run(main())
python
# inside a running loop loop = asyncio.get_running_loop()
python
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:

python
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 import

The 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 behaviourPython 3.13Python 3.14Replacement
asyncio.get_event_loop() without a loopcreates oneraises RuntimeErrorasyncio.run()
asyncio.get_running_loop()unchangedunchangeduse inside coroutines
Child watcher classesdeprecatedremovedloop internals manage subprocesses
multiprocessing default on Linuxforkforkserverpass state to the worker
bool(NotImplemented)True with a warningTypeErrorx is NotImplemented
int(obj) fallbackcalls __trunc__needs __int__ or __index__implement the right dunder
return in finallyallowedSyntaxWarningrestructure
except (A, B): without parenthesestoleratedaccepted and encouragedPEP 758 syntax
Where the loop was createdWhat breaksFix
CLI entry pointfirst call raisesasyncio.run(main())
Library __init__import-time loop cachedcreate lazily inside the coroutine
pytest fixtureno loop for the fixturepytest-asyncio 1.x, asyncio_mode = auto
Gunicorn worker hookpreload_app has no loopcreate the loop in post_fork
Celery task wrapperget_event_loop in a threadasyncio.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:

python
# 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:

python
# 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.

python
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:

python
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:

python
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:

bash
python3.14 -c "import sys; print(sys._is_gil_enabled())" uv venv --python 3.14t

Treat 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:

bash
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; use await.
  • Assuming pytest-asyncio still works. Version 1.x changed fixture loop handling for 3.14.
  • Debugging a forkserver failure as a pickling error only. A missing global raises AttributeError in the child, not a pickle error.
  • Suppressing the finally warning. It hides a swallowed exception, which is a real bug.
  • Using if not result on a comparison protocol. TypeError at 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 documentation

The Python documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.