Assigning a variable from either of two optional variables

未关闭
#11,404 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

评估

难度
4/5
预计耗时
3-5 天
新手友好度
35/100
Issue 类型
缺陷
描述清晰度
基本清楚
活跃度
停滞
技术栈
python
领域
devtools

调研方向

使用提供的 Python 复现程序作为第一个切入点,并对提前返回后的 x or y 赋值运行 mypy。跟踪此控制流是如何分析的;完成标准是示例接受 otherstr,同时不削弱其他位置报告的 Optional 行为。

由索引模型根据 Issue 内容生成。

描述

feature topic-type-narrowing

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
主要语言
Python
星标
20.6k
派生
3.3k
平均合并
1 天 18 小时
30 天内合并 PR
54

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

python/mypy 的其他 Issue

查看 python/mypy 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。