Merge pull request #11213 from bluetech/py38-literal

Use typing.Literal without TYPE_CHECKING checks
This commit is contained in:
Ran Benita 2023-07-16 23:17:12 +03:00 committed by GitHub
commit bf451d47a1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 40 additions and 62 deletions

View File

@ -25,14 +25,12 @@ from stat import S_ISREG
from typing import Any from typing import Any
from typing import Callable from typing import Callable
from typing import cast from typing import cast
from typing import Literal
from typing import overload from typing import overload
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from . import error from . import error
if TYPE_CHECKING:
from typing import Literal
# Moved from local.py. # Moved from local.py.
iswin32 = sys.platform == "win32" or (getattr(os, "_name", False) == "nt") iswin32 = sys.platform == "win32" or (getattr(os, "_name", False) == "nt")

View File

@ -9,12 +9,12 @@ from typing import cast
from typing import Dict from typing import Dict
from typing import final from typing import final
from typing import List from typing import List
from typing import Literal
from typing import Mapping from typing import Mapping
from typing import NoReturn from typing import NoReturn
from typing import Optional from typing import Optional
from typing import Sequence from typing import Sequence
from typing import Tuple from typing import Tuple
from typing import TYPE_CHECKING
from typing import Union from typing import Union
import _pytest._io import _pytest._io
@ -24,9 +24,6 @@ from _pytest.deprecated import ARGUMENT_TYPE_STR
from _pytest.deprecated import ARGUMENT_TYPE_STR_CHOICE from _pytest.deprecated import ARGUMENT_TYPE_STR_CHOICE
from _pytest.deprecated import check_ispytest from _pytest.deprecated import check_ispytest
if TYPE_CHECKING:
from typing_extensions import Literal
FILE_OR_DIR = "file_or_dir" FILE_OR_DIR = "file_or_dir"
@ -177,7 +174,7 @@ class Parser:
name: str, name: str,
help: str, help: str,
type: Optional[ type: Optional[
"Literal['string', 'paths', 'pathlist', 'args', 'linelist', 'bool']" Literal["string", "paths", "pathlist", "args", "linelist", "bool"]
] = None, ] = None,
default: Any = None, default: Any = None,
) -> None: ) -> None:

View File

@ -60,6 +60,7 @@ from _pytest.outcomes import skip
from _pytest.outcomes import TEST_OUTCOME from _pytest.outcomes import TEST_OUTCOME
from _pytest.pathlib import absolutepath from _pytest.pathlib import absolutepath
from _pytest.pathlib import bestrelpath from _pytest.pathlib import bestrelpath
from _pytest.scope import _ScopeName
from _pytest.scope import HIGH_SCOPES from _pytest.scope import HIGH_SCOPES
from _pytest.scope import Scope from _pytest.scope import Scope
from _pytest.stash import StashKey from _pytest.stash import StashKey
@ -68,7 +69,6 @@ from _pytest.stash import StashKey
if TYPE_CHECKING: if TYPE_CHECKING:
from typing import Deque from typing import Deque
from _pytest.scope import _ScopeName
from _pytest.main import Session from _pytest.main import Session
from _pytest.python import CallSpec2 from _pytest.python import CallSpec2
from _pytest.python import Function from _pytest.python import Function
@ -444,7 +444,7 @@ class FixtureRequest:
self.param: Any self.param: Any
@property @property
def scope(self) -> "_ScopeName": def scope(self) -> _ScopeName:
"""Scope string, one of "function", "class", "module", "package", "session".""" """Scope string, one of "function", "class", "module", "package", "session"."""
return self._scope.value return self._scope.value
@ -949,10 +949,10 @@ def _teardown_yield_fixture(fixturefunc, it) -> None:
def _eval_scope_callable( def _eval_scope_callable(
scope_callable: "Callable[[str, Config], _ScopeName]", scope_callable: Callable[[str, Config], _ScopeName],
fixture_name: str, fixture_name: str,
config: Config, config: Config,
) -> "_ScopeName": ) -> _ScopeName:
try: try:
# Type ignored because there is no typing mechanism to specify # Type ignored because there is no typing mechanism to specify
# keyword arguments, currently. # keyword arguments, currently.
@ -987,7 +987,7 @@ class FixtureDef(Generic[FixtureValue]):
baseid: Optional[str], baseid: Optional[str],
argname: str, argname: str,
func: "_FixtureFunc[FixtureValue]", func: "_FixtureFunc[FixtureValue]",
scope: Union[Scope, "_ScopeName", Callable[[str, Config], "_ScopeName"], None], scope: Union[Scope, _ScopeName, Callable[[str, Config], _ScopeName], None],
params: Optional[Sequence[object]], params: Optional[Sequence[object]],
unittest: bool = False, unittest: bool = False,
ids: Optional[ ids: Optional[
@ -1048,7 +1048,7 @@ class FixtureDef(Generic[FixtureValue]):
self._finalizers: Final[List[Callable[[], object]]] = [] self._finalizers: Final[List[Callable[[], object]]] = []
@property @property
def scope(self) -> "_ScopeName": def scope(self) -> _ScopeName:
"""Scope string, one of "function", "class", "module", "package", "session".""" """Scope string, one of "function", "class", "module", "package", "session"."""
return self._scope.value return self._scope.value

View File

@ -18,7 +18,7 @@ from _pytest.deprecated import WARNING_CMDLINE_PREPARSE_HOOK
if TYPE_CHECKING: if TYPE_CHECKING:
import pdb import pdb
import warnings import warnings
from typing_extensions import Literal from typing import Literal
from _pytest._code.code import ExceptionRepr from _pytest._code.code import ExceptionRepr
from _pytest._code.code import ExceptionInfo from _pytest._code.code import ExceptionInfo

View File

@ -16,6 +16,7 @@ from typing import Dict
from typing import final from typing import final
from typing import Generator from typing import Generator
from typing import List from typing import List
from typing import Literal
from typing import Mapping from typing import Mapping
from typing import Optional from typing import Optional
from typing import Tuple from typing import Tuple
@ -41,8 +42,6 @@ from _pytest.terminal import TerminalReporter
if TYPE_CHECKING: if TYPE_CHECKING:
logging_StreamHandler = logging.StreamHandler[StringIO] logging_StreamHandler = logging.StreamHandler[StringIO]
from typing_extensions import Literal
else: else:
logging_StreamHandler = logging.StreamHandler logging_StreamHandler = logging.StreamHandler

View File

@ -13,13 +13,13 @@ from typing import final
from typing import FrozenSet from typing import FrozenSet
from typing import Iterator from typing import Iterator
from typing import List from typing import List
from typing import Literal
from typing import Optional from typing import Optional
from typing import overload from typing import overload
from typing import Sequence from typing import Sequence
from typing import Set from typing import Set
from typing import Tuple from typing import Tuple
from typing import Type from typing import Type
from typing import TYPE_CHECKING
from typing import Union from typing import Union
import _pytest._code import _pytest._code
@ -43,10 +43,6 @@ from _pytest.runner import collect_one_node
from _pytest.runner import SetupState from _pytest.runner import SetupState
if TYPE_CHECKING:
from typing_extensions import Literal
def pytest_addoption(parser: Parser) -> None: def pytest_addoption(parser: Parser) -> None:
parser.addini( parser.addini(
"norecursedirs", "norecursedirs",

View File

@ -20,13 +20,13 @@ from typing import Generator
from typing import Iterable from typing import Iterable
from typing import Iterator from typing import Iterator
from typing import List from typing import List
from typing import Literal
from typing import Mapping from typing import Mapping
from typing import Optional from typing import Optional
from typing import Pattern from typing import Pattern
from typing import Sequence from typing import Sequence
from typing import Set from typing import Set
from typing import Tuple from typing import Tuple
from typing import TYPE_CHECKING
from typing import Union from typing import Union
import _pytest import _pytest
@ -75,16 +75,12 @@ from _pytest.pathlib import import_path
from _pytest.pathlib import ImportPathMismatchError from _pytest.pathlib import ImportPathMismatchError
from _pytest.pathlib import parts from _pytest.pathlib import parts
from _pytest.pathlib import visit from _pytest.pathlib import visit
from _pytest.scope import _ScopeName
from _pytest.scope import Scope from _pytest.scope import Scope
from _pytest.warning_types import PytestCollectionWarning from _pytest.warning_types import PytestCollectionWarning
from _pytest.warning_types import PytestReturnNotNoneWarning from _pytest.warning_types import PytestReturnNotNoneWarning
from _pytest.warning_types import PytestUnhandledCoroutineWarning from _pytest.warning_types import PytestUnhandledCoroutineWarning
if TYPE_CHECKING:
from typing_extensions import Literal
from _pytest.scope import _ScopeName
_PYTEST_DIR = Path(_pytest.__file__).parent _PYTEST_DIR = Path(_pytest.__file__).parent
@ -1236,7 +1232,7 @@ class Metafunc:
ids: Optional[ ids: Optional[
Union[Iterable[Optional[object]], Callable[[Any], Optional[object]]] Union[Iterable[Optional[object]], Callable[[Any], Optional[object]]]
] = None, ] = None,
scope: "Optional[_ScopeName]" = None, scope: Optional[_ScopeName] = None,
*, *,
_param_mark: Optional[Mark] = None, _param_mark: Optional[Mark] = None,
) -> None: ) -> None:

View File

@ -9,6 +9,7 @@ from typing import final
from typing import Iterable from typing import Iterable
from typing import Iterator from typing import Iterator
from typing import List from typing import List
from typing import Literal
from typing import Mapping from typing import Mapping
from typing import NoReturn from typing import NoReturn
from typing import Optional from typing import Optional
@ -36,8 +37,6 @@ from _pytest.nodes import Item
from _pytest.outcomes import skip from _pytest.outcomes import skip
if TYPE_CHECKING: if TYPE_CHECKING:
from typing_extensions import Literal
from _pytest.runner import CallInfo from _pytest.runner import CallInfo
@ -64,7 +63,7 @@ class BaseReport:
] ]
sections: List[Tuple[str, str]] sections: List[Tuple[str, str]]
nodeid: str nodeid: str
outcome: "Literal['passed', 'failed', 'skipped']" outcome: Literal["passed", "failed", "skipped"]
def __init__(self, **kw: Any) -> None: def __init__(self, **kw: Any) -> None:
self.__dict__.update(kw) self.__dict__.update(kw)
@ -258,11 +257,11 @@ class TestReport(BaseReport):
nodeid: str, nodeid: str,
location: Tuple[str, Optional[int], str], location: Tuple[str, Optional[int], str],
keywords: Mapping[str, Any], keywords: Mapping[str, Any],
outcome: "Literal['passed', 'failed', 'skipped']", outcome: Literal["passed", "failed", "skipped"],
longrepr: Union[ longrepr: Union[
None, ExceptionInfo[BaseException], Tuple[str, int, str], str, TerminalRepr None, ExceptionInfo[BaseException], Tuple[str, int, str], str, TerminalRepr
], ],
when: "Literal['setup', 'call', 'teardown']", when: Literal["setup", "call", "teardown"],
sections: Iterable[Tuple[str, str]] = (), sections: Iterable[Tuple[str, str]] = (),
duration: float = 0, duration: float = 0,
start: float = 0, start: float = 0,

View File

@ -9,6 +9,7 @@ from typing import Dict
from typing import final from typing import final
from typing import Generic from typing import Generic
from typing import List from typing import List
from typing import Literal
from typing import Optional from typing import Optional
from typing import Tuple from typing import Tuple
from typing import Type from typing import Type
@ -38,8 +39,6 @@ if sys.version_info[:2] < (3, 11):
from exceptiongroup import BaseExceptionGroup from exceptiongroup import BaseExceptionGroup
if TYPE_CHECKING: if TYPE_CHECKING:
from typing_extensions import Literal
from _pytest.main import Session from _pytest.main import Session
from _pytest.terminal import TerminalReporter from _pytest.terminal import TerminalReporter
@ -184,7 +183,7 @@ def pytest_runtest_teardown(item: Item, nextitem: Optional[Item]) -> None:
def _update_current_test_var( def _update_current_test_var(
item: Item, when: Optional["Literal['setup', 'call', 'teardown']"] item: Item, when: Optional[Literal["setup", "call", "teardown"]]
) -> None: ) -> None:
"""Update :envvar:`PYTEST_CURRENT_TEST` to reflect the current item and stage. """Update :envvar:`PYTEST_CURRENT_TEST` to reflect the current item and stage.
@ -217,7 +216,7 @@ def pytest_report_teststatus(report: BaseReport) -> Optional[Tuple[str, str, str
def call_and_report( def call_and_report(
item: Item, when: "Literal['setup', 'call', 'teardown']", log: bool = True, **kwds item: Item, when: Literal["setup", "call", "teardown"], log: bool = True, **kwds
) -> TestReport: ) -> TestReport:
call = call_runtest_hook(item, when, **kwds) call = call_runtest_hook(item, when, **kwds)
hook = item.ihook hook = item.ihook
@ -245,7 +244,7 @@ def check_interactive_exception(call: "CallInfo[object]", report: BaseReport) ->
def call_runtest_hook( def call_runtest_hook(
item: Item, when: "Literal['setup', 'call', 'teardown']", **kwds item: Item, when: Literal["setup", "call", "teardown"], **kwds
) -> "CallInfo[None]": ) -> "CallInfo[None]":
if when == "setup": if when == "setup":
ihook: Callable[..., None] = item.ihook.pytest_runtest_setup ihook: Callable[..., None] = item.ihook.pytest_runtest_setup
@ -281,7 +280,7 @@ class CallInfo(Generic[TResult]):
#: The call duration, in seconds. #: The call duration, in seconds.
duration: float duration: float
#: The context of invocation: "collect", "setup", "call" or "teardown". #: The context of invocation: "collect", "setup", "call" or "teardown".
when: "Literal['collect', 'setup', 'call', 'teardown']" when: Literal["collect", "setup", "call", "teardown"]
def __init__( def __init__(
self, self,
@ -290,7 +289,7 @@ class CallInfo(Generic[TResult]):
start: float, start: float,
stop: float, stop: float,
duration: float, duration: float,
when: "Literal['collect', 'setup', 'call', 'teardown']", when: Literal["collect", "setup", "call", "teardown"],
*, *,
_ispytest: bool = False, _ispytest: bool = False,
) -> None: ) -> None:
@ -319,7 +318,7 @@ class CallInfo(Generic[TResult]):
def from_call( def from_call(
cls, cls,
func: "Callable[[], TResult]", func: "Callable[[], TResult]",
when: "Literal['collect', 'setup', 'call', 'teardown']", when: Literal["collect", "setup", "call", "teardown"],
reraise: Optional[ reraise: Optional[
Union[Type[BaseException], Tuple[Type[BaseException], ...]] Union[Type[BaseException], Tuple[Type[BaseException], ...]]
] = None, ] = None,

View File

@ -9,13 +9,11 @@ Also this makes the module light to import, as it should.
""" """
from enum import Enum from enum import Enum
from functools import total_ordering from functools import total_ordering
from typing import Literal
from typing import Optional from typing import Optional
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from typing_extensions import Literal
_ScopeName = Literal["session", "package", "module", "class", "function"] _ScopeName = Literal["session", "package", "module", "class", "function"]
@total_ordering @total_ordering
@ -33,11 +31,11 @@ class Scope(Enum):
""" """
# Scopes need to be listed from lower to higher. # Scopes need to be listed from lower to higher.
Function: "_ScopeName" = "function" Function: _ScopeName = "function"
Class: "_ScopeName" = "class" Class: _ScopeName = "class"
Module: "_ScopeName" = "module" Module: _ScopeName = "module"
Package: "_ScopeName" = "package" Package: _ScopeName = "package"
Session: "_ScopeName" = "session" Session: _ScopeName = "session"
def next_lower(self) -> "Scope": def next_lower(self) -> "Scope":
"""Return the next lower scope.""" """Return the next lower scope."""
@ -60,7 +58,7 @@ class Scope(Enum):
@classmethod @classmethod
def from_user( def from_user(
cls, scope_name: "_ScopeName", descr: str, where: Optional[str] = None cls, scope_name: _ScopeName, descr: str, where: Optional[str] = None
) -> "Scope": ) -> "Scope":
""" """
Given a scope name from the user, return the equivalent Scope enum. Should be used Given a scope name from the user, return the equivalent Scope enum. Should be used

View File

@ -20,6 +20,7 @@ from typing import Dict
from typing import final from typing import final
from typing import Generator from typing import Generator
from typing import List from typing import List
from typing import Literal
from typing import Mapping from typing import Mapping
from typing import NamedTuple from typing import NamedTuple
from typing import Optional from typing import Optional
@ -54,8 +55,6 @@ from _pytest.reports import CollectReport
from _pytest.reports import TestReport from _pytest.reports import TestReport
if TYPE_CHECKING: if TYPE_CHECKING:
from typing_extensions import Literal
from _pytest.main import Session from _pytest.main import Session
@ -366,7 +365,7 @@ class TerminalReporter:
self._already_displayed_warnings: Optional[int] = None self._already_displayed_warnings: Optional[int] = None
self._keyboardinterrupt_memo: Optional[ExceptionRepr] = None self._keyboardinterrupt_memo: Optional[ExceptionRepr] = None
def _determine_show_progress_info(self) -> "Literal['progress', 'count', False]": def _determine_show_progress_info(self) -> Literal["progress", "count", False]:
"""Return whether we should display progress information based on the current config.""" """Return whether we should display progress information based on the current config."""
# do not show progress if we are not capturing output (#3038) unless explicitly # do not show progress if we are not capturing output (#3038) unless explicitly
# overridden by progress-even-when-capture-no # overridden by progress-even-when-capture-no

View File

@ -48,13 +48,13 @@ class TempPathFactory:
_trace: Any _trace: Any
_basetemp: Optional[Path] _basetemp: Optional[Path]
_retention_count: int _retention_count: int
_retention_policy: "RetentionType" _retention_policy: RetentionType
def __init__( def __init__(
self, self,
given_basetemp: Optional[Path], given_basetemp: Optional[Path],
retention_count: int, retention_count: int,
retention_policy: "RetentionType", retention_policy: RetentionType,
trace, trace,
basetemp: Optional[Path] = None, basetemp: Optional[Path] = None,
*, *,

View File

@ -2,8 +2,8 @@ import sys
import warnings import warnings
from contextlib import contextmanager from contextlib import contextmanager
from typing import Generator from typing import Generator
from typing import Literal
from typing import Optional from typing import Optional
from typing import TYPE_CHECKING
import pytest import pytest
from _pytest.config import apply_warning_filters from _pytest.config import apply_warning_filters
@ -13,9 +13,6 @@ from _pytest.main import Session
from _pytest.nodes import Item from _pytest.nodes import Item
from _pytest.terminal import TerminalReporter from _pytest.terminal import TerminalReporter
if TYPE_CHECKING:
from typing_extensions import Literal
def pytest_configure(config: Config) -> None: def pytest_configure(config: Config) -> None:
config.addinivalue_line( config.addinivalue_line(
@ -29,7 +26,7 @@ def pytest_configure(config: Config) -> None:
def catch_warnings_for_item( def catch_warnings_for_item(
config: Config, config: Config,
ihook, ihook,
when: "Literal['config', 'collect', 'runtest']", when: Literal["config", "collect", "runtest"],
item: Optional[Item], item: Optional[Item],
) -> Generator[None, None, None]: ) -> Generator[None, None, None]:
"""Context manager that catches warnings generated in the contained execution block. """Context manager that catches warnings generated in the contained execution block.