Type of compiled regex object in python

Since Python 3.7, you can use re.Pattern. At the time of writing, this is however undocumented: the re module doesn’t advertise that it exports the class, only the typing module mentions its existence (note that the documentation directly mentions functions like “re.findall”, but starts documenting Pattern’s methods with “Pattern.search”, not adding re. and not mentioning that Pattern is a class).

For older Python versions, see below:

Python 3.5 introduced the typing module. Included therein is typing.Pattern, a _TypeAlias.

Starting with Python 3.6, you can simply do:

from typing import Pattern

my_re = re.compile('foo')
assert isinstance(my_re, Pattern)

In 3.5, there used to be a bug requiring you to do this:

assert issubclass(type(my_re), Pattern)

Which isn’t guaranteed to work according to the documentation and test suite.

Leave a Comment