Search code examples
pythonclassobjecttypesisinstance

Can't get an object's class name in Python


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?


Solution

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