6

I'm trying to process a dict object, and PyCharm is giving me an unexpected type warning.

Here's a reduced example that produces the warning:

X = type("X", (), {})
def big_foo(data: Dict[str, Any]) -> Dict[str, Any]:
    def little_foo(entries: Iterable[Tuple[str, Any]]) -> Iterable[Tuple[X, Any]]:
        pass
    def little_bar(entry: Tuple[X, Any]) -> Tuple[str, Any]:
        pass
    return dict(map(little_bar, little_foo(data.items())))

PyCharm is attaching this warning to the phrase data.items() on the last line:

Expected type 'Iterable[Tuple[str, Any]]', got 'ItemsView[str, Any]' instead

I had confidently expected that dict.items() was returning some kind of Iterable of Tuples. Is there a good way of explaining to PyCharm what's going on? Is there actually a problem with the code?

Neuron
  • 5,141
  • 5
  • 38
  • 59
ShapeOfMatter
  • 991
  • 6
  • 25
  • 4
    `ItemsView` is defined as (according to PyCharm): `class ItemsView(MappingView, AbstractSet[Tuple[_KT_co, _VT_co]], Generic[_KT_co, _VT_co]): . . .`, so it's odd that an `ItemsView` wouldn't be an `Iterable[Tuple[x, y]]`, since it inherits from `AbstractSet[Tuple[x, y]]`. – Carcigenicate Apr 24 '20 at 14:50
  • 3
    Unless I'm missing some subtlety that's going on here, this appears to be Pycharm being short sighted. [This](https://gist.github.com/carcigenicate/21fb8c98deb9db48215ecbfe66123a1c) example, which seems to distill what's going on down, works as expected. – Carcigenicate Apr 24 '20 at 14:56
  • 1
    And it also has no problem with an even more [complicated example](https://gist.github.com/carcigenicate/041bdba6c0f38b6bb1b7f7853c154737). Unless it has to do with generics, which I've neglected here? I have to start an exam unfortunately though, so I can't play around with it any more. – Carcigenicate Apr 24 '20 at 15:01

0 Answers0