Types

Runtime Type Checks

type, isinstance, and issubclass inspect runtime relationships.

Runtime type checks inspect real objects while the program is running. They are different from type hints, which mostly guide tools before the program runs.

Use type() when the exact class matters, isinstance() when subclasses should count, and issubclass() when checking class relationships. Most APIs prefer behavior over type checks, but runtime checks are useful at input boundaries.

Do not turn every function into a wall of isinstance() calls. If the code only needs an object that can perform an operation, duck typing or a protocol may be clearer.

type() reports the exact runtime class. A Dog instance is not exactly an Animal instance.

Source

class Animal:
    pass

class Dog(Animal):
    pass

pet = Dog()
print(type(pet).__name__)
print(type(pet) is Animal)

Output

Dog
False
isinstance and issubclass ask the runtime; the answer is a bool, not a static type refinement.

isinstance() accepts subclasses, which is usually what API boundaries want.

Source

print(isinstance(pet, Dog))
print(isinstance(pet, Animal))

Output

True
True

issubclass() checks class relationships rather than individual objects.

Source

print(issubclass(Dog, Animal))

Output

True

Notes

See also

Run the complete example

Example code

Expected output

Dog
False
True
True

Execution time appears here after you run the example.