Parameterized generics cannot be used with class or instance checks

Question:

I wrote the code, but I get the following message in pycharm(2019.1):
“Parameterized generics cannot be used with class or instance checks”

    def data_is_valid(data):
        keys_and_types = {
            'comment': (str, type(None)),
            'from_budget': (bool, type(None)),
            'to_member': (int, type(None)),
            'survey_request': (int, type(None)),
        }

        def type_is_valid(test_key, test_value):
            return isinstance(test_value, keys_and_types[test_key])

        type_is_valid('comment', 3)

I really do not understand this message well. Did I do something wrong or is it a bug in pycharm?
The error disappears if I explicitly typecast to tuple.

def type_is_valid(test_key, test_value):
    return isinstance(test_value, tuple(keys_and_types[test_key]))

screenshot

Asked By: Mogost

||

Answers:

That looks like a bug in pycharm where it’s a bit overeager in assuming that you’re using the typing module in an unintended way. See this example here where that assumption would have been correct:

enter image description here

The classes in the typing module are only useful in a type annotation context, not to inspect or compare to actual classes, which is what isinstance tries to do. Since pycharm sees a simple object with square brackets that do not contain a literal, it jumps to the wrong conclusion you are seeing.

Your code is fine, you can use it exactly as it is.

Answered By: Arne

This was a known bug in PyCharm 2018, reported here.

There are some related bugs still in more recent PyCharm versions, e.g. PyCharm 2021.2.2, here.

In general, when you found that some PyCharm warning is incorrect, I would first isolate a simple test case where it becomes more clear what PyCharm is actually incorrect about. When it is clear that PyCharm is wrong with the warning, then you should always fill a bug report about it (or maybe search for existing bug reports first). Here this is clear because PyCharm says you cannot do sth, while in fact you can, so sth is wrong.

Answered By: Albert

I will not repeat after others that this is a pycharm bug. Just if you are a perfectionist and the error hurts your eyes, add the comment

# noqa

to the line where the "error" is

Answered By: user19051337

Since it’s agreed it’s a bug, you can suppress it in Pycharm by the line:

# noinspection PyTypeHints
Answered By: Banik
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.