Skip to content

inspect.get_annotations(eval_str=True) raises SyntaxError for PEP-646 unpacked tuple annotation *tuple[...] #138891

@artemyefimov

Description

@artemyefimov

Bug report

Bug description:

Problem

inspect.get_annotations(eval_str=True) raises a SyntaxError when evaluating unpacked tuple annotations (*tuple[...]):

from __future__ import annotations
from inspect import get_annotations

def f(*args: *tuple[int, ...]): ...

print(get_annotations(f, eval_str=True))  # Raises SyntaxError

The error occurs because *tuple[int, ...] is not a valid standalone expression for eval().

Expected

According to typing spec, *tuple[...] is valid in this context.

typing.get_type_hints already normalizes such annotations:

from __future__ import annotations
from typing import get_type_hints

def f(*args: *tuple[int, ...]): ...

print(get_type_hints(f))  # {'args': typing.Unpack[tuple[int, ...]]}

inspect.get_annotations should behave consistently and not raise SyntaxError.

Possible Resolution

Make inspect.get_annotations(eval_str=True) aware of this special case and transform annotation strings of the form *tuple[...] into typing.Unpack[tuple[...]] before evaluation, similar to what typing.get_type_hints does.

CPython versions tested on:

3.13

Operating systems tested on:

Linux

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytopic-typingtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions