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?

6
  • 3
    did you do import _sre? What surprises you about the NameError? Commented Jan 18, 2011 at 23:13
  • @SilentGhost: _sre is an internal module, and does not reveal SRE_Pattern to the outside. Commented Jan 18, 2011 at 23:25
  • @poke: you wouldn't know it if you're not importing _sre Commented Jan 18, 2011 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. Commented Jan 18, 2011 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. Commented Jan 19, 2011 at 0:18

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+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..
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.