【问题标题】:Type checking class static variables in PyCharmPyCharm 中的类型检查类静态变量
【发布时间】:2021-04-07 00:27:44
【问题描述】:

我在 PyCharm 项目中有以下 Python 代码:

class Category:
    text: str

a = Category()
a.text = 1.5454654  # where is the warning?

当我试图设置一个错误类型的属性时,编辑器应该显示一个警告。看看下面的设置:

【问题讨论】:

  • 你用的是什么python版本?你的 Pycharm 是如何配置的?启用TypeChecker 仅在使用的TypeChecker 可以检测到类型错误/警告时才有效,并且在您的问题中不清楚实际上 用于检查类型...
  • @Jean-BenoitHarvey - 版本是 2020.3,问题是如果 text 属性是 str,我为什么在设置 text = number 时没有看到警告?谢谢

标签: python pycharm static-variables typechecking python-typing


【解决方案1】:

这是一个错误,PyCharm implements its own static type checker,如果您尝试the same code using MyPy,静态类型检查器将发出警告。更改 IDE 配置不会改变这一点,唯一的方法是使用不同的 Linter。

我稍微修改了代码以确保文档字符串不会产生影响。

class Category:
    """Your docstring.

    Attributes:
        text(str): a description.
    """

    text: str


a = Category()

Category.text = 11  # where is the warning?
a.text = 1.5454654  # where is the warning?

MyPy 确实给出了以下警告:

main.py:13: error: Incompatible types in assignment (expression has type "int", variable has type "str")
main.py:14: error: Incompatible types in assignment (expression has type "float", variable has type "str")
Found 2 errors in 1 file (checked 1 source file)

编辑:在 cmets 中指出有一个错误报告 PY-36889 on JetBrains

顺便提一下,问题中的示例设置了一个静态类变量,但还通过在实例上设置值来重新绑定它。 This thread 给出了冗长的解释。

>>> Category.text = 11
>>> a.text = 1.5454654  
>>> a.text
1.5454654
>>> Category.text
11

【讨论】:

  • 事实上存在一个错误:PY-36889。不过,一年后仍未修复。
猜你喜欢
  • 2021-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-13
  • 2010-11-23
  • 2011-08-26
  • 1970-01-01
  • 2012-01-02
相关资源
最近更新 更多