Type of compiled regex object in python
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.
When the type of something isn't well specified, there's nothing wrong with using the type
builtin to discover the answer at runtime:
>>> import re
>>> retype = type(re.compile('hello, world'))
>>> isinstance(re.compile('goodbye'), retype)
True
>>> isinstance(12, retype)
False
>>>
Discovering the type at runtime protects you from having to access private attributes and against future changes to the return type. There's nothing inelegant about using type
here, though there may be something inelegant about wanting to know the type at all.
That said, with the passage of time, the context of this question has shifted. With contemporary versions of Python, the return type of re.compile
is now re.Pattern
.
The general question about what to do if the type of something is not well-specified is still valid but in this particular case, the type of re.compile(...)
is now well-specified.