Skip to content

Commit bd5b9a0

Browse files
committed
Many changes from the upstream repo (https://github.com/python/typing).
This syncs to rev 7b43ada77821d23e55e3a4b35f6055a59b9e1ad7 there. Summary: - Add typing.DefaultDict (as a generic variant of collections.defaultdict). - Use collections.Reversible if it exists (only relevant for Python 3.6). - Revamped generic class behavior to conform to updated PEP 484. - Improve speed of Generic.__new__. - Make sure __init__ is called for new Generic instances. Fix issue #26391. - Refactor async support to be compatible with 3.2, 3.3, 3.4. - Remove 'io' and 're' from __all__ (they still exist, just not included by "import *"). Fix issue #26234. - Change @overload -- you can now use it outside stubs (you still cannot call the decorated function though).
1 parent 0f76739 commit bd5b9a0

File tree

2 files changed

+371
-179
lines changed

2 files changed

+371
-179
lines changed

Lib/test/test_typing.py

Lines changed: 129 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
1-
import asyncio
21
import pickle
32
import re
43
import sys
5-
from unittest import TestCase, main
4+
from unittest import TestCase, main, skipUnless
65

76
from typing import Any
87
from typing import TypeVar, AnyStr
@@ -133,6 +132,7 @@ def test_basic_constrained(self):
133132
def test_constrained_error(self):
134133
with self.assertRaises(TypeError):
135134
X = TypeVar('X', int)
135+
X
136136

137137
def test_union_unique(self):
138138
X = TypeVar('X')
@@ -317,6 +317,7 @@ def test_union_instance_type_error(self):
317317
def test_union_str_pattern(self):
318318
# Shouldn't crash; see http://bugs.python.org/issue25390
319319
A = Union[str, Pattern]
320+
A
320321

321322

322323
class TypeVarUnionTests(TestCase):
@@ -487,7 +488,7 @@ def get(self, key: XK, default: XV = None) -> XV:
487488
...
488489

489490

490-
class MySimpleMapping(SimpleMapping):
491+
class MySimpleMapping(SimpleMapping[XK, XV]):
491492

492493
def __init__(self):
493494
self.store = {}
@@ -541,6 +542,7 @@ def test_supports_abs(self):
541542
assert not issubclass(str, typing.SupportsAbs)
542543

543544
def test_supports_round(self):
545+
issubclass(float, typing.SupportsRound)
544546
assert issubclass(float, typing.SupportsRound)
545547
assert issubclass(int, typing.SupportsRound)
546548
assert not issubclass(str, typing.SupportsRound)
@@ -551,20 +553,23 @@ def test_reversible(self):
551553

552554
def test_protocol_instance_type_error(self):
553555
with self.assertRaises(TypeError):
554-
isinstance([], typing.Reversible)
556+
isinstance(0, typing.SupportsAbs)
555557

556558

557559
class GenericTests(TestCase):
558560

559561
def test_basics(self):
560562
X = SimpleMapping[str, Any]
561-
Y = SimpleMapping[XK, str]
562-
X[str, str]
563-
Y[str, str]
563+
assert X.__parameters__ == ()
564564
with self.assertRaises(TypeError):
565-
X[int, str]
565+
X[str]
566+
with self.assertRaises(TypeError):
567+
X[str, str]
568+
Y = SimpleMapping[XK, str]
569+
assert Y.__parameters__ == (XK,)
570+
Y[str]
566571
with self.assertRaises(TypeError):
567-
Y[str, bytes]
572+
Y[str, str]
568573

569574
def test_init(self):
570575
T = TypeVar('T')
@@ -576,30 +581,61 @@ def test_init(self):
576581

577582
def test_repr(self):
578583
self.assertEqual(repr(SimpleMapping),
579-
__name__ + '.' + 'SimpleMapping[~XK, ~XV]')
584+
__name__ + '.' + 'SimpleMapping<~XK, ~XV>')
580585
self.assertEqual(repr(MySimpleMapping),
581-
__name__ + '.' + 'MySimpleMapping[~XK, ~XV]')
586+
__name__ + '.' + 'MySimpleMapping<~XK, ~XV>')
587+
588+
def test_chain_repr(self):
589+
T = TypeVar('T')
590+
S = TypeVar('S')
591+
592+
class C(Generic[T]):
593+
pass
594+
595+
X = C[Tuple[S, T]]
596+
assert X == C[Tuple[S, T]]
597+
assert X != C[Tuple[T, S]]
598+
599+
Y = X[T, int]
600+
assert Y == X[T, int]
601+
assert Y != X[S, int]
602+
assert Y != X[T, str]
603+
604+
Z = Y[str]
605+
assert Z == Y[str]
606+
assert Z != Y[int]
607+
assert Z != Y[T]
608+
609+
assert str(Z).endswith(
610+
'.C<~T>[typing.Tuple[~S, ~T]]<~S, ~T>[~T, int]<~T>[str]')
582611

583612
def test_dict(self):
584613
T = TypeVar('T')
614+
585615
class B(Generic[T]):
586616
pass
617+
587618
b = B()
588619
b.foo = 42
589620
self.assertEqual(b.__dict__, {'foo': 42})
621+
590622
class C(B[int]):
591623
pass
624+
592625
c = C()
593626
c.bar = 'abc'
594627
self.assertEqual(c.__dict__, {'bar': 'abc'})
595628

596629
def test_pickle(self):
630+
global C # pickle wants to reference the class by name
597631
T = TypeVar('T')
632+
598633
class B(Generic[T]):
599634
pass
600-
global C # pickle wants to reference the class by name
635+
601636
class C(B[int]):
602637
pass
638+
603639
c = C()
604640
c.foo = 42
605641
c.bar = 'abc'
@@ -626,20 +662,20 @@ class C(Generic[T]):
626662
assert C.__module__ == __name__
627663
if not PY32:
628664
assert C.__qualname__ == 'GenericTests.test_repr_2.<locals>.C'
629-
assert repr(C).split('.')[-1] == 'C[~T]'
665+
assert repr(C).split('.')[-1] == 'C<~T>'
630666
X = C[int]
631667
assert X.__module__ == __name__
632668
if not PY32:
633669
assert X.__qualname__ == 'C'
634-
assert repr(X).split('.')[-1] == 'C[int]'
670+
assert repr(X).split('.')[-1] == 'C<~T>[int]'
635671

636672
class Y(C[int]):
637673
pass
638674

639675
assert Y.__module__ == __name__
640676
if not PY32:
641677
assert Y.__qualname__ == 'GenericTests.test_repr_2.<locals>.Y'
642-
assert repr(Y).split('.')[-1] == 'Y[int]'
678+
assert repr(Y).split('.')[-1] == 'Y'
643679

644680
def test_eq_1(self):
645681
assert Generic == Generic
@@ -667,15 +703,14 @@ class A(Generic[T, VT]):
667703
class B(Generic[KT, T]):
668704
pass
669705

670-
class C(A, Generic[KT, VT], B):
706+
class C(A[T, VT], Generic[VT, T, KT], B[KT, T]):
671707
pass
672708

673-
assert C.__parameters__ == (T, VT, KT)
709+
assert C.__parameters__ == (VT, T, KT)
674710

675711
def test_nested(self):
676712

677-
class G(Generic):
678-
pass
713+
G = Generic
679714

680715
class Visitor(G[T]):
681716

@@ -721,9 +756,30 @@ def foo(x: T):
721756
assert type(a) is Node
722757
assert type(b) is Node
723758
assert type(c) is Node
759+
assert a.label == x
760+
assert b.label == x
761+
assert c.label == x
724762

725763
foo(42)
726764

765+
def test_implicit_any(self):
766+
T = TypeVar('T')
767+
768+
class C(Generic[T]):
769+
pass
770+
771+
class D(C):
772+
pass
773+
774+
assert D.__parameters__ == ()
775+
776+
with self.assertRaises(Exception):
777+
D[int]
778+
with self.assertRaises(Exception):
779+
D[Any]
780+
with self.assertRaises(Exception):
781+
D[T]
782+
727783

728784
class VarianceTests(TestCase):
729785

@@ -956,13 +1012,32 @@ def test_overload_fails(self):
9561012
from typing import overload
9571013

9581014
with self.assertRaises(RuntimeError):
1015+
9591016
@overload
9601017
def blah():
9611018
pass
9621019

1020+
blah()
9631021

964-
T_a = TypeVar('T')
1022+
def test_overload_succeeds(self):
1023+
from typing import overload
1024+
1025+
@overload
1026+
def blah():
1027+
pass
1028+
1029+
def blah():
1030+
pass
1031+
1032+
blah()
1033+
1034+
1035+
PY35 = sys.version_info[:2] >= (3, 5)
9651036

1037+
PY35_TESTS = """
1038+
import asyncio
1039+
1040+
T_a = TypeVar('T')
9661041
9671042
class AwaitableWrapper(typing.Awaitable[T_a]):
9681043
@@ -973,7 +1048,6 @@ def __await__(self) -> typing.Iterator[T_a]:
9731048
yield
9741049
return self.value
9751050
976-
9771051
class AsyncIteratorWrapper(typing.AsyncIterator[T_a]):
9781052
9791053
def __init__(self, value: typing.Iterable[T_a]):
@@ -989,6 +1063,10 @@ def __anext__(self) -> T_a:
9891063
return data
9901064
else:
9911065
raise StopAsyncIteration
1066+
"""
1067+
1068+
if PY35:
1069+
exec(PY35_TESTS)
9921070

9931071

9941072
class CollectionsAbcTests(TestCase):
@@ -1015,9 +1093,14 @@ def test_iterator(self):
10151093
assert isinstance(it, typing.Iterator[int])
10161094
assert not isinstance(42, typing.Iterator)
10171095

1096+
@skipUnless(PY35, 'Python 3.5 required')
10181097
def test_awaitable(self):
1019-
async def foo() -> typing.Awaitable[int]:
1020-
return await AwaitableWrapper(42)
1098+
ns = {}
1099+
exec(
1100+
"async def foo() -> typing.Awaitable[int]:\n"
1101+
" return await AwaitableWrapper(42)\n",
1102+
globals(), ns)
1103+
foo = ns['foo']
10211104
g = foo()
10221105
assert issubclass(type(g), typing.Awaitable[int])
10231106
assert isinstance(g, typing.Awaitable)
@@ -1028,6 +1111,7 @@ async def foo() -> typing.Awaitable[int]:
10281111
typing.Awaitable[Manager])
10291112
g.send(None) # Run foo() till completion, to avoid warning.
10301113

1114+
@skipUnless(PY35, 'Python 3.5 required')
10311115
def test_async_iterable(self):
10321116
base_it = range(10) # type: Iterator[int]
10331117
it = AsyncIteratorWrapper(base_it)
@@ -1037,6 +1121,7 @@ def test_async_iterable(self):
10371121
typing.AsyncIterable[Employee])
10381122
assert not isinstance(42, typing.AsyncIterable)
10391123

1124+
@skipUnless(PY35, 'Python 3.5 required')
10401125
def test_async_iterator(self):
10411126
base_it = range(10) # type: Iterator[int]
10421127
it = AsyncIteratorWrapper(base_it)
@@ -1127,6 +1212,22 @@ class MyDict(typing.Dict[str, int]):
11271212
d = MyDict()
11281213
assert isinstance(d, MyDict)
11291214

1215+
def test_no_defaultdict_instantiation(self):
1216+
with self.assertRaises(TypeError):
1217+
typing.DefaultDict()
1218+
with self.assertRaises(TypeError):
1219+
typing.DefaultDict[KT, VT]()
1220+
with self.assertRaises(TypeError):
1221+
typing.DefaultDict[str, int]()
1222+
1223+
def test_defaultdict_subclass_instantiation(self):
1224+
1225+
class MyDefDict(typing.DefaultDict[str, int]):
1226+
pass
1227+
1228+
dd = MyDefDict()
1229+
assert isinstance(dd, MyDefDict)
1230+
11301231
def test_no_set_instantiation(self):
11311232
with self.assertRaises(TypeError):
11321233
typing.Set()
@@ -1251,15 +1352,15 @@ def stuff(a: TextIO) -> str:
12511352
return a.readline()
12521353

12531354
a = stuff.__annotations__['a']
1254-
assert a.__parameters__ == (str,)
1355+
assert a.__parameters__ == ()
12551356

12561357
def test_binaryio(self):
12571358

12581359
def stuff(a: BinaryIO) -> bytes:
12591360
return a.readline()
12601361

12611362
a = stuff.__annotations__['a']
1262-
assert a.__parameters__ == (bytes,)
1363+
assert a.__parameters__ == ()
12631364

12641365
def test_io_submodule(self):
12651366
from typing.io import IO, TextIO, BinaryIO, __all__, __name__
@@ -1346,8 +1447,9 @@ def test_all(self):
13461447
assert 'ValuesView' in a
13471448
assert 'cast' in a
13481449
assert 'overload' in a
1349-
assert 'io' in a
1350-
assert 're' in a
1450+
# Check that io and re are not exported.
1451+
assert 'io' not in a
1452+
assert 're' not in a
13511453
# Spot-check that stdlib modules aren't exported.
13521454
assert 'os' not in a
13531455
assert 'sys' not in a

0 commit comments

Comments
 (0)