Skip to content

Commit 20d9fcf

Browse files
nimin98ambv
authored andcommitted
Support callable contextmanagers in contextlib (#1152)
mypy could not recognize the case when we use contextmanager as a decorator, which has been supported since Python 3.2. In the following code snippet, from contextlib import contextmanager @contextmanager def foo(arg1): try: print(arg1) print('1') yield finally: print('2') @foo('0') def foo2(): print('3') foo2() we get mypy error as follows, error: ContextManager[Any] not callable The suggested changes can fix this error and properly reflect the updated contextmanager usage pattern.
1 parent 26360e8 commit 20d9fcf

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

stdlib/2and3/contextlib.pyi

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,12 @@ class ContextManager(Generic[_T]):
2020
exc_val: Optional[Exception],
2121
exc_tb: Optional[TracebackType]) -> bool: ...
2222

23-
def contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., ContextManager[_T]]: ...
23+
if sys.version_info >= (3, 2):
24+
class GeneratorContextManager(Generic[_T], ContextManager[_T]):
25+
def __call__(self, func: Callable[..., _T]) -> Callable[..., _T]: ...
26+
def contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., GeneratorContextManager[_T]]: ...
27+
else:
28+
def contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., ContextManager[_T]]: ...
2429

2530
if sys.version_info < (3,):
2631
def nested(*mgr: ContextManager[Any]) -> ContextManager[Iterable[Any]]: ...

0 commit comments

Comments
 (0)