0

I'm using isinstance to check argument types, but I can't find the class name of a regex pattern object:

>>> import re
>>> x = re.compile('test')
>>> x.__class__.__name__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: __class__

...

>>> type(x)
<type '_sre.SRE_Pattern'>
>>> isinstance(x, _sre.SRE_Pattern)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '_sre' is not defined
>>>
>>>
>>> isinstance(x, '_sre.SRE_Pattern')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
>>> 

Any ideas?

zumjinger
  • 41
  • 1
  • 5
  • 3
    did you do `import _sre`? What surprises you about the `NameError`? – SilentGhost Jan 18 '11 at 23:13
  • @SilentGhost: `_sre` is an internal module, and does not reveal `SRE_Pattern` to the outside. – poke Jan 18 '11 at 23:25
  • @poke: you wouldn't know it if you're not importing `_sre` – SilentGhost Jan 18 '11 at 23:39
  • @SilentGhost: It didn't -- and still doesn't -- make much sense that an object wouldn't know itself or that it'd be in an outside module. – zumjinger Jan 18 '11 at 23:46
  • @zum: `x.__class__.__name__` works for me just fine in py3k. I'm not sure I'm following your *object know itself* charge. – SilentGhost Jan 19 '11 at 00:18
  • @SilentGhost: x.__class__.__name__ doesn't work at 2.6. By "object, know thyself" I mean that in an OO language like Python I'd expect to be able to see an objects class and inheritance tree at the drop of a hat. It's also a matter of consistency, the x.__class__.__name__ chain works on all the built-in classes (str etc.). – zumjinger Jan 19 '11 at 06:50

2 Answers2

4

You could do this:

import re

pattern_type = type(re.compile("foo"))

if isinstance(your_object, pattern_type):
   print "It's a pattern object!"

The idiomatic way would be to try to use it as a pattern object, and then handle the resulting exception if it is not.

mthurlin
  • 26,247
  • 4
  • 39
  • 46
  • +1, that should be the safest way to do it.. Everything else will be dangerous given that the actual regexp implementation is inside the C core.. – poke Jan 18 '11 at 23:24
0
In : x = re.compile('test')
In : isinstance(x, type(x))
Out: True

In [14]: type(type(x))
Out[14]: <type 'type'>

I think it relates to the type/object subtilities and to the re module implemetation. You can read a nice article here.

eolo999
  • 863
  • 6
  • 13