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:

  1. Define your custom class.
  2. Use isinstance() to check if an object is an instance of this class.

Example:

class MyClass:
    pass

obj = MyClass()
is_instance = isinstance(obj, MyClass)

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:

class Animal:
    pass

class Dog(Animal):
    pass

dog = Dog()
is_instance = isinstance(dog, Animal)  # Returns True

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:

def square(num):
    if not isinstance(num, int):
        return "Error: Input must be an integer"
    return num ** 2

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.

Example

class Example:
    def __init__(self, value):
        if not isinstance(value, int):
            raise ValueError("Value must be an integer")
        self.value = value

Create a free account to access the full topic

“It has all the necessary theory, lots of practice, and projects of different levels. I haven't skipped any of the 3000+ coding exercises.”
Andrei Maftei
Hyperskill Graduate