python - PyCharm 类型检查没有按预期工作

标签 python python-3.x pycharm python-3.5 typing

编辑

根据@Jim Fasarakis Hilliard 的回答,我知道这不是错误,而是预期的行为。所以,我想补充一个问题——我能以某种方式强制 mypy--strict-optional 类似 PyCharm 类型的功能吗检查员?


在观看了关于 Python 3.5+Pycharm 中的类型检查的几个视频后,我认为这应该被标记为错误的返回类型:

from typing import Optional, List
import random

def r() -> Optional[List[int]]:
    if random.choice([0, 1]):
        return [1, 2, 3]
    return None


def f() -> List[int]:
    return r()

enter image description here

f() 函数可以返回 intlist 或明确指定的 None,但是 PyCharm 不会将 return r() 标记为错误的返回。

def f() -> List[int]:
    return None

enter image description here

例如,如果 f() 函数如上所示,PyCharm 会检测到存在错误的 return 类型。

这是一个错误还是我应该更改一些设置?我将类型检查的严重性提高到 error

最佳答案

PyCharm 的类型检查器可能以与 mypy 相同的方式处理 None,请参阅:The type of None and optional types (至少,在这种情况下它是这样做的。)

这与以下函数类型在 mypy (0.580) 和 PyCharm (build 173.4301.16) 中检查的原因相同:

def foo(x: Optional[int]) -> int:
    return x + 2

猜想有人可以将其称为错误吗?无论哪种方式,mypy 都提供了 --strict-optional标志来处理这些,并在使用时捕获您的原始错误:

error: Incompatible return value type (got "Optional[List[int]]", expected "List[int]")

根据 mypy 的文档,此标志将在未来的版本中默认使用。尽管我在他们的 documentation on Type Hints 中找不到任何相关信息,但我可以安全地假设 PyCharm 会在某个时候效仿.

关于python - PyCharm 类型检查没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49814187/

相关文章:

python - 我无法让 import random 工作 - python 3

python - Pycharm调试器无法启动: finished with exit code -1073741819 (0xC0000005)

python - 变量不能被定义

python - Pycharm无法导入数学模块

python - PyInstaller:ValueError:模块文件...丢失

python - 使用 ctypes 实现 union 的困惑

python - 在数据框中添加字典作为新行

python - 规范化/标准化 numpy recarray

python - 如何检查字符串是否只包含大写或小写字母?

c - 有没有可以同时调试 C 和 Python 代码的 IDE?