Skip to content

Commit 88a0ac6

Browse files
brettcannongvanrossum
authored andcommitted
Port ContextManager from cpython repository (python#199)
https://hg.python.org/cpython/rev/841a263c0c56
1 parent fa78d52 commit 88a0ac6

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

src/test_typing.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import contextlib
12
import pickle
23
import re
34
import sys
@@ -1309,6 +1310,21 @@ def __len__(self):
13091310
assert len(MMB[KT, VT]()) == 0
13101311

13111312

1313+
class OtherABCTests(TestCase):
1314+
1315+
@skipUnless(hasattr(typing, 'ContextManager'),
1316+
'requires typing.ContextManager')
1317+
def test_contextmanager(self):
1318+
@contextlib.contextmanager
1319+
def manager():
1320+
yield 42
1321+
1322+
cm = manager()
1323+
assert isinstance(cm, typing.ContextManager)
1324+
assert isinstance(cm, typing.ContextManager[int])
1325+
assert not isinstance(42, typing.ContextManager)
1326+
1327+
13121328
class NamedTupleTests(TestCase):
13131329

13141330
def test_basics(self):
@@ -1447,6 +1463,8 @@ def test_all(self):
14471463
assert 'ValuesView' in a
14481464
assert 'cast' in a
14491465
assert 'overload' in a
1466+
if hasattr(contextlib, 'AbstractContextManager'):
1467+
assert 'ContextManager' in a
14501468
# Check that io and re are not exported.
14511469
assert 'io' not in a
14521470
assert 're' not in a

src/typing.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import abc
22
from abc import abstractmethod, abstractproperty
33
import collections
4+
import contextlib
45
import functools
56
import re as stdlib_re # Avoid confusion with the re we export.
67
import sys
@@ -1530,6 +1531,12 @@ class ValuesView(MappingView[VT_co], extra=collections_abc.ValuesView):
15301531
pass
15311532

15321533

1534+
if hasattr(contextlib, 'AbstractContextManager'):
1535+
class ContextManager(Generic[T_co], extra=contextlib.AbstractContextManager):
1536+
__slots__ = ()
1537+
__all__.append('ContextManager')
1538+
1539+
15331540
class Dict(dict, MutableMapping[KT, VT]):
15341541

15351542
def __new__(cls, *args, **kwds):

0 commit comments

Comments
 (0)