Python isinstance() function is used to check whether the given object is an instance of that class. If the object belongs to the class, it returns True. Otherwise returns False. It also returns true if the class is a subclass.
Syntax:
The syntax of the isinstance()
function is straightforward:
isinstance(object, classinfo)
Parameters:
isinstance()
takes two parameters:
- object: This is the object whose type you want to check.
- classinfo: A class, type, or a tuple of classes and types, against which the object is compared.
Return Value:
The function returns True
if the object is an instance or subclass of a class, or any element of the tuple. Otherwise, it returns False
.
The Basics of isinstance( ) :
At its core, isinstance()
serves the purpose of affirming an object’s type:
num = 3.14
result = isinstance(num, float)
print(result) # Output: True
Here, isinstance()
checks if num
is an instance of float
.
When you pass an object and a class (or a tuple of classes) to isinstance()
, the function checks if the object is derived from the class or one of the classes if you passed a tuple. Here is how it operates:
Direct Instance Check: If you pass a single class as classinfo
, isinstance()
checks whether the given object is an instance of that class.
class Bird:
pass
sparrow = Bird()
result = isinstance(sparrow, Bird)
print(result) # Output: True
Subclass Check: In addition to checking if the object is an instance of the specified class, isinstance()
also returns True
if the object is an instance of a subclass of that class.
class Animal:
pass
class Dog(Animal):
pass
my_dog = Dog()
result = isinstance(my_dog, Animal)
print(result) # Output: True
In this example, my_dog
is an instance of Dog
, which is a subclass of Animal
. Thus, isinstance()
correctly identifies my_dog
as an instance of Animal
.
Tuple of Classes: When classinfo
is a tuple of classes, isinstance()
will return True
if the object is an instance of any of the classes.
class Cat(Animal):
pass
my_pet = Cat()
result = isinstance(my_pet, (Dog, Cat))
print(result) # Output: True
Even though my_pet
is not a Dog
, it is a Cat
, and since Cat
is part of the tuple, isinstance()
returns True
.
Use Cases in Python Code
isinstance()
is commonly used in situations where the behavior of a function needs to be adjusted based on the type of object it is dealing with. For example, a function might need to handle an input parameter differently if it’s a list compared to when it’s a string.
def process(data):
if isinstance(data, list):
# Handle the list case
return "Received a list"
elif isinstance(data, str):
# Handle the string case
return "Received a string"
else:
return "Unknown type"
print(process([1, 2, 3])) # Output: Received a list
print(process("Hello")) # Output: Received a string
Benefits of Using isinstance( )
Using isinstance()
provides the following advantages:
- Safety: By checking an object’s type before operating on it, you can prevent type errors.
- Readability: Code that checks types with
isinstance()
can be easier to understand because it makes type expectations explicit. - Flexibility: Because
isinstance()
respects inheritance, it allows functions to work with a whole hierarchy of types rather than just one. - Polymorphism: It enables a form of polymorphism, allowing a single function to handle different types in different ways.
isinstance( ) vs. type( )
isinstance()
and type()
are both used in Python to check the type of variables, but they serve different purposes and operate in slightly different ways. To understand their differences in detail, we need to examine how they are used, their behavior with subclasses, and the philosophy behind their use in Pythonic code.
type( ) Function
The type()
function is used to get the type of an object. If you compare the result of type()
with a type object, you’re checking for an exact match. Here’s the basic usage:
num = 3.14
if type(num) is float:
print("num is a float")
This checks if num
is exactly a float
. It will not consider subclasses of float
.
isinstance( ) Function
The isinstance()
function checks if an object is an instance of a class or a subclass thereof. Unlike type()
, isinstance()
considers the inheritance hierarchy, making it suitable for checking if an object is of a type that could be used in place of another type. Here’s the basic usage:
num = 3.14
if isinstance(num, float):
print("num is a float or an instance of a subclass of float")
This will return True
if num
is a float
or an instance of a subclass of float
.
Differences in Behavior
- Subclass Sensitivity:
type()
does not consider subclasses. It checks for an object’s type to be exactly the same as the specified type.isinstance()
, on the other hand, does account for subclassing. It’s aware of and respects the object-oriented principle that a subclass should be substitutable for its superclass.
- Tuple of Types:
type()
can only handle a single type and does not accept a tuple of types to check against.isinstance()
can accept a tuple of types and returnTrue
if the object is an instance of any of the types.
- Use in Polymorphism:
- Using
type()
for type checking is less flexible in polymorphic situations where an object’s functionality is more important than its specific type. isinstance()
is the preferred tool in polymorphic contexts. It allows a function to accept objects from a class hierarchy as long as they provide certain functionalities, respecting the “Liskov Substitution Principle.”
- Using
Philosophical Differences
The usage of type()
versus isinstance()
can also reflect different philosophies in code design:
- Checking with
type()
is a way to ensure that an object is exactly a certain type, not a subtype. This is often not necessary and can lead to more brittle code, as it rejects subclasses that would otherwise be perfectly adequate. - Checking with
isinstance()
reflects a more flexible and abstract design, where the concern is whether an object can do what is required (has the methods or attributes needed), not what its specific type is. This aligns more closely with the duck-typing philosophy often espoused in Python: “If it quacks like a duck, it’s a duck.”
When to Use Each
- Use
type()
when: You need to know an object’s exact type. This is less common but can be necessary in cases where strict type identity is required and subclass functionality might lead to unexpected behavior. - Use
isinstance()
when: You are working with inheritance and need to check if an object is an instance of a base type or any derived type. This is more common and is usually the preferred method of type checking when you need to ensure that an object behaves like a certain type.
isinstance( ) and Abstract Base Classes
Abstract Base Classes (ABCs) in Python’s collections.abc
module allow for a more generic way of type checking. isinstance()
can be used with ABCs to check if an object conforms to a particular interface.
from collections.abc import Iterable
# Check if an object is iterable
result = isinstance([], Iterable)
print(result) # Output: True
Conclusion
The isinstance()
function is a powerful component of Python’s type system, providing the capability to perform runtime type checking in a way that accommodates Python’s polymorphic nature. While it may not always be the “Pythonic” way, it serves a critical role in scenarios where type certainty is necessary, particularly in large or complex codebases where type ambiguity can lead to bugs. Understanding when and how to use isinstance()
effectively is an essential skill for Python developers who must balance the language’s dynamic typing with the need for reliability and correctness in their code.