Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type annotation for dict.items() [duplicate]

Sample code:

def test() -> list[tuple[str, int]]:
    some_dict = {"some": 3, "another": 5}
    return some_dict.items()

For me it's quite obvious that it returns list of tuples: [("some", 3), ("another": 5)].

But dict.items() actually returns dict_items[("some", 3), ("another", 5)] and above result can be only achieved when casting it to list.

I wanted to have type annotation for this case, but list[tuple[str, int]] isn't working (checked with MyPy version 0.961) and I can't find anywhere how to annotate dict_items.

How to annotate function like this (without casting it to list, and preserving information about return type, not just Any)?

like image 259
Xalzir Avatar asked Mar 14 '26 23:03

Xalzir


1 Answers

Use ItemsView:

from typing import ItemsView


def test() -> ItemsView[str, int]:
    some_dict = {"some": 3, "another": 5}
    return some_dict.items()

Output (mypy)

Success: no issues found in 1 source file

In Python 3.9+ use instead:

from collections.abc import ItemsView

A more "general" solution would be to use Iterable:

from collections.abc import Iterable

def test() -> Iterable[tuple[str, int]]:
    some_dict = {"some": 3, "another": 5}
    return some_dict.items()

but on a personal note I prefer to stick with Postel's Law:

"be conservative in what you send, be liberal in what you accept"

like image 190
Dani Mesejo Avatar answered Mar 16 '26 15:03

Dani Mesejo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!