[Python] Understanding Python type annotation after indexing

Discussão em 'Python' iniciado por Stack, Julho 7, 2025.

  1. Stack

    Stack Membro Participativo

    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?

    Continue reading...

Compartilhe esta Página