Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

python - Type checking class static variables in PyCharm

I have the following Python code in a PyCharm project:

class Category:
    text: str

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

The editor is supposed to show a warning as I'm trying to set an attribute with a wrong type. Have a look below at the settings below:

screenshot of PyCharm settings configuration


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a bug, PyCharm implements its own static type checker, if you try the same code using MyPy the static type checker will emit the warnings. Changing IDE configurations does not change this, the only way is using a different Linter.

I slightly altered the code to make sure a docstring wouldn't make a difference.

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 does give the following warnings:

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)

EDIT: In the comments it was pointed out there's a bug report PY-36889 on JetBrains.

It's also worth mentioning, by the way, that the example in the question sets a static class variable but also rebinds it by setting the value on an instance. This thread gives a lengthy explanation.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...