`[Async]ContextDecorator.__call__` return type should depend on the underlying context manager's `_ExitT_co`

未關閉
#13,512 4 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

維護者通常 1 天內回覆

還沒有人認領這個 Issue。

  • #14439 來自 @johnslavik —— 已關閉,未合併

評估

難度
5/5
預估耗時
一週以上
新手友好度
35/100
Issue 類型
缺陷
描述清晰度
需要釐清
活躍度
停滯
技術堆疊
python

研究方向

從連結的 Python 討論和 Lib/contextlib.py 中的標準函式庫實作開始,重點關注 ContextDecorator.call 以及底層內容管理器的 _ExitT_co。確定包裝後 callable 的回傳型別所支援的型別層級關係,然後驗證該註解反映了內容管理器抑制操作回傳 None 的情況。

由索引模型根據 Issue 內容生成。

描述

[!Important]
Please see https://discuss.python.org/t/support-suppressing-generator-context-managers/103615 first!

This is how ContextDecorator.__call__ is implemented in the Python standard library:

def __call__(self, func):
    @wraps(func)
    def inner(*args, **kwds):
        with self._recreate_cm():
            return func(*args, **kwds)
    return inner

In typeshed, ContextDecorator.__call__ currently has a return type of the original callable (func).
However, if the return value of self._recreate_cm().__call__ is truthy, the return type of ContextDecorator.__call__ can as well be None, like in the silly example below:

from collections.abc import Generator
from contextlib import contextmanager, suppress
from typing import reveal_type


@contextmanager
def zero_division_to_none() -> Generator[None]:
    with suppress(ZeroDivisionError):
        yield


@zero_division_to_none()
def div(a: int, b: int) -> float:
    return a / b


reveal_type(div(1, 0))
# mypy, pyright: Revealed type is "builtins.float"
# Runtime type is 'NoneType'

My first shot was to patch the proper __call__ functions to "extend" the return type with _ThrottledExcReturnT (a new type parameter of ContextDecorator), constrained by Never and None, with the default type Never for backward compatibility. To me, there's no way to declare the relationship symbolically, so it would have to be typed manually in classes implementing the context manager protocol.

主要語言
Python
星號
5.1k
分支
2.1k
平均合併
2 天 7 分鐘
30 天內合併 PR
116

環境準備

  • 沒有 Dockerfile 或 Docker Compose 檔案
  • 沒有 Pull Request 範本
  • 閱讀貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

python/typeshed 的其他 Issue

查看 python/typeshed 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。