Types
Runtime Type Checks
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
Falseisinstance() accepts subclasses, which is usually what API boundaries want.
Source
print(isinstance(pet, Dog))
print(isinstance(pet, Animal))Output
True
Trueissubclass() checks class relationships rather than individual objects.
Source
print(issubclass(Dog, Animal))Output
TrueNotes
type()is exact;isinstance()follows inheritance.- Runtime checks inspect objects, not static annotations.
- Prefer behavior, protocols, or clear validation over scattered type checks.
See also
- related: Type Hints
- related: Protocols
- related: Casts and Any
- next depth: Abstract Base Classes
Run the complete example
Expected output
Dog
False
True
True
Execution time appears here after you run the example.