Skip to content

Commit 0fe5d98

Browse files
authored
Merge branch 'main' into codex/add-pdb-exception-chain-navigation
2 parents 92cdbd1 + 2aab7d4 commit 0fe5d98

7 files changed

Lines changed: 119 additions & 3 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,16 @@ releases are available on [PyPI](https://pypi.org/project/pytask) and
99

1010
- [#973](https://github.com/pytask-dev/pytask/pull/973) enables navigating chained
1111
exceptions in post-mortem PDB sessions on Python 3.13 and newer.
12+
- [#969](https://github.com/pytask-dev/pytask/pull/969) initializes readline before
13+
output capture so libedit-backed interactive prompts and debuggers remain responsive.
1214
- [#971](https://github.com/pytask-dev/pytask/pull/971) restores help text for
1315
PDB commands wrapped by pytask.
1416
- [#970](https://github.com/pytask-dev/pytask/pull/970) prevents tee-sys capture from
1517
replaying output that was already displayed when capture stops before its buffer is
1618
read.
19+
- [#972](https://github.com/pytask-dev/pytask/pull/972) uses
20+
`importlib.import_module` for dynamic imports of custom PDB classes and warning
21+
categories.
1722
- [#968](https://github.com/pytask-dev/pytask/pull/968) improves the performance of file
1823
descriptor capture for tasks that produce no output.
1924
- Documents the pytest provenance of the adapted debugging, marker, and warning

‎src/_pytask/capture.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,9 +99,21 @@ def pytask_parse_config(config: dict[str, Any]) -> None:
9999
config["show_capture"] = convert_to_enum(config["show_capture"], ShowCapture)
100100

101101

102+
def _readline_workaround() -> None:
103+
"""Import readline before it can attach to redirected standard streams.
104+
105+
GNU readline is not affected, but libedit can retain the file descriptors that are
106+
active when it is first imported. Importing it before capture starts keeps
107+
interactive input and debugging responsive on affected Python installations.
108+
"""
109+
with contextlib.suppress(ImportError):
110+
import readline # noqa: F401, PLC0415
111+
112+
102113
@hookimpl
103114
def pytask_post_parse(config: dict[str, Any]) -> None:
104115
"""Initialize the CaptureManager."""
116+
_readline_workaround()
105117
pluginmanager = config["pm"]
106118
capman = CaptureManager(config["capture"])
107119
pluginmanager.register(capman, "capturemanager")

‎src/_pytask/debugging.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from __future__ import annotations
88

99
import functools
10+
import importlib
1011
import pdb # noqa: T100
1112
import sys
1213
from typing import TYPE_CHECKING
@@ -173,8 +174,7 @@ def _import_pdb_cls(
173174
modname, classname = usepdb_cls
174175

175176
try:
176-
__import__(modname)
177-
mod = sys.modules[modname]
177+
mod = importlib.import_module(modname)
178178

179179
# Handle --pdbcls=pdb:pdb.Pdb (useful e.g. with pdbpp or pdbp).
180180
parts = classname.split(".")

‎src/_pytask/warnings_utils.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from __future__ import annotations
44

55
import functools
6+
import importlib
67
import re
78
import textwrap
89
import warnings
@@ -124,7 +125,7 @@ def _resolve_warning_category(category: str) -> type[Warning]:
124125
klass = category
125126
else:
126127
module, _, klass = category.rpartition(".")
127-
m = __import__(module, None, None, [klass])
128+
m = importlib.import_module(module)
128129
cat = getattr(m, klass)
129130
if not issubclass(cat, Warning):
130131
msg = f"{cat} is not a Warning subclass"

‎tests/test_capture.py‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from __future__ import annotations
22

3+
import builtins
34
import contextlib
45
import io
56
import os
@@ -31,6 +32,37 @@
3132
from collections.abc import Generator
3233

3334

35+
def test_readline_workaround_ignores_missing_module(monkeypatch):
36+
imported_modules = []
37+
original_import = builtins.__import__
38+
39+
def import_or_raise(name, *args, **kwargs):
40+
imported_modules.append(name)
41+
if name == "readline":
42+
raise ImportError
43+
return original_import(name, *args, **kwargs)
44+
45+
monkeypatch.setattr(builtins, "__import__", import_or_raise)
46+
47+
capture._readline_workaround()
48+
49+
assert imported_modules == ["readline"]
50+
51+
52+
def test_readline_workaround_runs_before_capture_starts(monkeypatch):
53+
events = []
54+
capman = Mock()
55+
capman.start_capturing.side_effect = lambda: events.append("capture")
56+
monkeypatch.setattr(
57+
capture, "_readline_workaround", lambda: events.append("readline")
58+
)
59+
monkeypatch.setattr(capture, "CaptureManager", lambda _method: capman)
60+
61+
capture.pytask_post_parse({"pm": Mock(), "capture": CaptureMethod.FD})
62+
63+
assert events == ["readline", "capture"]
64+
65+
3466
@pytest.mark.parametrize("show_capture", ["s", "no", "stdout", "stderr", "log", "all"])
3567
def test_show_capture(tmp_path, runner, show_capture):
3668
source = """

‎tests/test_debugging.py‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import sys
77
import textwrap
88
from contextlib import ExitStack as does_not_raise # noqa: N813
9+
from types import SimpleNamespace
910

1011
import click
1112
import pytest
@@ -104,6 +105,50 @@ def task_example():
104105
_flush(child)
105106

106107

108+
def test_import_pdb_cls_uses_import_module(monkeypatch):
109+
class CustomPdb(pdb.Pdb):
110+
pass
111+
112+
module = SimpleNamespace(CustomPdb=CustomPdb)
113+
imported = []
114+
115+
def import_module(name):
116+
imported.append(name)
117+
return module
118+
119+
monkeypatch.setattr("importlib.import_module", import_module)
120+
monkeypatch.setattr(
121+
PytaskPDB, "_config", {"pdbcls": ("package.debuggers", "CustomPdb")}
122+
)
123+
monkeypatch.setattr(PytaskPDB, "_wrapped_pdb_cls", None)
124+
125+
wrapped = PytaskPDB._import_pdb_cls(None, None) # type: ignore[arg-type]
126+
127+
assert imported == ["package.debuggers"]
128+
assert issubclass(wrapped, CustomPdb)
129+
130+
131+
@pytest.mark.skipif(not IS_PEXPECT_INSTALLED, reason="pexpect is not installed.")
132+
@pytest.mark.skipif(sys.platform == "win32", reason="pexpect cannot spawn on Windows.")
133+
def test_pdb_after_readline_is_imported_during_capture(tmp_path):
134+
source = """
135+
from pathlib import Path
136+
137+
def task_example():
138+
import readline
139+
140+
breakpoint()
141+
Path(__file__).with_name("continued.txt").touch()
142+
"""
143+
tmp_path.joinpath("task_module.py").write_text(textwrap.dedent(source))
144+
145+
child = pexpect.spawn(f"pytask {tmp_path.as_posix()}")
146+
child.expect("Pdb")
147+
child.sendline("continue")
148+
_flush(child)
149+
assert tmp_path.joinpath("continued.txt").exists()
150+
151+
107152
@pytest.mark.skipif(not IS_PEXPECT_INSTALLED, reason="pexpect is not installed.")
108153
@pytest.mark.skipif(sys.platform == "win32", reason="pexpect cannot spawn on Windows.")
109154
@pytest.mark.skipif(

‎tests/test_warnings.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,36 @@
22

33
import sys
44
import textwrap
5+
from types import SimpleNamespace
56

67
import pytest
78

9+
from _pytask.warnings_utils import _resolve_warning_category
810
from pytask import ExitCode
911
from pytask import build
1012
from pytask import cli
1113
from tests.conftest import run_in_subprocess
1214

1315

16+
def test_resolve_warning_category_uses_import_module(monkeypatch):
17+
class CustomWarning(Warning):
18+
pass
19+
20+
module = SimpleNamespace(CustomWarning=CustomWarning)
21+
imported = []
22+
23+
def import_module(name):
24+
imported.append(name)
25+
return module
26+
27+
monkeypatch.setattr("importlib.import_module", import_module)
28+
29+
result = _resolve_warning_category("package.warnings.CustomWarning")
30+
31+
assert imported == ["package.warnings"]
32+
assert result is CustomWarning
33+
34+
1435
@pytest.mark.parametrize(
1536
"disable_warnings",
1637
[pytest.param(True, marks=pytest.mark.filterwarnings("ignore:warning!!!")), False],

0 commit comments

Comments
 (0)