Skip to content

Commit 18f15a3

Browse files
authored
Merge pull request #12435 from bluetech/avoid-type-checking
Avoid some `TYPE_CHECKING`
2 parents db67107 + c07bbdf commit 18f15a3

File tree

10 files changed

+40
-48
lines changed

10 files changed

+40
-48
lines changed

src/_pytest/_code/code.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@
5555
if sys.version_info < (3, 11):
5656
from exceptiongroup import BaseExceptionGroup
5757

58-
_TracebackStyle = Literal["long", "short", "line", "no", "native", "value", "auto"]
58+
TracebackStyle = Literal["long", "short", "line", "no", "native", "value", "auto"]
5959

6060

6161
class Code:
@@ -628,7 +628,7 @@ def _getreprcrash(self) -> Optional["ReprFileLocation"]:
628628
def getrepr(
629629
self,
630630
showlocals: bool = False,
631-
style: _TracebackStyle = "long",
631+
style: TracebackStyle = "long",
632632
abspath: bool = False,
633633
tbfilter: Union[
634634
bool, Callable[["ExceptionInfo[BaseException]"], Traceback]
@@ -809,7 +809,7 @@ class FormattedExcinfo:
809809
fail_marker: ClassVar = "E"
810810

811811
showlocals: bool = False
812-
style: _TracebackStyle = "long"
812+
style: TracebackStyle = "long"
813813
abspath: bool = True
814814
tbfilter: Union[bool, Callable[[ExceptionInfo[BaseException]], Traceback]] = True
815815
funcargs: bool = False
@@ -1174,7 +1174,7 @@ def toterminal(self, tw: TerminalWriter) -> None:
11741174
class ReprTraceback(TerminalRepr):
11751175
reprentries: Sequence[Union["ReprEntry", "ReprEntryNative"]]
11761176
extraline: Optional[str]
1177-
style: _TracebackStyle
1177+
style: TracebackStyle
11781178

11791179
entrysep: ClassVar = "_ "
11801180

@@ -1208,7 +1208,7 @@ def __init__(self, tblines: Sequence[str]) -> None:
12081208
class ReprEntryNative(TerminalRepr):
12091209
lines: Sequence[str]
12101210

1211-
style: ClassVar[_TracebackStyle] = "native"
1211+
style: ClassVar[TracebackStyle] = "native"
12121212

12131213
def toterminal(self, tw: TerminalWriter) -> None:
12141214
tw.write("".join(self.lines))
@@ -1220,7 +1220,7 @@ class ReprEntry(TerminalRepr):
12201220
reprfuncargs: Optional["ReprFuncArgs"]
12211221
reprlocals: Optional["ReprLocals"]
12221222
reprfileloc: Optional["ReprFileLocation"]
1223-
style: _TracebackStyle
1223+
style: TracebackStyle
12241224

12251225
def _write_entry_lines(self, tw: TerminalWriter) -> None:
12261226
"""Write the source code portions of a list of traceback entries with syntax highlighting.

src/_pytest/config/__init__.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,10 @@
5454
import _pytest._code
5555
from _pytest._code import ExceptionInfo
5656
from _pytest._code import filter_traceback
57+
from _pytest._code.code import TracebackStyle
5758
from _pytest._io import TerminalWriter
59+
from _pytest.config.argparsing import Argument
60+
from _pytest.config.argparsing import Parser
5861
import _pytest.deprecated
5962
import _pytest.hookspec
6063
from _pytest.outcomes import fail
@@ -71,9 +74,7 @@
7174

7275

7376
if TYPE_CHECKING:
74-
from .argparsing import Argument
75-
from .argparsing import Parser
76-
from _pytest._code.code import _TracebackStyle
77+
from _pytest.cacheprovider import Cache
7778
from _pytest.terminal import TerminalReporter
7879

7980

@@ -1030,6 +1031,9 @@ class ArgsSource(enum.Enum):
10301031
#: 'testpaths' configuration value.
10311032
TESTPATHS = enum.auto()
10321033

1034+
# Set by cacheprovider plugin.
1035+
cache: Optional["Cache"]
1036+
10331037
def __init__(
10341038
self,
10351039
pluginmanager: PytestPluginManager,
@@ -1091,11 +1095,6 @@ def __init__(
10911095
self.args_source = Config.ArgsSource.ARGS
10921096
self.args: List[str] = []
10931097

1094-
if TYPE_CHECKING:
1095-
from _pytest.cacheprovider import Cache
1096-
1097-
self.cache: Optional[Cache] = None
1098-
10991098
@property
11001099
def rootpath(self) -> Path:
11011100
"""The path to the :ref:`rootdir <rootdir>`.
@@ -1175,7 +1174,7 @@ def notify_exception(
11751174
option: Optional[argparse.Namespace] = None,
11761175
) -> None:
11771176
if option and getattr(option, "fulltrace", False):
1178-
style: _TracebackStyle = "long"
1177+
style: TracebackStyle = "long"
11791178
else:
11801179
style = "native"
11811180
excrepr = excinfo.getrepr(

src/_pytest/debugging.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,12 @@
1313
from typing import Optional
1414
from typing import Tuple
1515
from typing import Type
16-
from typing import TYPE_CHECKING
1716
from typing import Union
1817
import unittest
1918

2019
from _pytest import outcomes
2120
from _pytest._code import ExceptionInfo
21+
from _pytest.capture import CaptureManager
2222
from _pytest.config import Config
2323
from _pytest.config import ConftestImportFailure
2424
from _pytest.config import hookimpl
@@ -27,11 +27,7 @@
2727
from _pytest.config.exceptions import UsageError
2828
from _pytest.nodes import Node
2929
from _pytest.reports import BaseReport
30-
31-
32-
if TYPE_CHECKING:
33-
from _pytest.capture import CaptureManager
34-
from _pytest.runner import CallInfo
30+
from _pytest.runner import CallInfo
3531

3632

3733
def _validate_usepdb_cls(value: str) -> Tuple[str, str]:
@@ -310,7 +306,7 @@ def pytest_pyfunc_call(self, pyfuncitem) -> Generator[None, object, object]:
310306
return (yield)
311307

312308

313-
def wrap_pytest_function_for_tracing(pyfuncitem):
309+
def wrap_pytest_function_for_tracing(pyfuncitem) -> None:
314310
"""Change the Python function object of the given Function item by a
315311
wrapper which actually enters pdb before calling the python function
316312
itself, effectively leaving the user in the pdb prompt in the first
@@ -322,14 +318,14 @@ def wrap_pytest_function_for_tracing(pyfuncitem):
322318
# python < 3.7.4) runcall's first param is `func`, which means we'd get
323319
# an exception if one of the kwargs to testfunction was called `func`.
324320
@functools.wraps(testfunction)
325-
def wrapper(*args, **kwargs):
321+
def wrapper(*args, **kwargs) -> None:
326322
func = functools.partial(testfunction, *args, **kwargs)
327323
_pdb.runcall(func)
328324

329325
pyfuncitem.obj = wrapper
330326

331327

332-
def maybe_wrap_pytest_function_for_tracing(pyfuncitem):
328+
def maybe_wrap_pytest_function_for_tracing(pyfuncitem) -> None:
333329
"""Wrap the given pytestfunct item for tracing support if --trace was given in
334330
the command line."""
335331
if pyfuncitem.config.getvalue("trace"):

src/_pytest/fixtures.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@
6060
from _pytest.deprecated import check_ispytest
6161
from _pytest.deprecated import MARKED_FIXTURE
6262
from _pytest.deprecated import YIELD_FIXTURE
63+
from _pytest.main import Session
6364
from _pytest.mark import Mark
6465
from _pytest.mark import ParameterSet
6566
from _pytest.mark.structures import MarkDecorator
@@ -78,7 +79,6 @@
7879

7980

8081
if TYPE_CHECKING:
81-
from _pytest.main import Session
8282
from _pytest.python import CallSpec2
8383
from _pytest.python import Function
8484
from _pytest.python import Metafunc

src/_pytest/main.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@
3838
from _pytest.config import UsageError
3939
from _pytest.config.argparsing import Parser
4040
from _pytest.config.compat import PathAwareHookProxy
41-
from _pytest.fixtures import FixtureManager
4241
from _pytest.outcomes import exit
4342
from _pytest.pathlib import absolutepath
4443
from _pytest.pathlib import bestrelpath
@@ -55,6 +54,8 @@
5554
if TYPE_CHECKING:
5655
from typing import Self
5756

57+
from _pytest.fixtures import FixtureManager
58+
5859

5960
def pytest_addoption(parser: Parser) -> None:
6061
parser.addini(
@@ -551,7 +552,7 @@ class Session(nodes.Collector):
551552
# Set on the session by runner.pytest_sessionstart.
552553
_setupstate: SetupState
553554
# Set on the session by fixtures.pytest_sessionstart.
554-
_fixturemanager: FixtureManager
555+
_fixturemanager: "FixtureManager"
555556
exitstatus: Union[int, ExitCode]
556557

557558
def __init__(self, config: Config) -> None:

src/_pytest/mark/structures.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
from _pytest.deprecated import check_ispytest
3232
from _pytest.deprecated import MARKED_FIXTURE
3333
from _pytest.outcomes import fail
34+
from _pytest.scope import _ScopeName
3435
from _pytest.warning_types import PytestUnknownMarkWarning
3536

3637

@@ -430,7 +431,6 @@ def store_mark(obj, mark: Mark, *, stacklevel: int = 2) -> None:
430431
# Typing for builtin pytest marks. This is cheating; it gives builtin marks
431432
# special privilege, and breaks modularity. But practicality beats purity...
432433
if TYPE_CHECKING:
433-
from _pytest.scope import _ScopeName
434434

435435
class _SkipMarkDecorator(MarkDecorator):
436436
@overload # type: ignore[override,no-overload-impl]

src/_pytest/nodes.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
from _pytest._code.code import ExceptionInfo
3131
from _pytest._code.code import TerminalRepr
3232
from _pytest._code.code import Traceback
33+
from _pytest._code.code import TracebackStyle
3334
from _pytest.compat import LEGACY_PATH
3435
from _pytest.config import Config
3536
from _pytest.config import ConftestImportFailure
@@ -49,7 +50,6 @@
4950
from typing import Self
5051

5152
# Imported here due to circular import.
52-
from _pytest._code.code import _TracebackStyle
5353
from _pytest.main import Session
5454

5555

@@ -416,7 +416,7 @@ def _traceback_filter(self, excinfo: ExceptionInfo[BaseException]) -> Traceback:
416416
def _repr_failure_py(
417417
self,
418418
excinfo: ExceptionInfo[BaseException],
419-
style: "Optional[_TracebackStyle]" = None,
419+
style: "Optional[TracebackStyle]" = None,
420420
) -> TerminalRepr:
421421
from _pytest.fixtures import FixtureLookupError
422422

@@ -474,7 +474,7 @@ def _repr_failure_py(
474474
def repr_failure(
475475
self,
476476
excinfo: ExceptionInfo[BaseException],
477-
style: "Optional[_TracebackStyle]" = None,
477+
style: "Optional[TracebackStyle]" = None,
478478
) -> Union[str, TerminalRepr]:
479479
"""Return a representation of a collection or test failure.
480480

src/_pytest/stepwise.py

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,14 @@
11
from typing import List
22
from typing import Optional
3-
from typing import TYPE_CHECKING
43

54
from _pytest import nodes
5+
from _pytest.cacheprovider import Cache
66
from _pytest.config import Config
77
from _pytest.config.argparsing import Parser
88
from _pytest.main import Session
99
from _pytest.reports import TestReport
10-
import pytest
1110

1211

13-
if TYPE_CHECKING:
14-
from _pytest.cacheprovider import Cache
15-
1612
STEPWISE_CACHE_DIR = "cache/stepwise"
1713

1814

@@ -37,7 +33,6 @@ def pytest_addoption(parser: Parser) -> None:
3733
)
3834

3935

40-
@pytest.hookimpl
4136
def pytest_configure(config: Config) -> None:
4237
if config.option.stepwise_skip:
4338
# allow --stepwise-skip to work on its own merits.

src/_pytest/unittest.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -41,10 +41,11 @@
4141

4242
import twisted.trial.unittest
4343

44-
_SysExcInfoType = Union[
45-
Tuple[Type[BaseException], BaseException, types.TracebackType],
46-
Tuple[None, None, None],
47-
]
44+
45+
_SysExcInfoType = Union[
46+
Tuple[Type[BaseException], BaseException, types.TracebackType],
47+
Tuple[None, None, None],
48+
]
4849

4950

5051
def pytest_pycollect_makeitem(
@@ -228,7 +229,7 @@ def teardown(self) -> None:
228229
def startTest(self, testcase: "unittest.TestCase") -> None:
229230
pass
230231

231-
def _addexcinfo(self, rawexcinfo: "_SysExcInfoType") -> None:
232+
def _addexcinfo(self, rawexcinfo: _SysExcInfoType) -> None:
232233
# Unwrap potential exception info (see twisted trial support below).
233234
rawexcinfo = getattr(rawexcinfo, "_rawexcinfo", rawexcinfo)
234235
try:
@@ -264,7 +265,7 @@ def _addexcinfo(self, rawexcinfo: "_SysExcInfoType") -> None:
264265
self.__dict__.setdefault("_excinfo", []).append(excinfo)
265266

266267
def addError(
267-
self, testcase: "unittest.TestCase", rawexcinfo: "_SysExcInfoType"
268+
self, testcase: "unittest.TestCase", rawexcinfo: _SysExcInfoType
268269
) -> None:
269270
try:
270271
if isinstance(rawexcinfo[1], exit.Exception):
@@ -274,7 +275,7 @@ def addError(
274275
self._addexcinfo(rawexcinfo)
275276

276277
def addFailure(
277-
self, testcase: "unittest.TestCase", rawexcinfo: "_SysExcInfoType"
278+
self, testcase: "unittest.TestCase", rawexcinfo: _SysExcInfoType
278279
) -> None:
279280
self._addexcinfo(rawexcinfo)
280281

@@ -287,7 +288,7 @@ def addSkip(self, testcase: "unittest.TestCase", reason: str) -> None:
287288
def addExpectedFailure(
288289
self,
289290
testcase: "unittest.TestCase",
290-
rawexcinfo: "_SysExcInfoType",
291+
rawexcinfo: _SysExcInfoType,
291292
reason: str = "",
292293
) -> None:
293294
try:

testing/code/test_excinfo.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828

2929

3030
if TYPE_CHECKING:
31-
from _pytest._code.code import _TracebackStyle
31+
from _pytest._code.code import TracebackStyle
3232

3333
if sys.version_info < (3, 11):
3434
from exceptiongroup import ExceptionGroup
@@ -925,7 +925,7 @@ def entry():
925925
)
926926
excinfo = pytest.raises(ValueError, mod.entry)
927927

928-
styles: tuple[_TracebackStyle, ...] = ("long", "short")
928+
styles: tuple[TracebackStyle, ...] = ("long", "short")
929929
for style in styles:
930930
p = FormattedExcinfo(style=style)
931931
reprtb = p.repr_traceback(excinfo)
@@ -1052,7 +1052,7 @@ def entry():
10521052
)
10531053
excinfo = pytest.raises(ValueError, mod.entry)
10541054

1055-
styles: tuple[_TracebackStyle, ...] = ("short", "long", "no")
1055+
styles: tuple[TracebackStyle, ...] = ("short", "long", "no")
10561056
for style in styles:
10571057
for showlocals in (True, False):
10581058
repr = excinfo.getrepr(style=style, showlocals=showlocals)

0 commit comments

Comments
 (0)