Fixes to ContextManager (#1249)

* add typing.ContextManager for 3.6+ only

This fixes the easier part of #655.

Would it make sense to add a generic typing.ContextManager that exists in any Python version?

* update comment

* fix argument types for ContextManager.__exit__

* add AsyncContextManager

* add @asynccontextmanager

* typing.ContextManager now always exists

* back out async-related changes

Will submit those in a separate PR later

* fix import order

* AbstractContextManager only exists in 3.6+

* AbstractContextManager -> ContextManager
This commit is contained in:
Jelle Zijlstra
2017-05-08 16:21:51 -07:00
committed by Matthias Kramm
parent 385b9c8b66
commit 7dd2f80194
5 changed files with 28 additions and 20 deletions

View File

@@ -2,7 +2,7 @@
import sys
from abc import abstractmethod, ABCMeta
from types import CodeType, FrameType
from types import CodeType, FrameType, TracebackType
# Definitions of special type checking related constructs. Their definition
# are not used, so their value does not matter.
@@ -127,7 +127,7 @@ class Generator(Iterator[_T_co], Generic[_T_co, _T_contra, _V_co]):
gi_yieldfrom = ... # type: Optional[Generator]
# TODO: Several types should only be defined if sys.python_version >= (3, 5):
# Awaitable, AsyncIterator, AsyncIterable, Coroutine, Collection, ContextManager.
# Awaitable, AsyncIterator, AsyncIterable, Coroutine, Collection.
# See https: //github.com/python/typeshed/issues/655 for why this is not easy.
class Awaitable(Generic[_T_co]):
@@ -281,7 +281,11 @@ class ValuesView(MappingView, Iterable[_VT_co], Generic[_VT_co]):
def __contains__(self, o: object) -> bool: ...
def __iter__(self) -> Iterator[_VT_co]: ...
# TODO: ContextManager (only if contextlib.AbstractContextManager exists)
class ContextManager(Generic[_T_co]):
def __enter__(self) -> _T_co: ...
def __exit__(self, exc_type: Optional[Type[BaseException]],
exc_value: Optional[BaseException],
traceback: Optional[TracebackType]) -> Optional[bool]: ...
class Mapping(_Collection[_KT], Generic[_KT, _VT_co]):
# TODO: We wish the key type could also be covariant, but that doesn't work,

View File

@@ -3,12 +3,11 @@
from typing import (
Any, Callable, Dict, Iterable, Iterator, List, Optional, Pattern, Sequence,
Set, FrozenSet, TextIO, Tuple, Type, TypeVar, Union, Generic,
overload,
overload, ContextManager
)
import logging
import sys
from types import ModuleType, TracebackType
from contextlib import ContextManager
_T = TypeVar('_T')