Can't get an object's class name in Python
-
12-10-2019 - |
Question
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.
OTHER TIPS
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow