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.
This commit is contained in:
nimin98
2017-04-11 14:51:03 -07:00
committed by Łukasz Langa
parent 26360e821b
commit 20d9fcf858

View File

@@ -20,7 +20,12 @@ class ContextManager(Generic[_T]):
exc_val: Optional[Exception],
exc_tb: Optional[TracebackType]) -> bool: ...
def contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., ContextManager[_T]]: ...
if sys.version_info >= (3, 2):
class GeneratorContextManager(Generic[_T], ContextManager[_T]):
def __call__(self, func: Callable[..., _T]) -> Callable[..., _T]: ...
def contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., GeneratorContextManager[_T]]: ...
else:
def contextmanager(func: Callable[..., Iterator[_T]]) -> Callable[..., ContextManager[_T]]: ...
if sys.version_info < (3,):
def nested(*mgr: ContextManager[Any]) -> ContextManager[Iterable[Any]]: ...