3

I would like to understand what does the expression p: dict = {} mean. To me it is not as intuitive as p = {}. Why does the part : dict add to the expression? To me it appears to not add anything at all.

The code I am looking at is as follows

>>> p = {}
>>> p['s'] = 2
>>> p
{'s': 2}
>>> p: dict = {}
>>> p['a'] = 4
>>> p
{'a': 4}
piterbarg
  • 8,089
  • 2
  • 6
  • 22
  • 1
    It's type annotation. More info is [here](https://www.python.org/dev/peps/pep-0526/) – Abdul Niyas P M Dec 13 '20 at 06:27
  • They didn't want to make it like other languages that's all. – Mazdak Dec 13 '20 at 06:43
  • 2
    Note that the annotation in `p: dict = {}` is pretty pointless, since it does not add any information. Restricting the key, value types as in `p: dict[str, int] = {}` or `p: dict[str, int | str] = {}` would be more sensible. – MisterMiyagi Dec 14 '20 at 09:49

1 Answers1

1

It's for Python Type Checking. Since Python is a dynamic type language this syntax helps the developer to avoid errors related to type violation. There are tools like mypy which checks these syntax statistically. In your sample code, type for p is defined dict and initialized empty.

Check here as a reference

Pouya Esmaeili
  • 1,265
  • 4
  • 11
  • 25