Python isinstance()
Understanding isinstance()
in Python
What is the isinstance()
function?
The isinstance()
function is a built-in Python function used to check if an object is an instance of a specific class or type. It takes two arguments: the object to check and the class or type to compare against. If the object is an instance of the specified class or type, isinstance()
returns True
; otherwise, it returns False
.
Why is type checking important in Python?
Type checking is essential in Python to ensure code reliability and readability. Python's dynamic typing allows variables to hold any type, which can lead to errors if incorrect types are used. Type checking helps identify these errors early and prevents bugs. Python introduced type hints in version 3.5 to improve type checking, allowing for static analysis and better code quality.
Syntax of isinstance()
The syntax for isinstance()
is:
isinstance(object, class_or_type)
object
: The object you want to check.class_or_type
: The class or type to check against. This can also be a tuple of classes or types.
Example Usage
To check if an object rect
is an instance of the Rectangle
class:
is_instance = isinstance(rect, Rectangle)
To check if an object is an instance of any class in a tuple:
is_instance = isinstance(obj, (Class1, Class2, Class3))
Using isinstance()
with Built-in Types
You can use isinstance()
to check if a variable is of a built-in type such as int
, float
, str
, list
, tuple
, or dict
. For example:
is_integer = isinstance(variable, int)
This function is useful for ensuring that functions receive the correct type of arguments, avoiding errors.
Using isinstance()
with Custom Classes
To use isinstance()
with custom classes:
- Define your custom class.
- Use
isinstance()
to check if an object is an instance of this class.
Example:
Using isinstance()
with a Tuple of Types
You can pass a tuple of types to isinstance()
to check if an object is an instance of any type in the tuple:
is_instance = isinstance(variable, (int, float))
Working with Parent Classes and Subclasses
Checking for Parent Class
To check if an object is an instance of a parent class:
Checking for Subclasses
To check if an object is an instance of a subclass:
is_subclass_instance = isinstance(dog, (Animal, Dog))
Type Checking within Functions
You can use isinstance()
within functions to ensure the correct type of arguments:
Type Checking within Class Definitions
Different methods for type checking include isinstance()
, type()
, and hasattr()
. Choose the method based on your needs:
- Use
isinstance()
for inheritance checks. - Use
type()
for exact type checks. - Use
hasattr()
to check if an object has a specific attribute.