From ca2a746bc99ed905fc00398364021e1e4a1c9955 Mon Sep 17 00:00:00 2001 From: Ivan Levkivskyi Date: Wed, 7 Aug 2019 15:00:10 +0100 Subject: [PATCH 1/5] Try fixing Travis build --- .travis.yml | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 847addde..7075a033 100644 --- a/.travis.yml +++ b/.travis.yml @@ -21,16 +21,17 @@ jobs: python: 3.6.2 - name: "3.6.1" python: 3.6.1 - - name: "3.6.0" - python: 3.6.0 + - name: "3.6" + python: 3.6 - name: "3.5.3" python: 3.5.3 - name: "3.5.2" python: 3.5.2 - name: "3.5.1" + dist: xenial python: 3.5.1 - - name: "3.5.0" - python: 3.5.0 + - name: "3.5" + python: 3.5 - name: "3.4" python: 3.4 - name: "2.7" From 096abda5a64a373ea4604bf88b287837eb4fa1e6 Mon Sep 17 00:00:00 2001 From: Ivan Levkivskyi Date: Wed, 7 Aug 2019 15:06:20 +0100 Subject: [PATCH 2/5] Another attempt --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 7075a033..928724e0 100644 --- a/.travis.yml +++ b/.travis.yml @@ -28,7 +28,7 @@ jobs: - name: "3.5.2" python: 3.5.2 - name: "3.5.1" - dist: xenial + dist: trusty python: 3.5.1 - name: "3.5" python: 3.5 From 5074699b9309370c258ab3859afa18c0e0a0c666 Mon Sep 17 00:00:00 2001 From: Ivan Levkivskyi Date: Wed, 7 Aug 2019 17:17:01 +0100 Subject: [PATCH 3/5] Fix lint (that was not run for looong time) --- .flake8-tests | 4 +- python2/test_typing.py | 11 +- python2/typing.py | 3 +- src/mod_generics_cache.py | 4 - src/test_typing.py | 26 ++-- tox.ini | 4 +- .../src_py2/test_typing_extensions.py | 15 +-- .../src_py2/typing_extensions.py | 4 +- .../src_py3/test_typing_extensions.py | 27 ++-- .../src_py3/typing_extensions.py | 119 ++++++++++-------- 10 files changed, 113 insertions(+), 104 deletions(-) diff --git a/.flake8-tests b/.flake8-tests index fedc1cbb..06b437db 100644 --- a/.flake8-tests +++ b/.flake8-tests @@ -8,7 +8,7 @@ [flake8] # fake builtins for python2/* builtins = basestring, unicode -max-line-length = 90 +max-line-length = 100 ignore = # temporary ignores until we sort it out E306, @@ -18,6 +18,8 @@ ignore = # irrelevant plugins B3, DW12 + # consistency with mypy + W504 exclude = # This config is NOT for the main module. setup.py diff --git a/python2/test_typing.py b/python2/test_typing.py index fc4a80e6..0d8096fa 100644 --- a/python2/test_typing.py +++ b/python2/test_typing.py @@ -1827,7 +1827,6 @@ def __new__(cls, arg): self.assertEqual(c.from_c, 'c') - class ClassVarTests(BaseTestCase): def test_basics(self): @@ -2308,8 +2307,8 @@ def __len__(self): self.assertIsSubclass(MMB[str, str], typing.Mapping) self.assertIsSubclass(MMC, MMA) - class I(typing.Iterable): pass - self.assertNotIsSubclass(list, I) + class It(typing.Iterable): pass + self.assertNotIsSubclass(list, It) class G(typing.Generator[int, int, int]): pass def g(): yield 0 @@ -2366,8 +2365,8 @@ class S(collections.MutableSequence): pass self.assertIsSubclass(S, typing.MutableSequence) self.assertIsSubclass(S, typing.Iterable) - class I(collections.Iterable): pass - self.assertIsSubclass(I, typing.Iterable) + class It(collections.Iterable): pass + self.assertIsSubclass(It, typing.Iterable) class A(collections.Mapping): pass class B: pass @@ -2659,7 +2658,7 @@ def test_respect_no_type_check(self): class NoTpCheck(object): class Inn(object): def __init__(self, x): - # type: (this is not actually a type) -> None + # type: (this is not actually a type) -> None # noqa pass self.assertTrue(NoTpCheck.__no_type_check__) self.assertTrue(NoTpCheck.Inn.__init__.__no_type_check__) diff --git a/python2/typing.py b/python2/typing.py index 85d2168d..38720d22 100644 --- a/python2/typing.py +++ b/python2/typing.py @@ -1780,7 +1780,8 @@ def __init__(cls, *args, **kwargs): if cls._is_protocol: for base in cls.__mro__[1:]: if not (base in (object, Generic) or - base.__module__ == '_abcoll' and base.__name__ in _PROTO_WHITELIST or + base.__module__ == '_abcoll' and + base.__name__ in _PROTO_WHITELIST or isinstance(base, TypingMeta) and base._is_protocol or isinstance(base, GenericMeta) and base.__origin__ is Generic): raise TypeError('Protocols can only inherit from other protocols,' diff --git a/src/mod_generics_cache.py b/src/mod_generics_cache.py index 6d35c583..51cef0f0 100644 --- a/src/mod_generics_cache.py +++ b/src/mod_generics_cache.py @@ -12,11 +12,9 @@ T = TypeVar('T') - class A(Generic[T]): some_b: 'B' - class B(Generic[T]): class A(Generic[T]): pass @@ -35,13 +33,11 @@ class A(Generic[T]): T = TypeVar('T') - class A(Generic[T]): __annotations__ = dict( some_b='B' ) - class B(Generic[T]): class A(Generic[T]): pass diff --git a/src/test_typing.py b/src/test_typing.py index 8be4bdc9..6c9f3669 100644 --- a/src/test_typing.py +++ b/src/test_typing.py @@ -12,7 +12,7 @@ from typing import TypeVar, AnyStr from typing import T, KT, VT # Not in __all__. from typing import Union, Optional -from typing import Tuple, List, MutableMapping +from typing import Tuple, List, MutableMapping, Iterator from typing import Callable from typing import Generic, ClassVar, GenericMeta from typing import cast @@ -1539,7 +1539,7 @@ def test_syntax_error(self): def test_delayed_syntax_error(self): - def foo(a: 'Node[T'): + def foo(a: 'Node[T'): # noqa pass with self.assertRaises(SyntaxError): @@ -1555,7 +1555,7 @@ def foo(a: Tuple['42']): def test_name_error(self): - def foo(a: 'Noode[T]'): + def foo(a: 'Noode[T]'): # noqa pass with self.assertRaises(NameError): @@ -1564,7 +1564,7 @@ def foo(a: 'Noode[T]'): def test_no_type_check(self): @no_type_check - def foo(a: 'whatevers') -> {}: + def foo(a: 'int') -> {}: pass th = get_type_hints(foo) @@ -1574,7 +1574,7 @@ def test_no_type_check_class(self): @no_type_check class C: - def foo(a: 'whatevers') -> {}: + def foo(a: 'int') -> {}: pass cth = get_type_hints(C.foo) @@ -1600,12 +1600,12 @@ def magic_decorator(deco): self.assertEqual(magic_decorator.__name__, 'magic_decorator') @magic_decorator - def foo(a: 'whatevers') -> {}: + def foo(a: 'int') -> {}: pass @magic_decorator class C: - def foo(a: 'whatevers') -> {}: + def foo(a: 'int') -> {}: pass self.assertEqual(foo.__name__, 'foo') @@ -1764,7 +1764,7 @@ async def g_with(am: AsyncContextManager[int]): # fake names for the sake of static analysis ann_module = ann_module2 = ann_module3 = None A = B = CSub = G = CoolEmployee = CoolEmployeeWithDefault = object - XMeth = XRepr = NoneAndForward = object + XMeth = XRepr = NoneAndForward = HasForeignBaseClass = object gth = get_type_hints @@ -1826,7 +1826,7 @@ def test_respect_no_type_check(self): @no_type_check class NoTpCheck: class Inn: - def __init__(self, x: 'not a type'): ... + def __init__(self, x: 'not a type'): ... # noqa self.assertTrue(NoTpCheck.__no_type_check__) self.assertTrue(NoTpCheck.Inn.__init__.__no_type_check__) self.assertEqual(gth(ann_module2.NTC.meth), {}) @@ -2233,8 +2233,8 @@ def __len__(self): self.assertIsSubclass(MMB[str, str], typing.Mapping) self.assertIsSubclass(MMC, MMA) - class I(typing.Iterable): ... - self.assertNotIsSubclass(list, I) + class It(typing.Iterable): ... + self.assertNotIsSubclass(list, It) class G(typing.Generator[int, int, int]): ... def g(): yield 0 @@ -2316,8 +2316,8 @@ class S(collections_abc.MutableSequence): ... self.assertIsSubclass(S, typing.MutableSequence) self.assertIsSubclass(S, typing.Iterable) - class I(collections_abc.Iterable): ... - self.assertIsSubclass(I, typing.Iterable) + class It(collections_abc.Iterable): ... + self.assertIsSubclass(It, typing.Iterable) class A(collections_abc.Mapping, metaclass=abc.ABCMeta): ... class B: ... diff --git a/tox.ini b/tox.ini index 5f92822c..1017cd40 100644 --- a/tox.ini +++ b/tox.ini @@ -17,7 +17,9 @@ ignore = B3, DW12, # code is sometimes better without this - E129 + E129, + # consistency with mypy + W504 exclude = # tests have more relaxed formatting rules # and its own specific config in .flake8-tests diff --git a/typing_extensions/src_py2/test_typing_extensions.py b/typing_extensions/src_py2/test_typing_extensions.py index 2967dbac..7825e407 100644 --- a/typing_extensions/src_py2/test_typing_extensions.py +++ b/typing_extensions/src_py2/test_typing_extensions.py @@ -5,7 +5,7 @@ import subprocess from unittest import TestCase, main -from typing_extensions import Annotated, NoReturn, ClassVar, Final, IntVar, Literal, TypedDict +from typing_extensions import Annotated, NoReturn, ClassVar, IntVar from typing_extensions import ContextManager, Counter, Deque, DefaultDict from typing_extensions import NewType, overload from typing import Dict, List @@ -118,7 +118,7 @@ def test_no_isinstance(self): class IntVarTests(BaseTestCase): def test_valid(self): - T_ints = IntVar("T_ints") + T_ints = IntVar("T_ints") # noqa def test_invalid(self): with self.assertRaises(TypeError): @@ -126,7 +126,7 @@ def test_invalid(self): with self.assertRaises(TypeError): T_ints = IntVar("T_ints", bound=int) with self.assertRaises(TypeError): - T_ints = IntVar("T_ints", covariant=True) + T_ints = IntVar("T_ints", covariant=True) # noqa class CollectionsAbcTests(BaseTestCase): @@ -332,8 +332,8 @@ def test_hash_eq(self): def test_cannot_subclass(self): with self.assertRaises(TypeError): - class C(Annotated): - pass + class C(Annotated): + pass def test_cannot_check_instance(self): with self.assertRaises(TypeError): @@ -364,9 +364,9 @@ def test_subst(self): with self.assertRaises(TypeError): D[int] - I = Annotated[int, dec] + It = Annotated[int, dec] with self.assertRaises(TypeError): - I[None] + It[None] LI = L[int] with self.assertRaises(TypeError): @@ -376,6 +376,7 @@ def test_annotated_in_other_types(self): X = List[Annotated[T, 5]] self.assertEqual(X[int], List[Annotated[int, 5]]) + class AllTests(BaseTestCase): def test_typing_extensions_includes_standard(self): diff --git a/typing_extensions/src_py2/typing_extensions.py b/typing_extensions/src_py2/typing_extensions.py index e5f53852..64c5bedb 100644 --- a/typing_extensions/src_py2/typing_extensions.py +++ b/typing_extensions/src_py2/typing_extensions.py @@ -1,7 +1,7 @@ import abc -import sys import typing -from typing import ( +from typing import ( # noqa + # These are imported for re-export. ClassVar, Type, Generic, Callable, GenericMeta, TypingMeta, Counter, DefaultDict, Deque, TypeVar, Tuple, Final, final, NewType, overload, Text, TYPE_CHECKING, Literal, TypedDict, Protocol, diff --git a/typing_extensions/src_py3/test_typing_extensions.py b/typing_extensions/src_py3/test_typing_extensions.py index 87dddd84..d051b461 100644 --- a/typing_extensions/src_py3/test_typing_extensions.py +++ b/typing_extensions/src_py3/test_typing_extensions.py @@ -9,7 +9,7 @@ from unittest import TestCase, main, skipUnless from typing import TypeVar, Optional from typing import T, KT, VT # Not in __all__. -from typing import Tuple, List, Dict +from typing import Tuple, List, Dict, Iterator from typing import Generic from typing import no_type_check from typing_extensions import NoReturn, ClassVar, Final, IntVar, Literal, Type, NewType, TypedDict @@ -34,13 +34,13 @@ OLD_GENERICS = False try: - from typing import _type_vars, _next_in_mro, _type_check + from typing import _type_vars, _next_in_mro, _type_check # noqa except ImportError: OLD_GENERICS = True # We assume Python versions *below* 3.5.0 will have the most # up-to-date version of the typing module installed. Since -# the typing module isn't a part of the standard library in older +# the typing module isn't a part of the standard library in older # versions of Python, those users are likely to have a reasonably # modern version of `typing` installed from PyPi. TYPING_LATEST = sys.version_info[:3] < (3, 5, 0) @@ -73,6 +73,7 @@ # Protocols are hard to backport to the original version of typing 3.5.0 HAVE_PROTOCOLS = sys.version_info[:3] != (3, 5, 0) + class BaseTestCase(TestCase): def assertIsSubclass(self, cls, class_or_tuple, msg=None): if not issubclass(cls, class_or_tuple): @@ -226,7 +227,7 @@ def test_no_isinstance(self): class IntVarTests(BaseTestCase): def test_valid(self): - T_ints = IntVar("T_ints") + T_ints = IntVar("T_ints") # noqa def test_invalid(self): with self.assertRaises(TypeError): @@ -234,7 +235,7 @@ def test_invalid(self): with self.assertRaises(TypeError): T_ints = IntVar("T_ints", bound=int) with self.assertRaises(TypeError): - T_ints = IntVar("T_ints", covariant=True) + T_ints = IntVar("T_ints", covariant=True) # noqa class LiteralTests(BaseTestCase): @@ -475,7 +476,7 @@ def test_respect_no_type_check(self): @no_type_check class NoTpCheck: class Inn: - def __init__(self, x: 'not a type'): ... + def __init__(self, x: 'not a type'): ... # noqa self.assertTrue(NoTpCheck.__no_type_check__) self.assertTrue(NoTpCheck.Inn.__init__.__no_type_check__) self.assertEqual(gth(ann_module2.NTC.meth), {}) @@ -502,6 +503,7 @@ def test_final_forward_ref(self): self.assertNotEqual(gth(Loop, globals())['attr'], Final[int]) self.assertNotEqual(gth(Loop, globals())['attr'], Final) + class CollectionsAbcTests(BaseTestCase): def test_isinstance_collections(self): @@ -1609,8 +1611,8 @@ def test_hash_eq(self): def test_cannot_subclass(self): with self.assertRaisesRegex(TypeError, "Cannot subclass .*Annotated"): - class C(Annotated): - pass + class C(Annotated): + pass def test_cannot_check_instance(self): with self.assertRaises(TypeError): @@ -1620,7 +1622,6 @@ def test_cannot_check_subclass(self): with self.assertRaises(TypeError): issubclass(int, Annotated[int, "positive"]) - @skipUnless(PEP_560, "pickle support was added with PEP 560") def test_pickle(self): samples = [typing.Any, typing.Union[int, str], @@ -1673,9 +1674,9 @@ def test_subst(self): with self.assertRaises(TypeError): D[int] - I = Annotated[int, dec] + It = Annotated[int, dec] with self.assertRaises(TypeError): - I[None] + It[None] LI = L[int] with self.assertRaises(TypeError): @@ -1747,7 +1748,6 @@ def __iand__(self, other: Const["MySet[T]"]) -> "MySet[T]": ) - class AllTests(BaseTestCase): def test_typing_extensions_includes_standard(self): @@ -1782,7 +1782,6 @@ def test_typing_extensions_includes_standard(self): self.assertIn('Protocol', a) self.assertIn('runtime', a) - def test_typing_extensions_defers_when_possible(self): exclude = {'overload', 'Text', 'TYPE_CHECKING', 'Final', 'get_type_hints'} for item in typing_extensions.__all__: @@ -1804,4 +1803,4 @@ def test_typing_extensions_compiles_with_opt(self): if __name__ == '__main__': - main() + main() diff --git a/typing_extensions/src_py3/typing_extensions.py b/typing_extensions/src_py3/typing_extensions.py index f37ee642..207e2665 100644 --- a/typing_extensions/src_py3/typing_extensions.py +++ b/typing_extensions/src_py3/typing_extensions.py @@ -6,15 +6,16 @@ import collections.abc as collections_abc import operator +# These are used by Protocol implementation +# We use internal typing helpers here, but this significantly reduces +# code duplication. (Also this is only until Protocol is in typing.) +from typing import Generic, Callable, TypeVar, Tuple + # After PEP 560, internal typing API was substantially reworked. # This is especially important for Protocol class which uses internal APIs # quite extensivelly. PEP_560 = sys.version_info[:3] >= (3, 7, 0) -# These are used by Protocol implementation -# We use internal typing helpers here, but this significantly reduces -# code duplication. (Also this is only until Protocol is in typing.) -from typing import Generic, Callable, TypeVar, Tuple if PEP_560: GenericMeta = TypingMeta = type else: @@ -25,19 +26,23 @@ except ImportError: OLD_GENERICS = True try: - from typing import _subs_tree + from typing import _subs_tree # noqa SUBS_TREE = True except ImportError: SUBS_TREE = False try: from typing import _tp_cache except ImportError: - _tp_cache = lambda x: x + def _tp_cache(x): + return x try: from typing import _TypingEllipsis, _TypingEmpty except ImportError: - class _TypingEllipsis: pass - class _TypingEmpty: pass + class _TypingEllipsis: + pass + + class _TypingEmpty: + pass # The two functions below are copies of typing internal helpers. @@ -363,21 +368,20 @@ def __getitem__(self, parameters): '{} accepts only single type'.format(self._name)) return _GenericAlias(self, (item,)) - Final = _FinalForm('Final', doc= - """A special typing construct to indicate that a name - cannot be re-assigned or overridden in a subclass. - For example: + Final = _FinalForm('Final', + doc="""A special typing construct to indicate that a name + cannot be re-assigned or overridden in a subclass. + For example: - MAX_SIZE: Final = 9000 - MAX_SIZE += 1 # Error reported by type checker + MAX_SIZE: Final = 9000 + MAX_SIZE += 1 # Error reported by type checker - class Connection: - TIMEOUT: Final[int] = 10 - class FastConnector(Connection): - TIMEOUT = 1 # Error reported by type checker + class Connection: + TIMEOUT: Final[int] = 10 + class FastConnector(Connection): + TIMEOUT = 1 # Error reported by type checker - There is no runtime checking of these properties. - """) + There is no runtime checking of these properties.""") elif hasattr(typing, '_FinalTypingBase'): class _Final(typing._FinalTypingBase, _root=True): """A special typing construct to indicate that a name @@ -534,7 +538,7 @@ def IntVar(name): if hasattr(typing, 'Literal'): - Literal = typing.Literal + Literal = typing.Literal elif sys.version_info[:2] >= (3, 7): class _LiteralForm(typing._SpecialForm, _root=True): @@ -544,19 +548,19 @@ def __repr__(self): def __getitem__(self, parameters): return _GenericAlias(self, parameters) - Literal = _LiteralForm('Literal', doc= - """A type that can be used to indicate to type checkers that the - corresponding value has a value literally equivalent to the - provided parameter. For example: + Literal = _LiteralForm('Literal', + doc="""A type that can be used to indicate to type checkers + that the corresponding value has a value literally equivalent + to the provided parameter. For example: - var: Literal[4] = 4 - - The type checker understands that 'var' is literally equal to the - value 4 and no other value. + var: Literal[4] = 4 - Literal[...] cannot be subclassed. There is no runtime checking - verifying that the parameter is actually a value instead of a type. - """) + The type checker understands that 'var' is literally equal to + the value 4 and no other value. + + Literal[...] cannot be subclassed. There is no runtime + checking verifying that the parameter is actually a value + instead of a type.""") elif hasattr(typing, '_FinalTypingBase'): class _Literal(typing._FinalTypingBase, _root=True): """A type that can be used to indicate to type checkers that the @@ -564,7 +568,7 @@ class _Literal(typing._FinalTypingBase, _root=True): provided parameter. For example: var: Literal[4] = 4 - + The type checker understands that 'var' is literally equal to the value 4 and no other value. @@ -658,7 +662,7 @@ class Literal(typing.Final, metaclass=_LiteralMeta, _root=True): provided parameter. For example: var: Literal[4] = 4 - + The type checker understands that 'var' is literally equal to the value 4 and no other value. @@ -1071,7 +1075,7 @@ def _gorg(cls): if OLD_GENERICS: - def _next_in_mro(cls): + def _next_in_mro(cls): # noqa """This function exists for compatibility with old typing versions.""" next_in_mro = object for i, c in enumerate(cls.__mro__[:-1]): @@ -1220,8 +1224,10 @@ def _proto_hook(other): return NotImplemented break annotations = getattr(base, '__annotations__', {}) - if (isinstance(annotations, typing.Mapping) and attr in annotations and - isinstance(other, _ProtocolMeta) and other._is_protocol): + if (isinstance(annotations, typing.Mapping) and + attr in annotations and + isinstance(other, _ProtocolMeta) and + other._is_protocol): break else: return NotImplemented @@ -1252,13 +1258,17 @@ def __subclasscheck__(self, cls): return False if (self.__dict__.get('_is_protocol', None) and not self.__dict__.get('_is_runtime_protocol', None)): - if sys._getframe(1).f_globals['__name__'] in ['abc', 'functools', 'typing']: + if sys._getframe(1).f_globals['__name__'] in ['abc', + 'functools', + 'typing']: return False raise TypeError("Instance and class checks can only be used with" " @runtime protocols") if (self.__dict__.get('_is_runtime_protocol', None) and not _is_callable_members_only(self)): - if sys._getframe(1).f_globals['__name__'] in ['abc', 'functools', 'typing']: + if sys._getframe(1).f_globals['__name__'] in ['abc', + 'functools', + 'typing']: return super(GenericMeta, self).__subclasscheck__(cls) raise TypeError("Protocols with non-method members" " don't support issubclass()") @@ -1351,7 +1361,7 @@ def __new__(cls, *args, **kwds): elif PEP_560: - from typing import _type_check, _GenericAlias, _collect_type_vars + from typing import _type_check, _GenericAlias, _collect_type_vars # noqa class _ProtocolMeta(abc.ABCMeta): # This metaclass is a bit unfortunate and exists only because of the lack @@ -1371,11 +1381,10 @@ def __instancecheck__(cls, instance): return True return super().__instancecheck__(instance) - class Protocol(metaclass=_ProtocolMeta): # There is quite a lot of overlapping code with typing.Generic. - # Unfortunately it is hard to avoid this while these live in two different modules. - # The duplicated code will be removed when Protocol is moved to typing. + # Unfortunately it is hard to avoid this while these live in two different + # modules. The duplicated code will be removed when Protocol is moved to typing. """Base class for protocol classes. Protocol classes are defined as:: class Proto(Protocol): @@ -1474,7 +1483,8 @@ def __init_subclass__(cls, *args, **kwargs): s_vars = ', '.join(str(t) for t in tvars if t not in gvarset) s_args = ', '.join(str(g) for g in gvars) raise TypeError("Some type variables ({}) are" - " not listed in {}[{}]".format(s_vars, the_base, s_args)) + " not listed in {}[{}]".format(s_vars, + the_base, s_args)) tvars = gvars cls.__parameters__ = tuple(tvars) @@ -1506,8 +1516,10 @@ def _proto_hook(other): return NotImplemented break annotations = getattr(base, '__annotations__', {}) - if (isinstance(annotations, typing.Mapping) and attr in annotations and - isinstance(other, _ProtocolMeta) and other._is_protocol): + if (isinstance(annotations, typing.Mapping) and + attr in annotations and + isinstance(other, _ProtocolMeta) and + other._is_protocol): break else: return NotImplemented @@ -1562,18 +1574,18 @@ def runtime_checkable(cls): else: def _check_fails(cls, other): try: - if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools', 'typing']: + if sys._getframe(1).f_globals['__name__'] not in ['abc', + 'functools', + 'typing']: # Typed dicts are only for static structural subtyping. raise TypeError('TypedDict does not support instance and class checks') except (AttributeError, ValueError): pass return False - def _dict_new(cls, *args, **kwargs): return dict(*args, **kwargs) - def _typeddict_new(cls, _typename, _fields=None, **kwargs): total = kwargs.pop('total', True) if _fields is None: @@ -1591,7 +1603,6 @@ def _typeddict_new(cls, _typename, _fields=None, **kwargs): return _TypedDictMeta(_typename, (), ns) - class _TypedDictMeta(type): def __new__(cls, name, bases, ns, total=True): # Create new typed dict class object. @@ -1615,7 +1626,6 @@ def __new__(cls, name, bases, ns, total=True): __instancecheck__ = __subclasscheck__ = _check_fails - TypedDict = _TypedDictMeta('TypedDict', (dict,), {}) TypedDict.__module__ = __name__ TypedDict.__doc__ = \ @@ -1707,7 +1717,7 @@ class Annotated: - It's an error to call `Annotated` with less than two arguments. - Nested Annotated are flattened:: - Annotated[Annotated[int, Ann1, Ann2], Ann3] == Annotated[int, Ann1, Ann2, Ann3] + Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3] - Instantiating an annotated type is equivalent to instantiating the underlying type:: @@ -1825,7 +1835,7 @@ def _tree_repr(self, tree): metadata_reprs = ", ".join(repr(arg) for arg in metadata) return '%s[%s, %s]' % (cls, tp_repr, metadata_reprs) - def _subs_tree(self, tvars=None, args=None): + def _subs_tree(self, tvars=None, args=None): # noqa if self is Annotated: return Annotated res = super()._subs_tree(tvars=tvars, args=args) @@ -1902,7 +1912,6 @@ def __instancecheck__(self, obj): def __subclasscheck__(self, cls): raise TypeError("Annotated cannot be used with issubclass().") - class Annotated(metaclass=AnnotatedMeta): """Add context specific metadata to a type. @@ -1919,7 +1928,7 @@ class Annotated(metaclass=AnnotatedMeta): - It's an error to call `Annotated` with less than two arguments. - Nested Annotated are flattened:: - Annotated[Annotated[int, Ann1, Ann2], Ann3] == Annotated[int, Ann1, Ann2, Ann3] + Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3] - Instantiating an annotated type is equivalent to instantiating the underlying type:: From 577975a3b4b66d7925115657fbdacc1b4479e17c Mon Sep 17 00:00:00 2001 From: Ivan Levkivskyi Date: Wed, 7 Aug 2019 18:23:30 +0100 Subject: [PATCH 4/5] One more attempt at fixing --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 928724e0..52c0fa9c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -43,7 +43,7 @@ install: script: - export PYTHONPATH=`python -c "import sys; print('python2' if sys.version.startswith('2') else 'src')"`; if [[ $TRAVIS_PYTHON_VERSION < '3.7' ]]; then py.test $PYTHONPATH; fi - - if [[ $TRAVIS_PYTHON_VERSION < '3.5' ]]; then python setup.py install; fi + - if [[ $TRAVIS_PYTHON_VERSION < '3.5' ]]; then pip install -U .; fi - export PYTHONPATH=`python -c "import sys; print('typing_extensions/src_py2' if sys.version.startswith('2') else 'typing_extensions/src_py3')"`; py.test $PYTHONPATH; - if [[ $TRAVIS_PYTHON_VERSION == '3.6' ]]; then flake8; fi From 1427eb7d03d2d10cd566cf96137b991da6045701 Mon Sep 17 00:00:00 2001 From: Ivan Levkivskyi Date: Sat, 10 Aug 2019 19:58:10 +0100 Subject: [PATCH 5/5] Address CR --- src/test_typing.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/test_typing.py b/src/test_typing.py index 6c9f3669..9350249d 100644 --- a/src/test_typing.py +++ b/src/test_typing.py @@ -1564,7 +1564,7 @@ def foo(a: 'Noode[T]'): # noqa def test_no_type_check(self): @no_type_check - def foo(a: 'int') -> {}: + def foo(a: 'whatevers') -> {}: # noqa pass th = get_type_hints(foo) @@ -1574,7 +1574,7 @@ def test_no_type_check_class(self): @no_type_check class C: - def foo(a: 'int') -> {}: + def foo(a: 'whatevers') -> {}: # noqa pass cth = get_type_hints(C.foo) @@ -1600,12 +1600,12 @@ def magic_decorator(deco): self.assertEqual(magic_decorator.__name__, 'magic_decorator') @magic_decorator - def foo(a: 'int') -> {}: + def foo(a: 'whatevers') -> {}: # noqa pass @magic_decorator class C: - def foo(a: 'int') -> {}: + def foo(a: 'whatevers') -> {}: # noqa pass self.assertEqual(foo.__name__, 'foo')