isinstance() / issubclass() / type()
| Since: | Python 2(2000) |
|---|
isinstance() checks whether an object is an instance of a specified type (or a subclass of it). issubclass() checks whether a class is a subclass of another class, and type() returns the type of an object. Use isinstance() for type checking whenever possible; strict type comparison with type() is not recommended because it does not account for subclasses.
Syntax
# Check type (including subclasses) isinstance(object, classinfo) # Check class inheritance relationship issubclass(class, classinfo) # Get type (or dynamically create a class) type(object) type(name, bases, dict)
Function List
| Function | Description |
|---|---|
| isinstance(obj, type) | Returns True if obj is an instance of type, including instances of subclasses. |
| isinstance(obj, (t1, t2)) | Returns True if obj matches any one of the given types. |
| issubclass(cls, parent) | Returns True if cls is a subclass of parent (a class is also considered a subclass of itself). |
| type(obj) | Returns the type (class object) of obj. |
| type(name, bases, dict) | Dynamically creates and returns a new class. |
Sample Code
sample_isinstance_type.py
# isinstance: basic type checking
print(isinstance(42, int)) # True
print(isinstance(3.14, float)) # True
print(isinstance('hello', str)) # True
print(isinstance([1, 2], list)) # True
# isinstance: check against multiple types using a tuple
def add(a, b):
if not isinstance(a, (int, float)):
raise TypeError(f"Expected a number, but got {type(a).__name__}")
return a + b
print(add(1, 2)) # 3
print(add(1.5, 2.5)) # 4.0
# isinstance: includes subclasses (difference from type())
class Animal:
pass
class Dog(Animal):
pass
d = Dog()
print(isinstance(d, Dog)) # True
print(isinstance(d, Animal)) # True (Dog is a subclass of Animal)
print(type(d) == Animal) # False (strict type comparison excludes subclasses)
print(type(d) == Dog) # True
# issubclass: check class inheritance
print(issubclass(Dog, Animal)) # True
print(issubclass(Animal, Dog)) # False
print(issubclass(Dog, Dog)) # True (a class is considered a subclass of itself)
print(issubclass(bool, int)) # True (bool is a subclass of int)
# type: get the type of an object
print(type(42)) # <class 'int'>
print(type('hello')) # <class 'str'>
print(type(42).__name__) # 'int'
# type: dynamic class creation (advanced usage)
MyClass = type('MyClass', (object,), {'x': 10, 'greet': lambda self: 'Hello'})
obj = MyClass()
print(obj.x) # 10
print(obj.greet()) # Hello
python3 isinstance_type.py True True True True 3 4.0 True True False True True False True True <class 'int'> <class 'str'> int 10 Hello
Notes
Because isinstance() respects inheritance, it is well-suited for polymorphic code. For example, since bool is a subclass of int, isinstance(True, int) returns True.
Python 3.10 and later support union type syntax (int | str) as an alternative to passing a tuple. Combined with type hints, this allows you to write more type-safe code.
Passing three arguments to type() dynamically creates a class. This is an advanced metaprogramming technique, but in everyday code it is recommended to define classes with the class keyword for better readability.
If you find any errors or copyright issues, please contact us.