Determine an object’s type in Python
Use type for exact classes, isinstance for inheritance-aware checks, and issubclass for classes. Check supported operations directly when type is not the requirement.
Use type(obj) to inspect an object's exact class. Use isinstance(obj, SomeClass) when subclasses should also count. Use issubclass(Child, Parent) to compare classes rather than instances.
Inspect the exact class
value = 10
print(type(value)) # <class 'int'>
print(type(value) is int) # True
type(value) is int excludes subclasses. That is appropriate only when you deliberately require the exact built-in class.
Include subclasses with isinstance
print(isinstance(10, int)) # True
print(isinstance(True, int)) # True
class A:
pass
class B(A):
pass
print(isinstance(B(), A)) # True
print(isinstance(2.5, (int, float))) # True
The tuple form accepts any matching type. Python's bool is a subclass of int, so check for Boolean values separately if your application must not treat them as numbers.
Compare classes with issubclass
print(issubclass(B, A)) # True
print(issubclass(A, B)) # False
Pass classes here. Passing an ordinary instance as the first argument raises TypeError.
Check the operation you need
Sometimes a specific class is not the requirement. To consume an iterable, attempt to obtain its iterator:
value = [1, 2, 3]
try:
iterator = iter(value)
except TypeError:
print("This value is not iterable")
else:
for item in iterator:
print(item)
Checking only hasattr(value, "__iter__") is incomplete. Python can also iterate through the sequence protocol implemented by __getitem__. Merely having a named attribute does not prove that the operation works. An iterator obtained successfully can still raise an exception later while producing items.
FAQ
Why does isinstance(True, int) return true? Boolean values belong to an integer subclass. type(value) is bool detects an exact Boolean, or you can handle isinstance(value, bool) before a broader numeric check.
Which should I use: type() or isinstance()? Use inheritance-aware checks when subclasses are valid inputs. Use exact type identity only when that exclusion is part of the contract; consider checking the required operation when concrete type is irrelevant.
How do I check for a string? isinstance(value, str) is clearer than comparing with type(""), and includes string subclasses.
References
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan