re.RegexObject不存在(引发AttributeError)

mgi*_*son 4 python regex monkeypatching

在我最近的一系列问题中,我问到了与内部人士的混淆argparse.大多数情况下,我想更改定义为的属性:

class FooClass(object):
   def __init__(self):
      self._this_is_a_re=re.compile("foo")
Run Code Online (Sandbox Code Playgroud)

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

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"))
Run Code Online (Sandbox Code Playgroud)

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

geo*_*org 5

<type '_sre.SRE_Pattern'>只是我用的type(re.compile('')).

顺便说一句,似乎即使re开发商不肯定知道确切的类型是什么,因为看到这里:

_pattern_type = type(sre_compile.compile("", 0))
Run Code Online (Sandbox Code Playgroud)