我想知道什么是正确的pythonic向后和向前兼容的方法,如何检查一个对象是否是编译的re对象。
当结果对象声明为_sre.SRE_Pattern对象时,isinstance方法不容易使用:
>>> import re
>>> rex = re.compile('')
>>> rex
<_sre.SRE_Pattern object at 0x7f63db414390>但是没有这样的一个:
>>> 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'我不想使用鸭子类型(即检查某些特定方法的可用性),因为这可能会与其他类型发生冲突。
现在,我使用:
>>> RegexpType = type(re.compile(''))
>>> type(rex) == RegexpType
True但也许有更好的方法..。
发布于 2011-06-03 20:48:21
re._pattern_type存在,并且看起来可以做你想做的事情:
>>> isinstance(re.compile(''), re._pattern_type)
True但这不是一个好主意--根据Python约定,以_开头的名称不是模块的公共API的一部分,也不是向后兼容性保证的一部分。因此,使用type(re.compile(''))是最好的选择-尽管请注意,这也不能保证工作,因为re模块没有提到从re.compile()返回的对象属于任何特定的类。
事实上,即使保证了这一点,最具Pythonic风格和向后和向前兼容的方法将是依赖于接口,而不是类型。换句话说,拥抱鸭子类型和EAFP,这样做:
try:
rex.match(my_string)
except AttributeError:
# rex is not an re
else:
# rex is an re发布于 2017-02-16 23:22:23
下面是你能想到的一些建议:
import re
# global constant
RE_TYPE = re.compile('').__class__
def is_regex(a):
return isinstance(a, RE_TYPE)发布于 2011-06-03 19:03:39
在similar question中,除了您使用的解决方案之外,没有任何其他答案,所以我认为没有更好的方法。
https://stackoverflow.com/questions/6226180
复制相似问题