Proposal: add `@typing.format_specifiers(...)`

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.

2 Likes

python/typing#2321

As much as I like the idea, adding a new decorator and new mechanism for type checkers to implement just to solve the very specific problem of knowing which formatting codes are supported by a class doesn’t really sit well with me.

Makes me wonder if it’s really a type-checking problem to begin with? It seems like a question of supported values, not our set-theoretic types.

To deduce what format codes an object supports, the type of the object has to be known. I forgot to include the context; this actually stemmed from astral-sh/ruff#25744.

A decorator definitely seems like the wrong way to handle this (and other) typing features. Anything done for the benefit of static analysis should be possible to defer and not have runtime costs.

type-checkers could use the signature of __format__ here, no decorator required. Any LSP issue for this is likely a typechecker issue along the lines of other issues with typecheckers not holistically incorporating the data model methods into the typechecker’s knowledge and constraints

1 Like

Agreed that this is a possibility.