Search code examples
pythonpycharmwarnings

PyCharm type warnings - Iterable vs ValuesView/KeysView/ItemsView


Lately in PyCharm (I don't know which version started it, I'm currently running 2021.2.3 Pro), I'm getting warnings that don't make sense.

For example, this snippet:

d = {1: 2, 3: 4, 5: 6}
for v in d.values():
    print(v)

Triggers the following warning:

Expected type 'collections.Iterable', got 'ValuesView' instead

In the above snippet, replacing values() with keys() gives a similar warning.

BTW, the return value of d.values() is dict_values and not ValuesView:

type(d.values())
<class 'dict_values'>

Why does PyCharm give me this warning, when this has always been the correct way to iterate over dictionary keys/values?

It might be a bug in PyCharm, but maybe I'm missing something.


EDIT: Even the sample code at https://docs.python.org/3.8/library/stdtypes.html#dict-views gets this warning, see screenshot.enter image description here


Solution

  • This is a regression of a known bug in the PyCharm 2021.2.3 linter, see PY-41457 on the JetBrains bug tracker.

    It doesn't happen for me using the immediately previous PyCharm 2021.2.2 Pro version.

    The solution, for now, is to report the regression on the JetBrains bug tracker and wait for a fix. There's nothing wrong with your code.