Assigning a variable from either of two optional variables
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 20.6k
- フォーク
- 3.3k
- PR マージ指標
- PR 指標を取得中
説明
Bug Report
consider the following example:
from typing import Optional
def test_something(x: Optional[str] = None, y: Optional[str] = None) -> str:
if not (x or y):
return "early"
other: str = x or y # <<< mypy complains that other should be Optional[str]
return other
am i not able to assume that other would be of type str given that if neither x nor y is given then the function would return early and the assignment of other would never happen? in other words, at the assignment of other, surely one or both of x or y would be of type str, therefore other would be of type str?
to further the argument, if i modify the example like so:
#!/usr/bin/env python3
from typing import Optional
def test_something(x: Optional[str] = None, y: Optional[str] = None) -> str:
if not (x or y):
return "early"
other: str = x or y
print(f"x = {x}")
print(f"y = {y}")
print(f"other class: {type(other)}")
print()
return other
test_something()
test_something(x="hello")
test_something(y="goodbye")
test_something(x="hello", y="goodbye")
and run it i get:
x = hello
y = None
other class: <class 'str'>
x = None
y = goodbye
other class: <class 'str'>
x = hello
y = goodbye
other class: <class 'str'>
To Reproduce
run mypy on the example above
Expected Behavior
mypy would not complain about typing other as str
Actual Behavior
running mypy on the above example yields:
.../test.py: note: In function "test_something":
.../test.py:8:18: error: Incompatible types in assignment (expression has type "Optional[str]", variable has type "str") [assignment]
other: str = x or y
^
Found 1 error in 1 file (checked 1 source file)
Your Environment
- Mypy version used: 0.910
- Mypy command-line flags: none
- Mypy configuration options from
mypy.ini(and other config files):
strict = true
pretty = true
show_column_numbers = true
show_error_codes = true
show_error_context = true
- Python version used: 3.7.9
- Operating system and version: MacOSX 10.15.7 Catalina
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
提供された Python の再現コードを最初の入口として使用し、早期 return の後にある x or y の代入に対して mypy を実行します。この制御フローがどのように解析されるかを追跡します。完了の条件は、他の箇所で報告される Optional の挙動を弱めることなく、例で other を str として受け入れられることです。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- devtools
- issue の種類
- バグ
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 35/100