5

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

bad_coder
  • 11,289
  • 20
  • 44
  • 72
SexyMF
  • 10,657
  • 33
  • 102
  • 206
  • 1
    What python version are you using? And how is your Pycharm configured relating to that? Enabling `TypeChecker` will only work if the `TypeChecker` used can detect the type error/warning, and it's not clear in your question here what is _actually_ used to check the type... – Jean-Benoit Harvey Dec 30 '20 at 13:50
  • @Jean-BenoitHarvey - the version is 2020.3, the problem is that if text property is `str`, I why don't I see a warning when setting text = number? thanks – SexyMF Dec 30 '20 at 13:59

1 Answers1

4

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
bad_coder
  • 11,289
  • 20
  • 44
  • 72
  • 2
    There is in fact a bug filed for this: [PY-36889](https://youtrack.jetbrains.com/issue/PY-36889). Hasn't been fixed after a year, though. – CrazyChucky Jan 02 '21 at 01:33