我想知道什么是正确的pythonic向后兼容和向前兼容方法如何检查对象是否是编译re对象.
isinstance方法不能轻易使用,而生成的对象声称是_sre.SRE_Pattern对象:
>>> import re
>>> rex = re.compile('')
>>> rex
<_sre.SRE_Pattern object at 0x7f63db414390>
Run Code Online (Sandbox Code Playgroud)
但没有这样的:
>>> import _sre
>>> _sre.SRE_Pattern
AttributeError: 'module' object has no attribute 'SRE_Pattern'
>>> import sre
__main__:1: DeprecationWarning: The sre module is deprecated, please import re.
>>> sre.SRE_Pattern
AttributeError: 'module' object has no attribute 'SRE_Pattern'
>>> re.SRE_Pattern
AttributeError: 'module' object has no attribute 'SRE_Pattern'
Run Code Online (Sandbox Code Playgroud)
我不想使用duck typing(即检查某些特定方法的可用性),因为这可能会与其他一些类型冲突.
现在,我正在使用:
>>> RegexpType = type(re.compile(''))
>>> type(rex) == RegexpType
True
Run Code Online (Sandbox Code Playgroud)
但可能有更好的方法..
如果我编译一个正则表达式
>>> type(re.compile(""))
<class '_sre.SRE_Pattern'>
Run Code Online (Sandbox Code Playgroud)
并希望将该正则表达式传递给函数并使用Mypy来键入check
def my_func(compiled_regex: _sre.SRE_Pattern):
Run Code Online (Sandbox Code Playgroud)
我遇到了这个问题
>>> import _sre
>>> from _sre import SRE_Pattern
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'SRE_Pattern'
Run Code Online (Sandbox Code Playgroud)
您似乎可以导入_sre但由于某种原因SRE_Pattern不可导入.
我正在编写一个函数来处理预编译的正则表达式。我如何明确定义这一点?例如
def use_regular_expression(regular_expression: ???):
pass
Run Code Online (Sandbox Code Playgroud)
我要写什么来代替“???” 只接受re.compile给定有效正则表达式字符串的输出?
print(type(re.compile('')))说_sre.SRE_Pattern并且 PyCharm IDE 表明它是,re.__Regex但无论我尝试导入和指定它们的明显方式是什么,似乎都不起作用。