Merge pull request #7840 from asottile/py36_typing_Type

py36+: from typing import Type: no longer need guard
This commit is contained in:
Anthony Sottile 2020-10-03 07:44:06 -07:00 committed by GitHub
commit 6ed07a1c25
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
22 changed files with 63 additions and 93 deletions

View File

@ -21,6 +21,7 @@ from typing import Pattern
from typing import Sequence
from typing import Set
from typing import Tuple
from typing import Type
from typing import TYPE_CHECKING
from typing import TypeVar
from typing import Union
@ -44,7 +45,6 @@ from _pytest.compat import overload
from _pytest.pathlib import Path
if TYPE_CHECKING:
from typing import Type
from typing_extensions import Literal
from weakref import ReferenceType
@ -421,14 +421,14 @@ class ExceptionInfo(Generic[_E]):
_assert_start_repr = "AssertionError('assert "
_excinfo = attr.ib(type=Optional[Tuple["Type[_E]", "_E", TracebackType]])
_excinfo = attr.ib(type=Optional[Tuple[Type["_E"], "_E", TracebackType]])
_striptext = attr.ib(type=str, default="")
_traceback = attr.ib(type=Optional[Traceback], default=None)
@classmethod
def from_exc_info(
cls,
exc_info: Tuple["Type[_E]", "_E", TracebackType],
exc_info: Tuple[Type[_E], _E, TracebackType],
exprinfo: Optional[str] = None,
) -> "ExceptionInfo[_E]":
"""Return an ExceptionInfo for an existing exc_info tuple.
@ -479,13 +479,13 @@ class ExceptionInfo(Generic[_E]):
"""Return an unfilled ExceptionInfo."""
return cls(None)
def fill_unfilled(self, exc_info: Tuple["Type[_E]", _E, TracebackType]) -> None:
def fill_unfilled(self, exc_info: Tuple[Type[_E], _E, TracebackType]) -> None:
"""Fill an unfilled ExceptionInfo created with ``for_later()``."""
assert self._excinfo is None, "ExceptionInfo was already filled"
self._excinfo = exc_info
@property
def type(self) -> "Type[_E]":
def type(self) -> Type[_E]:
"""The exception class."""
assert (
self._excinfo is not None
@ -551,7 +551,7 @@ class ExceptionInfo(Generic[_E]):
return text
def errisinstance(
self, exc: Union["Type[BaseException]", Tuple["Type[BaseException]", ...]]
self, exc: Union[Type[BaseException], Tuple[Type[BaseException], ...]]
) -> bool:
"""Return True if the exception is an instance of exc.

View File

@ -24,7 +24,6 @@ from _pytest.outcomes import TEST_OUTCOME
if TYPE_CHECKING:
from typing import NoReturn
from typing import Type
from typing_extensions import Final
@ -349,6 +348,7 @@ else:
if sys.version_info >= (3, 8):
from functools import cached_property as cached_property
else:
from typing import Type
class cached_property(Generic[_S, _T]):
__slots__ = ("func", "__doc__")
@ -359,13 +359,13 @@ else:
@overload
def __get__(
self, instance: None, owner: Optional["Type[_S]"] = ...
self, instance: None, owner: Optional[Type[_S]] = ...
) -> "cached_property[_S, _T]":
...
@overload # noqa: F811
def __get__( # noqa: F811
self, instance: _S, owner: Optional["Type[_S]"] = ...
self, instance: _S, owner: Optional[Type[_S]] = ...
) -> _T:
...

View File

@ -26,6 +26,7 @@ from typing import Sequence
from typing import Set
from typing import TextIO
from typing import Tuple
from typing import Type
from typing import TYPE_CHECKING
from typing import Union
@ -56,7 +57,6 @@ from _pytest.store import Store
from _pytest.warning_types import PytestConfigWarning
if TYPE_CHECKING:
from typing import Type
from _pytest._code.code import _TracebackStyle
from _pytest.terminal import TerminalReporter
@ -104,7 +104,7 @@ class ConftestImportFailure(Exception):
def __init__(
self,
path: py.path.local,
excinfo: Tuple["Type[Exception]", Exception, TracebackType],
excinfo: Tuple[Type[Exception], Exception, TracebackType],
) -> None:
super().__init__(path, excinfo)
self.path = path
@ -1560,7 +1560,7 @@ def _strtobool(val: str) -> bool:
@lru_cache(maxsize=50)
def parse_warning_filter(
arg: str, *, escape: bool
) -> "Tuple[str, str, Type[Warning], str, int]":
) -> Tuple[str, str, Type[Warning], str, int]:
"""Parse a warnings filter string.
This is copied from warnings._setoption, but does not apply the filter,
@ -1573,9 +1573,7 @@ def parse_warning_filter(
parts.append("")
action_, message, category_, module, lineno_ = [s.strip() for s in parts]
action = warnings._getaction(action_) # type: str # type: ignore[attr-defined]
category = warnings._getcategory(
category_
) # type: Type[Warning] # type: ignore[attr-defined]
category: Type[Warning] = warnings._getcategory(category_) # type: ignore[attr-defined]
if message and escape:
message = re.escape(message)
if module and escape:

View File

@ -9,6 +9,7 @@ from typing import Generator
from typing import List
from typing import Optional
from typing import Tuple
from typing import Type
from typing import TYPE_CHECKING
from typing import Union
@ -24,8 +25,6 @@ from _pytest.nodes import Node
from _pytest.reports import BaseReport
if TYPE_CHECKING:
from typing import Type
from _pytest.capture import CaptureManager
from _pytest.runner import CallInfo

View File

@ -17,6 +17,7 @@ from typing import Optional
from typing import Pattern
from typing import Sequence
from typing import Tuple
from typing import Type
from typing import TYPE_CHECKING
from typing import Union
@ -40,7 +41,6 @@ from _pytest.warning_types import PytestWarning
if TYPE_CHECKING:
import doctest
from typing import Type
DOCTEST_REPORT_CHOICE_NONE = "none"
DOCTEST_REPORT_CHOICE_CDIFF = "cdiff"
@ -168,7 +168,7 @@ class MultipleDoctestFailures(Exception):
self.failures = failures
def _init_runner_class() -> "Type[doctest.DocTestRunner]":
def _init_runner_class() -> Type["doctest.DocTestRunner"]:
import doctest
class PytestDoctestRunner(doctest.DebugRunner):
@ -204,7 +204,7 @@ def _init_runner_class() -> "Type[doctest.DocTestRunner]":
out,
test: "doctest.DocTest",
example: "doctest.Example",
exc_info: "Tuple[Type[BaseException], BaseException, types.TracebackType]",
exc_info: Tuple[Type[BaseException], BaseException, types.TracebackType],
) -> None:
if isinstance(exc_info[1], OutcomeException):
raise exc_info[1]
@ -568,7 +568,7 @@ def _setup_fixtures(doctest_item: DoctestItem) -> FixtureRequest:
return fixture_request
def _init_checker_class() -> "Type[doctest.OutputChecker]":
def _init_checker_class() -> Type["doctest.OutputChecker"]:
import doctest
import re

View File

@ -19,6 +19,7 @@ from typing import Optional
from typing import Sequence
from typing import Set
from typing import Tuple
from typing import Type
from typing import TYPE_CHECKING
from typing import TypeVar
from typing import Union
@ -57,7 +58,6 @@ from _pytest.pathlib import absolutepath
if TYPE_CHECKING:
from typing import Deque
from typing import NoReturn
from typing import Type
from typing_extensions import Literal
from _pytest import nodes
@ -91,7 +91,7 @@ _FixtureCachedResult = Union[
# Cache key.
object,
# Exc info if raised.
Tuple["Type[BaseException]", BaseException, TracebackType],
Tuple[Type[BaseException], BaseException, TracebackType],
],
]

View File

@ -14,6 +14,7 @@ from typing import Optional
from typing import Sequence
from typing import Set
from typing import Tuple
from typing import Type
from typing import TYPE_CHECKING
from typing import Union
@ -44,7 +45,6 @@ from _pytest.runner import SetupState
if TYPE_CHECKING:
from typing import Type
from typing_extensions import Literal

View File

@ -14,6 +14,7 @@ from typing import Optional
from typing import Sequence
from typing import Set
from typing import Tuple
from typing import Type
from typing import TYPE_CHECKING
from typing import TypeVar
from typing import Union
@ -31,8 +32,6 @@ from _pytest.outcomes import fail
from _pytest.warning_types import PytestUnknownMarkWarning
if TYPE_CHECKING:
from typing import Type
from ..nodes import Node
@ -417,9 +416,7 @@ if TYPE_CHECKING:
*conditions: Union[str, bool],
reason: str = ...,
run: bool = ...,
raises: Union[
"Type[BaseException]", Tuple["Type[BaseException]", ...]
] = ...,
raises: Union[Type[BaseException], Tuple[Type[BaseException], ...]] = ...,
strict: bool = ...
) -> MarkDecorator:
...

View File

@ -10,6 +10,7 @@ from typing import List
from typing import Optional
from typing import Set
from typing import Tuple
from typing import Type
from typing import TYPE_CHECKING
from typing import TypeVar
from typing import Union
@ -36,8 +37,6 @@ from _pytest.pathlib import Path
from _pytest.store import Store
if TYPE_CHECKING:
from typing import Type
# Imported here due to circular import.
from _pytest.main import Session
from _pytest.warning_types import PytestWarning
@ -350,7 +349,7 @@ class Node(metaclass=NodeMeta):
"""
self.session._setupstate.addfinalizer(fin, self)
def getparent(self, cls: "Type[_NodeType]") -> Optional[_NodeType]:
def getparent(self, cls: Type[_NodeType]) -> Optional[_NodeType]:
"""Get the next parent node (including self) which is an instance of
the given class."""
current = self # type: Optional[Node]

View File

@ -5,13 +5,13 @@ from typing import Any
from typing import Callable
from typing import cast
from typing import Optional
from typing import Type
from typing import TypeVar
TYPE_CHECKING = False # Avoid circular import through compat.
if TYPE_CHECKING:
from typing import NoReturn
from typing import Type # noqa: F401 (used in type string)
from typing_extensions import Protocol
else:
# typing.Protocol is only available starting from Python 3.8. It is also
@ -84,7 +84,7 @@ class Exit(Exception):
# Ideally would just be `exit.Exception = Exit` etc.
_F = TypeVar("_F", bound=Callable[..., object])
_ET = TypeVar("_ET", bound="Type[BaseException]")
_ET = TypeVar("_ET", bound=Type[BaseException])
class _WithException(Protocol[_F, _ET]):

View File

@ -18,6 +18,7 @@ from typing import List
from typing import Optional
from typing import Sequence
from typing import Tuple
from typing import Type
from typing import TYPE_CHECKING
from typing import Union
from weakref import WeakKeyDictionary
@ -49,7 +50,6 @@ from _pytest.reports import TestReport
from _pytest.tmpdir import TempdirFactory
if TYPE_CHECKING:
from typing import Type
from typing_extensions import Literal
import pexpect
@ -420,7 +420,7 @@ def linecomp() -> "LineComp":
@pytest.fixture(name="LineMatcher")
def LineMatcher_fixture(request: FixtureRequest) -> "Type[LineMatcher]":
def LineMatcher_fixture(request: FixtureRequest) -> Type["LineMatcher"]:
"""A reference to the :class: `LineMatcher`.
This is instantiable with a list of lines (without their trailing newlines).

View File

@ -22,6 +22,7 @@ from typing import Optional
from typing import Sequence
from typing import Set
from typing import Tuple
from typing import Type
from typing import TYPE_CHECKING
from typing import Union
@ -72,7 +73,6 @@ from _pytest.warning_types import PytestCollectionWarning
from _pytest.warning_types import PytestUnhandledCoroutineWarning
if TYPE_CHECKING:
from typing import Type
from typing_extensions import Literal
from _pytest.fixtures import _Scope

View File

@ -13,7 +13,7 @@ from typing import Generic
from typing import Optional
from typing import Pattern
from typing import Tuple
from typing import TYPE_CHECKING
from typing import Type
from typing import TypeVar
from typing import Union
@ -23,9 +23,6 @@ from _pytest.compat import overload
from _pytest.compat import STRING_TYPES
from _pytest.outcomes import fail
if TYPE_CHECKING:
from typing import Type
def _non_numeric_type_error(value, at: Optional[str]) -> TypeError:
at_str = " at {}".format(at) if at else ""
@ -560,7 +557,7 @@ _E = TypeVar("_E", bound=BaseException)
@overload
def raises(
expected_exception: Union["Type[_E]", Tuple["Type[_E]", ...]],
expected_exception: Union[Type[_E], Tuple[Type[_E], ...]],
*,
match: Optional[Union[str, Pattern[str]]] = ...
) -> "RaisesContext[_E]":
@ -569,7 +566,7 @@ def raises(
@overload # noqa: F811
def raises( # noqa: F811
expected_exception: Union["Type[_E]", Tuple["Type[_E]", ...]],
expected_exception: Union[Type[_E], Tuple[Type[_E], ...]],
func: Callable[..., Any],
*args: Any,
**kwargs: Any
@ -578,9 +575,7 @@ def raises( # noqa: F811
def raises( # noqa: F811
expected_exception: Union["Type[_E]", Tuple["Type[_E]", ...]],
*args: Any,
**kwargs: Any
expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], *args: Any, **kwargs: Any
) -> Union["RaisesContext[_E]", _pytest._code.ExceptionInfo[_E]]:
r"""Assert that a code block/function call raises ``expected_exception``
or raise a failure exception otherwise.
@ -738,7 +733,7 @@ raises.Exception = fail.Exception # type: ignore
class RaisesContext(Generic[_E]):
def __init__(
self,
expected_exception: Union["Type[_E]", Tuple["Type[_E]", ...]],
expected_exception: Union[Type[_E], Tuple[Type[_E], ...]],
message: str,
match_expr: Optional[Union[str, Pattern[str]]] = None,
) -> None:
@ -753,7 +748,7 @@ class RaisesContext(Generic[_E]):
def __exit__(
self,
exc_type: Optional["Type[BaseException]"],
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> bool:
@ -764,9 +759,7 @@ class RaisesContext(Generic[_E]):
if not issubclass(exc_type, self.expected_exception):
return False
# Cast to narrow the exception type now that it's verified.
exc_info = cast(
Tuple["Type[_E]", _E, TracebackType], (exc_type, exc_val, exc_tb)
)
exc_info = cast(Tuple[Type[_E], _E, TracebackType], (exc_type, exc_val, exc_tb))
self.excinfo.fill_unfilled(exc_info)
if self.match_expr is not None:
self.excinfo.match(self.match_expr)

View File

@ -10,7 +10,7 @@ from typing import List
from typing import Optional
from typing import Pattern
from typing import Tuple
from typing import TYPE_CHECKING
from typing import Type
from typing import TypeVar
from typing import Union
@ -19,9 +19,6 @@ from _pytest.compat import overload
from _pytest.fixtures import fixture
from _pytest.outcomes import fail
if TYPE_CHECKING:
from typing import Type
T = TypeVar("T")
@ -86,7 +83,7 @@ def deprecated_call( # noqa: F811
@overload
def warns(
expected_warning: Optional[Union["Type[Warning]", Tuple["Type[Warning]", ...]]],
expected_warning: Optional[Union[Type[Warning], Tuple[Type[Warning], ...]]],
*,
match: Optional[Union[str, Pattern[str]]] = ...
) -> "WarningsChecker":
@ -95,7 +92,7 @@ def warns(
@overload # noqa: F811
def warns( # noqa: F811
expected_warning: Optional[Union["Type[Warning]", Tuple["Type[Warning]", ...]]],
expected_warning: Optional[Union[Type[Warning], Tuple[Type[Warning], ...]]],
func: Callable[..., T],
*args: Any,
**kwargs: Any
@ -104,7 +101,7 @@ def warns( # noqa: F811
def warns( # noqa: F811
expected_warning: Optional[Union["Type[Warning]", Tuple["Type[Warning]", ...]]],
expected_warning: Optional[Union[Type[Warning], Tuple[Type[Warning], ...]]],
*args: Any,
match: Optional[Union[str, Pattern[str]]] = None,
**kwargs: Any
@ -187,7 +184,7 @@ class WarningsRecorder(warnings.catch_warnings):
"""The number of recorded warnings."""
return len(self._list)
def pop(self, cls: "Type[Warning]" = Warning) -> "warnings.WarningMessage":
def pop(self, cls: Type[Warning] = Warning) -> "warnings.WarningMessage":
"""Pop the first recorded warning, raise exception if not exists."""
for i, w in enumerate(self._list):
if issubclass(w.category, cls):
@ -214,7 +211,7 @@ class WarningsRecorder(warnings.catch_warnings):
def __exit__(
self,
exc_type: Optional["Type[BaseException]"],
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
@ -234,7 +231,7 @@ class WarningsChecker(WarningsRecorder):
def __init__(
self,
expected_warning: Optional[
Union["Type[Warning]", Tuple["Type[Warning]", ...]]
Union[Type[Warning], Tuple[Type[Warning], ...]]
] = None,
match_expr: Optional[Union[str, Pattern[str]]] = None,
) -> None:
@ -258,7 +255,7 @@ class WarningsChecker(WarningsRecorder):
def __exit__(
self,
exc_type: Optional["Type[BaseException]"],
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:

View File

@ -8,6 +8,7 @@ from typing import Iterator
from typing import List
from typing import Optional
from typing import Tuple
from typing import Type
from typing import TYPE_CHECKING
from typing import TypeVar
from typing import Union
@ -36,7 +37,6 @@ from _pytest.pathlib import Path
if TYPE_CHECKING:
from typing import NoReturn
from typing_extensions import Type
from typing_extensions import Literal
from _pytest.runner import CallInfo
@ -199,7 +199,7 @@ class BaseReport:
return _report_to_json(self)
@classmethod
def _from_json(cls: "Type[_R]", reportdict: Dict[str, object]) -> _R:
def _from_json(cls: Type[_R], reportdict: Dict[str, object]) -> _R:
"""Create either a TestReport or CollectReport, depending on the calling class.
It is the callers responsibility to know which class to pass here.
@ -213,7 +213,7 @@ class BaseReport:
def _report_unserialization_failure(
type_name: str, report_class: "Type[BaseReport]", reportdict
type_name: str, report_class: Type[BaseReport], reportdict
) -> "NoReturn":
url = "https://github.com/pytest-dev/pytest/issues"
stream = StringIO()

View File

@ -9,6 +9,7 @@ from typing import Generic
from typing import List
from typing import Optional
from typing import Tuple
from typing import Type
from typing import TYPE_CHECKING
from typing import TypeVar
from typing import Union
@ -33,7 +34,6 @@ from _pytest.outcomes import Skipped
from _pytest.outcomes import TEST_OUTCOME
if TYPE_CHECKING:
from typing import Type
from typing_extensions import Literal
from _pytest.main import Session
@ -301,7 +301,9 @@ class CallInfo(Generic[TResult]):
cls,
func: "Callable[[], TResult]",
when: "Literal['collect', 'setup', 'call', 'teardown']",
reraise: "Optional[Union[Type[BaseException], Tuple[Type[BaseException], ...]]]" = None,
reraise: Optional[
Union[Type[BaseException], Tuple[Type[BaseException], ...]]
] = None,
) -> "CallInfo[TResult]":
excinfo = None
start = timing.time()

View File

@ -6,7 +6,7 @@ import traceback
from typing import Generator
from typing import Optional
from typing import Tuple
from typing import TYPE_CHECKING
from typing import Type
import attr
@ -22,9 +22,6 @@ from _pytest.reports import BaseReport
from _pytest.runner import CallInfo
from _pytest.store import StoreKey
if TYPE_CHECKING:
from typing import Type
def pytest_addoption(parser: Parser) -> None:
group = parser.getgroup("general")
@ -194,7 +191,7 @@ class Xfail:
reason = attr.ib(type=str)
run = attr.ib(type=bool)
strict = attr.ib(type=bool)
raises = attr.ib(type=Optional[Tuple["Type[BaseException]", ...]])
raises = attr.ib(type=Optional[Tuple[Type[BaseException], ...]])
def evaluate_xfail_marks(item: Item) -> Optional[Xfail]:

View File

@ -9,6 +9,7 @@ from typing import Iterable
from typing import List
from typing import Optional
from typing import Tuple
from typing import Type
from typing import TYPE_CHECKING
from typing import Union
@ -33,7 +34,6 @@ from _pytest.skipping import unexpectedsuccess_key
if TYPE_CHECKING:
import unittest
from typing import Type
from _pytest.fixtures import _Scope

View File

@ -1,15 +1,12 @@
from typing import Any
from typing import Generic
from typing import TYPE_CHECKING
from typing import Type
from typing import TypeVar
import attr
from _pytest.compat import final
if TYPE_CHECKING:
from typing import Type # noqa: F401 (used in type string)
class PytestWarning(UserWarning):
"""Base class for all warnings emitted by pytest."""
@ -105,7 +102,7 @@ class UnformattedWarning(Generic[_W]):
as opposed to a direct message.
"""
category = attr.ib(type="Type[_W]")
category = attr.ib(type=Type["_W"])
template = attr.ib(type=str)
def format(self, **kwargs: Any) -> _W:

View File

@ -6,7 +6,7 @@ from typing import Dict
from typing import List
from typing import Sequence
from typing import Tuple
from typing import TYPE_CHECKING
from typing import Type
import attr
import py.path
@ -29,9 +29,6 @@ from _pytest.monkeypatch import MonkeyPatch
from _pytest.pathlib import Path
from _pytest.pytester import Testdir
if TYPE_CHECKING:
from typing import Type
class TestParseIni:
@pytest.mark.parametrize(
@ -1936,7 +1933,7 @@ def test_strtobool():
],
)
def test_parse_warning_filter(
arg: str, escape: bool, expected: "Tuple[str, str, Type[Warning], str, int]"
arg: str, escape: bool, expected: Tuple[str, str, Type[Warning], str, int]
) -> None:
assert parse_warning_filter(arg, escape=escape) == expected

View File

@ -4,7 +4,7 @@ import sys
import textwrap
from typing import Dict
from typing import Generator
from typing import TYPE_CHECKING
from typing import Type
import py
@ -12,9 +12,6 @@ import pytest
from _pytest.monkeypatch import MonkeyPatch
from _pytest.pytester import Testdir
if TYPE_CHECKING:
from typing import Type
@pytest.fixture
def mp() -> Generator[MonkeyPatch, None, None]:
@ -354,7 +351,7 @@ class SampleInherit(Sample):
@pytest.mark.parametrize(
"Sample", [Sample, SampleInherit], ids=["new", "new-inherit"],
)
def test_issue156_undo_staticmethod(Sample: "Type[Sample]") -> None:
def test_issue156_undo_staticmethod(Sample: Type[Sample]) -> None:
monkeypatch = MonkeyPatch()
monkeypatch.setattr(Sample, "hello", None)

View File

@ -5,7 +5,7 @@ import types
from typing import Dict
from typing import List
from typing import Tuple
from typing import TYPE_CHECKING
from typing import Type
import py
@ -17,9 +17,6 @@ from _pytest import runner
from _pytest.config import ExitCode
from _pytest.outcomes import OutcomeException
if TYPE_CHECKING:
from typing import Type
class TestSetupState:
def test_setup(self, testdir) -> None:
@ -457,7 +454,7 @@ reporttypes = [
@pytest.mark.parametrize(
"reporttype", reporttypes, ids=[x.__name__ for x in reporttypes]
)
def test_report_extra_parameters(reporttype: "Type[reports.BaseReport]") -> None:
def test_report_extra_parameters(reporttype: Type[reports.BaseReport]) -> None:
args = list(inspect.signature(reporttype.__init__).parameters.keys())[1:]
basekw = dict.fromkeys(args, []) # type: Dict[str, List[object]]
report = reporttype(newthing=1, **basekw)