Convert a python 'type' object to a string

PythonReflection

Python Problem Overview


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)

Python Solutions


Solution 1 - Python

print type(someObject).__name__

If that doesn't suit you, use this:

print some_instance.__class__.__name__

Example:

class A:
    pass
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.

Solution 2 - Python

>>> class A(object): pass

>>> e = A()
>>> e
<__main__.A object at 0xb6d464ec>
>>> print type(e)
<class '__main__.A'>
>>> print type(e).__name__
A
>>> 

what do you mean by convert into a string? you can define your own repr and str_ methods:

>>> class A(object):
    def __repr__(self):
        return 'hei, i am A or B or whatever'

>>> e = A()
>>> e
hei, i am A or B or whatever
>>> str(e)
hei, i am A or B or whatever

or i dont know..please add explainations ;)

Solution 3 - Python

print("My type is %s" % type(someObject)) # the type in python

or...

print("My type is %s" % type(someObject).__name__) # the object's type (the class you defined)

Solution 4 - Python

In case you want to use str() and a custom str method. This also works for repr.

class TypeProxy:
    def __init__(self, _type):
        self._type = _type

    def __call__(self, *args, **kwargs):
        return self._type(*args, **kwargs)

    def __str__(self):
        return self._type.__name__

    def __repr__(self):
        return "TypeProxy(%s)" % (repr(self._type),)

>>> str(TypeProxy(str))
'str'
>>> str(TypeProxy(type("")))
'str'

Solution 5 - Python

By using the str() function you can do this.

 typeOfOneAsString=str(type(1))  # changes the type to a string type

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRehno LindequeView Question on Stackoverflow
Solution 1 - PythonGabi PurcaruView Answer on Stackoverflow
Solution 2 - PythonAntView Answer on Stackoverflow
Solution 3 - PythonFisherView Answer on Stackoverflow
Solution 4 - PythonkilljoyView Answer on Stackoverflow
Solution 5 - PythonBrian C.View Answer on Stackoverflow