Multi-level type resolution
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 20.6k
- フォーク
- 3.3k
- PR マージ指標
- PR 指標を取得中
説明
Feature
It would be nice if Mypy was able to resolve the types in the below snippet:
import os
import typing as t
T = t.TypeVar('T')
R = t.TypeVar('R')
class flatmap(t.Generic[T, R]):
def __init__(self, func: t.Callable[[T], R]) -> None:
self.func = func
def __ror__(self, value: t.Optional[T]) -> t.Optional[R]:
if value is not None:
return self.func(value)
return None
# error: Cannot infer type argument 1 of "flatmap"
# error: "object" has no attribute "upper"
print(os.getenv('VARNAME') | flatmap(lambda m: m.upper()))
print(os.getenv('VARNAME') | flatmap(str.upper)) # ok
Pitch
Looking at just flatmap(lambda m: m.upper()), neither T nor R can be immediately determined.
However, it should be possible to deduce the type variables by taking into account the broader
context.
T = strcan be derived from the__ror__()call- After propagating
Tinto theflatmap()andlambda,R = strcan be deduced from the lambda body
One potential use case is already highlighted in the example above. Being able to chain the flatmap() function using ror adds a lot of readability compared to a normal call:
# 1)
os.getenv('VARNAME') | flatmap(lambda m: m.upper())
# 2)
flatmap(os.getenv('VARNAME'), lambda m: m.upper())
The obvious workaround in this example would be to use str.upper which would satisfy Mypy because the function is already typed. However, there are other example where the there is no already-typed alternative, like accessing an attribute of an optional object. Nr. 1 would be preferred over 2 for it's better readability. 3 is an alternative without a helper function, though that also gets harder to read as you start to work with more optional values.
# 1)
email = maybe_get_user() | flatmap(lambda user: user.email) | flatmap(sanitize_email_address)
# 2)
email = flatmap(flatmap(maybe_get_user(), lambda user: user.email), sanitize_email_address)
# 3)
user = maybe_get_user()
email = sanitize_email_address(user.email) if user and user.email else None
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
提供された Python スニペットで問題を再現し、lambda のケースと動作する str.upper のケースを比較します。mypy による汎用 flatmap 構築の処理、ror 呼び出し、および lambda を通じた伝播を追跡します。完了条件は、例がエラーなしで期待される Optional[str] の結果を推論することです。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- compilers, devtools
- issue の種類
- 機能追加
- 難易度
- 5/5
- 見積もり時間
- 1週間以上
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 35/100