-1

Any documentation for this kind of declaration?

x: dict() = {}
y: list() = ()

also this works just fine:

v: list(list((1,2))) = {}
v["str"] = 1
#v returns {'str': 1}

What I understand: Starting the reading from the right; Evaluating the expression then returns its value and associate it to the left after evaluating it.

I did try some other combinations, just gave me more questions.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Kingloss404
  • 15
  • 2
  • 7
  • Would love to share this answer: https://stackoverflow.com/a/11008311/17306932. – never_again Jul 04 '22 at 03:50
  • That's a type annotation. The python statement is `v = {}`, a new, empty `dict` is created and assigned to `v`. `: dict()` is an "annotation" - a hint about what you expect `v` to contain. It doesn't affect the execution of the code, but some tools (and readers of the code) may find it useful. See also "Jumped The Shark" IMHO. – tdelaney Jul 04 '22 at 03:53

1 Answers1

2

This syntax is supposed to annotate the variable type, but Python itself completely ignores it (except for making sure the syntax is correct and any variables used therein are defined). It will be read by a static type checker, usually run by code editors to help programmers make fewer mistakes while writing code.

v: list(list((1,2))) = {} makes no sense, but Python will take it. As far as Python itself is concerned, this is equivalent to v = {}, since it ignores type annotations.

v: dict[str, int] = {} makes sense, and tells any static type checker that comes looking that v will be a dict whose keys are strings and whose values are integers. It will allow a code editor to see that v["str"] = 1 is okay, and to mark v[1] = "str" as an error.

Amadan
  • 191,408
  • 23
  • 240
  • 301