Type of compiled regex object in python

后端 未结 10 1090
一个人的身影
一个人的身影 2020-11-30 07:14

What is the type of the compiled regular expression in python?

In particular, I want to evaluate

isinstance(re.compile(\'\'), ???)

10条回答
  •  忘掉有多难
    2020-11-30 07:36

    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.

提交回复
热议问题