Python: discover the type of an object

This seems a simple enough question:

How can I discover the type of any given Python object?

Suppose Python 2.7 (Python 3 is a different beast on this topic), and try implementing such function:

def discover_type_of_object(obj):  
        obj: Any python object

        the type of input object

When you're done, scroll the page way down...

Now, try the function you've wrote with this case:

class Oldstyle:  

class Otheroldstyle:  

print discover_type_of_object(Oldstyle()) == discover_type_of_object(Otheroldstyle())

print discover_type_of_object(Oldstyle)  

Does the first print statement write True and/or does the second statement raise an exception? If your output is

<type 'classobj'>  

Congratulations, you've done everything right!

If not, you got stuck into the NewStyleVsClassicClasses problem, which makes it quite hard to do something as simple as getting the type of an arbitrary object. This is the code I created:

from types import ClassType  
def get_object_type(obj):  
    obj_type = getattr(obj, "__class__", _NO_CLASS)
    if obj_type is not _NO_CLASS:
        return obj_type
    # AFAIK the only situation where this happens is an old-style class
    obj_type = type(obj)
    if obj_type is not ClassType:
        raise ValueError("Could not determine object '{}' type.".format(obj_type))
    return obj_type

If it weren't that Python 2.7 is in maintenance mode only, I'd probably submit such utility for inclusion in the inspect module.

Originally answered on Stack Overflow:

Alan Franzoni

Read more posts by this author.

Trieste, Italy
comments powered by Disqus