Skip to content
Myr

Allow covariants of __enter__, __aenter__, and @classmethod (#1336)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Allow covariants of __enter__, __aenter__, and @classmethod The problem we currently have is the return type of classes such as Client does not allow covariants when subclassing or context manager. In other words: ```python class Base: def __enter__(self) -> Base: # XXX return self class Derived(Base): ... with Derived() as derived: # The type of derived is Base but not Derived. It is WRONG ... ``` There are three approaches to improve type annotations. 1. Just do not type-annotate and let the type checker infer `return self`. 2. Use a generic type with a covariant bound `_AsyncClient = TypeVar('_AsyncClient', bound=AsyncClient)` 3. Use a generic type `T = TypeVar('T')` or `Self = TypeVar('Self')` They have pros and cons. 1. It just works and is not friendly to developers as there is no type annotation at the first sight. A developer has to reveal its type via a type checker. Aslo, documentation tools that rely on type annotations lack the type. I haven't found any python docuementation tools that rely on type inference to infer `return self`. There are some tools simply check annotations. 2. This approach is correct and has a nice covariant bound that adds type safety. It is also nice to documentation tools and _somewhat_ friendly to developers. Type checkers, pyright that I use, always shows the the bounded type '_AsyncClient' rather than the subtype. Aslo, it requires more key strokes. Not good, not good. It is used by `BaseException.with_traceback` See https://github.com/python/typeshed/pull/4298/files 3. This approach always type checks, and I believe it _will_ be the official solution in the future. Fun fact, Rust has a Self type keyword. It is slightly unfriendly to documentation, but is simple to implement and easy to understand for developers. Most importantly, type checkers love it. See https://github.com/python/mypy/issues/1212 But, we can have 2 and 3 combined: ```python _Base = typing.TypeVar('_Base', bound=Base) class Base: def __enter__(self: _Base) -> _Base: return self class Derive(Base): ... with Derived() as derived: ... # type of derived is Derived and it's a subtype of Base ``` * revert back type of of SteamContextManager to Response * Remove unused type definitions * Add comment and link to PEP484 for clarification * Switch to `T = TypeVar("T", covariant=True)` * fixup! Switch to `T = TypeVar("T", covariant=True)` * Add back bound=xxx in TypeVar

authored by Changsheng · committed by GitHub · parent 65b69fa · Browse files · 1 file+8 added−2 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Florimond Manca <florimond.manca@gmail.com>

Diff stats

1 file+8 added−2 removed

  • other:+8 added−2 removed

1 file+8 added−2 removed

modified:httpx/_client.py+8 added-2 removed
54 unmodified lines
55 same_origin,56 warn_deprecated,57)5859# The type annotation for @classmethod and context managers here follows PEP 48460# https://www.python.org/dev/peps/pep-0484/#annotating-instance-and-class-methods61T = typing.TypeVar("T", bound="Client")62U = typing.TypeVar("U", bound="AsyncClient")636465logger = get_logger(__name__)6667KEEPALIVE_EXPIRY = 5.068USER_AGENT = f"python-httpx/{__version__}"
1042 unmodified lines
1111 for proxy in self._proxies.values():1112 if proxy is not None:1113 proxy.close()11141109 def __enter__(self) -> "Client":1115 def __enter__(self: T) -> T:1116 self._transport.__enter__()1117 for proxy in self._proxies.values():1118 if proxy is not None:1119 proxy.__enter__()
637 unmodified lines
1757 for proxy in self._proxies.values():1758 if proxy is not None:1759 await proxy.aclose()17601755 async def __aenter__(self) -> "AsyncClient":1761 async def __aenter__(self: U) -> U:1762 await self._transport.__aenter__()1763 for proxy in self._proxies.values():1764 if proxy is not None:1765 await proxy.__aenter__()
84 unmodified lines