Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

re.RegexObject doesn't exist (raises AttributeError)

In my latest series of questions, I asked about fooling around with the internals of argparse. Mostly, I want to change an attribute defined as:

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

Since it is "protected", I would like to check if this attribute exists and if it is a regular expression before I substitute in my own regex. 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"))

This fails with an attribute error because re has no attribute named RegexObject even though it is in the documentation. Why is RegexObject documented but not available? What am I supposed to be using there? I suppose I could say: type(a) is type(b), but that seems ugly...

like image 300
mgilson Avatar asked Jun 14 '12 14:06

mgilson


1 Answers

It's <type '_sre.SRE_Pattern'> but I'd simply use type(re.compile('')).

BTW, it appears that even re developers don't know for sure what the exact type is, as seen here:

_pattern_type = type(sre_compile.compile("", 0))
like image 73
georg Avatar answered Nov 15 '22 07:11

georg