Rehno Lindeque Rehno Lindeque - 10 months ago 54
Python Question

Convert a python 'type' object to a string

I'm wondering how to convert a python 'type' object into a string using python's reflective capabilities.

For example, I'd like to print the type of an object

print "My type is " + type(someObject) # (which obviously doesn't work like this)

EDIT: Btw, thanks guys, I was just looking for plain printing of types for console output purposes, nothing fancy. Gabi's
works just fine :)

Answer Source
print type(someObject).__name__

If that doesn't suit you, use this:

print some_instance.__class__.__name__


class A:
print type(A())
# prints <type 'instance'>
print A().__class__.__name__
# prints A

Also, it seems there are differences with type() when using new-style classes vs old-style (that is, inheritance from object). For a new-style class, type(someObject).__name__ returns the name, and for old-style classes it returns instance.