re.RegexObject不存在(引发AttributeError)

时间:2012-06-14 14:04:11

标签: python regex monkeypatching

在我最近的一系列问题中,我问到了argparse的内部错误。大多数情况下,我想更改定义为:

的属性
class FooClass(object):
   def __init__(self):
      self._this_is_a_re=re.compile("foo")

由于它是“受保护的”,我想在我用自己的正则表达式替换之前检查这个属性是否存在以及它是否是正则表达式。 e.g:

import re
myFoo=FooClass()
attr='_this_is_a_re'
if(hasattr(myFoo,attr) and isinstance(getattr(myFoo,attr),re.RegexObject):
   setattr(myFoo,attr,re.compile("bar"))

这会因属性错误而失败,因为即使它位于documentation中,re也没有名为RegexObject的属性。为什么RegexObject已记录但不可用?我应该在那里使用什么?我想我可以说:type(a) is type(b),但这看起来很难看......

1 个答案:

答案 0 :(得分:5)

这是<type '_sre.SRE_Pattern'>,但我只是使用type(re.compile(''))

顺便说一下,即使是re开发人员也不确定具体类型是什么,如here所示:

_pattern_type = type(sre_compile.compile("", 0))