I made a typo in my code and replaced an =
with a :
, which resulted in a line of code that looked like:
data = {}
data["teapot"]: "turtle"
To my surprise, this did not produce a syntax error, but I don't understand what it's doing.
I then dumped the abstract syntax tree and it appears that it is some sort of type hint, although not one I've been able to find an example of elsewhere:
>>> import ast
>>> print(ast.dump(ast.parse("data['x']: 'turtle'"), indent=2))
Module(
body=[
AnnAssign(
target=Subscript(
value=Name(id='data', ctx=Load()),
slice=Constant(value='x'),
ctx=Store()),
annotation=Constant(value='turtle'),
simple=0)],
type_ignores=[])
What does this code mean? If it is, as I guess based on the AST, a type hint, does it have any practical use?
This comes from a combination of two features of type annotation syntax.
First, you can put a type hint after any expression that could syntactically be the target of an assignment. This includes identifiers (e.g. data
), indexed expressions (e.g. data["teapot"]
), attributes (e.g. data.teapot
). It doesn't have to be an actual assignment; it's common to put type hints for variables at the beginning of a function or class, and fill in the value later.
Second, the type name can be a string literal, because this is used for forward references to types that haven't yet been defined. Forward references are needed when you have circular or recursive chains of type hints, to solve the chicken-and-egg problem.
So your example fits this case
data["teapot"]: "turtle"
It simply declares that the eventual value of data["teapot"]
will be of the type named turtle
, which may not yet be defined.