Skip to content

Proposal: add @typing.format_specifiers #2321

Description

@jonathandung

This decorator factory would tell type checkers what format codes are supported by instances of that type. It would take variable positional arguments, each a string corresponding to a valid specification, and type checkers will know the class its returned decorator is applied to will only take those format specifications, so that it can flag mistyped format specifications and make subtle bugs clear. It, however, requires special-casing string formatting and the format builtin.

Currently it is possible to restrict the type of format_spec in __format__ to Literal[...], but that will cause Liskov substitution principle violations and type checkers may not consider it.

I am opening an issue here in hopes of getting more feedback because my DPO thread has gained little traction.

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: featureDiscussions about new features for Python's type annotations

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions