In 2.x, a class object can be be a type
(new-style classes) or a classobj
(classic classes). The type
type is a builtin, but the classobj
type is not. So, how do you get it? That's what the types
module is for.
isinstance(MyClass, (types.TypeType, types.ClassType))
In 3.x, you don't need to worry about classic classes, so:
isinstance(MyClass, type)
Even if you want to compare the types directly, you should never compare any objects by their str
. Compare:
>>> class MyClassicClass:
... pass
>>> str(type(MyClassicClass)) == "<type 'classobj'>"
True
>>> str("<type 'classobj'>") == "<type 'classobj'>"
True
You can almost always just compare objects directly:
>>> type(MyClassicClass) == types.ClassType
True
>>> "<type 'classobj'>" == types.ClassType
False
(And in the incredibly rare cases where you really do need to compare the string representation for some reason, you want the repr
, not the str
.)