Reputation: 1182
What's the purpose of the dictionary type hint below?
def func(a: list) -> list:
b: dict[int, set[int]] = {}
# do stuff
# return a list
Is it only for use with a static type checker, or does it have other consequences? There are some similar typing questions on here but I haven't seen any answers newer than Python 3.7
Upvotes: 2
Views: 83
Reputation: 88
These are type hints. And they are valid syntax in all python versions greater than 3.5. With a caveat being that before python 3.9 you could not subscript dict[] and had to use typing.Dict instead (or use a special from __future__ import annotations
import)
Type hints are completely ignored by the python interpreter at run time, so they have no effect on the behaviour of the programme.
What they do effect is any static type checking analysis running on this file. E.g. mypy, pyright to name a few.
The type variables for a dict is (key type: value type). So this is saying that b is a dictionary mapping integers to sets of integers.
E.g.
{1: {1, 2, 3}, 2: {2, 3}}
Would satisfy this typing annotation by the type checker. But
{"1": {1, 2}}
would not since it maps strings to sets of integers.
There's more to this and it's worth reading https://peps.python.org/pep-0484/ for better information.
Upvotes: 2