python / python/typing

Awaitable typeguards

オープン
#1,872 コメント 1 件 リアクション 1 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

topic: feature
主要言語
Python
スター
1.8k
フォーク
302
平均マージ
23時間
マージ済み PR(30日)
8

説明

Currently it seems impossible to have async TypeGuard or TypeIs:

from typing_extensions import TypeIs

async def foo(a: int | str) -> TypeIs[int]:
    raise NotImplementedError

async def main() -> None:
    a: int | str = 10
    if await foo(a):
        reveal_type(a)
    else:
        reveal_type(a)

Current specification is not clear about how async functions returning TypeIs or TypeGuards should be treated, but I believe this would be useful for async lazy evaluation of typestate fields, example:

from typing_extensions import TypeIs, TypeVar, Generic


T = TypeVar('T', int | None, int, None, covariant=True)


class A(Generic[T]):
    _a: T
    
    async def get_a(self: A[int | None]) -> int | None:
        a = 123  # imagine some expensive async operation, e.g. fetch value from API
        self._a = a
        return self._a
        
    def method_requires_a(self: A[int]) -> None:
        raise NotImplementedError
        
    def __init__(self):
        self._a = None

async def has_a(a: A[int | None]) -> TypeIs[A[int]]:
    return await a.get_a() is not None
 
 
async def main(a: A[int | None]):
    if await has_a(a):
        a.method_requires_a()  # currently fails as type was not narrowed

コントリビューションガイド

このリポジトリのコントリビューションガイドは索引されていません

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

この issue には、リポジトリのファイル、テスト、実装のエントリーポイントが記載されていません。まず、TypeIs または TypeGuard を返す async 関数について typing 仕様でどのように扱われているかを確認し、次に提案された絞り込みをどのように定義すべきかを決定してください; 合意された仕様と、それに対応する実装およびテストが揃えば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
devtools
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
説明が足りない
初心者へのやさしさ
25/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。