Search code examples
pythonpycharmpython-typing

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


Solution

  • 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