Skip to content
Advertisement

Python annotate type as regex pattern

I have a dictionary annotation

class OrderDict(TypedDict):
    name: str
    price: float
    time: str

The value of time: will always be formatted like 2022-01-01 00:00:00, or "%Y-%m-%d %H:%M:%S". I’d like a way to express this in the type annotation

Something like

class OrderDict(TypedDict):
    name: str
    price: float
    time: Pattern["%Y-%m-%d %H:%M:%S"]

WIth the goal of IDE hinting through VSCode Intellisense and Pylance.

Are regex-defined type annotations supported?

Advertisement

Answer

Leaving out philosophical discussions about what should or should not be considered a type, what you are asking is not supported by the current type system.

It is valid syntax of course and you certainly can cook something up that abuses __class_getitem__ to return dynamically created subclasses of itself. From a runtime perspective you can implement your desired logic without much of an issue.

But no static type checker will recognize this (not least) because it does not conform to the specifications that are currently in place around types in Python. As others have pointed out, from the perspective of the Python type system, a string (literal) is not considered a type and thus cannot be passed as a type argument to a generic type.

Advertisement