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):
"""
Args:
obj: Any python object
Returns:
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:
pass
class Otheroldstyle:
pass
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
False
<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
_NO_CLASS=object()
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:
http://stackoverflow.com/questions/2225038/determine-the-type-of-an-object/37876801#37876801