Search code examples
pythonpycharmpython-3.9

isinstance showing error when lookup is used for type comparison (Possible Pycharm Error)


I am trying to write a function that checks that data read in is of the same type as a dictionary of default values. My code is:

defaults: dict[str, type] = {
    "a": str,
    "b": int,
}

read_in = {
    "a": "life_of",
    "b": "brian"
}

for key, value in read_in.items():
    correct_type = defaults[key]
    if not isinstance(value, correct_type):
        print("wrong type")
        break

The correct type in isinstance shows as an error in my IDE (Pycharm community edition) . However, the code does run correctly (at least in this simple instance). From this I can see two options.

  1. Pycharm has a bug which causes an error to show where none exits
  2. I've made some kind of horrible mistake that will introduce a hard to debug error into my code.

The error is "Parameterized generics cannot be used with instance and class checks"

Does anyone know which it is?

Thanks


Solution

  • This is an existing pycharm issue (https://youtrack.jetbrains.com/issue/PY-32860). If you dont like the error you can add #noqa to the line:

    defaults: dict[str, type] = {
        "a": str,
        "b": int,
    }
    
    read_in = {
        "a": "life_of",
        "b": "brian"
    }
    
    for key, value in read_in.items():
        correct_type = defaults[key]
        if not isinstance(value, correct_type): # noqa
            print("wrong type")
            break