Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get type of object as simple class name [duplicate]

How do I find out the name of the class used to create an instance of an object in Python?

I'm not sure if I should use the inspect module or parse the __class__ attribute.

like image 613
Dan Avatar asked Feb 02 '26 00:02

Dan


2 Answers

Have you tried the __name__ attribute of the class? ie type(x).__name__ will give you the name of the class, which I think is what you want.

>>> import itertools
>>> x = itertools.count(0)
>>> type(x).__name__
'count'

If you're still using Python 2, note that the above method works with new-style classes only (in Python 3+ all classes are "new-style" classes). Your code might use some old-style classes. The following works for both:

x.__class__.__name__
like image 70
sykora Avatar answered Feb 04 '26 14:02

sykora


Do you want the name of the class as a string?

instance.__class__.__name__
like image 43
mthurlin Avatar answered Feb 04 '26 13:02

mthurlin