Skip to content

Commit 5aa488a

Browse files
authored
fix: cleanup_loaded_modules: dont clean up modules that have not finished loading [backport 3.16] (#14840) (#14906)
1 parent 873a407 commit 5aa488a

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

ddtrace/bootstrap/sitecustomize.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,20 @@
4545
def cleanup_loaded_modules():
4646
def drop(module_name):
4747
# type: (str) -> None
48+
module = sys.modules.get(module_name)
49+
# Don't delete modules that are currently being imported (they might be None or incomplete)
50+
# or that don't exist. This can happen when pytest's assertion rewriter is importing modules
51+
# that themselves import ddtrace.auto, which triggers this cleanup during the import process.
52+
if module is None:
53+
return
54+
# Skip modules that don't have a __spec__ attribute yet (still being imported)
55+
if not hasattr(module, "__spec__"):
56+
return
57+
# Check if the module is currently being initialized
58+
# During import, __spec__._initializing is True
59+
spec = getattr(module, "__spec__", None)
60+
if spec is not None and getattr(spec, "_initializing", False):
61+
return
4862
del sys.modules[module_name]
4963

5064
MODULES_REQUIRING_CLEANUP = ("gevent",)
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
---
2+
fixes:
3+
- |
4+
Fix some modules being unloaded too soon when using pytest + ddtrace + gevent.

0 commit comments

Comments
 (0)