Python isinstance(): Check if an Object Belongs to a Class

The isinstance() function checks if an object is an instance of a specific class or a tuple of classes. It’s useful for type checking, input validation, and ensuring correct function usage.

Example

x = 5
print(isinstance(x, int))  
# Output: True

Since x is an integer, isinstance() returns True.

Syntax

isinstance(object, class_or_tuple)
  • object → The variable to check.
  • class_or_tuple → A class or a tuple of classes to compare against.
  • ReturnsTrue if the object is an instance, else False.

1. Checking Data Types Before Operations

Ensure a variable is of the expected type before using it.

num = "100"

if isinstance(num, int):
    print(num + 10)  
else:
    print("Not a number!")
# Output: Not a number!

This prevents runtime errors.

2. Checking for Multiple Types

Use a tuple of classes to check for multiple types.

value = 3.14

if isinstance(value, (int, float)):
    print("Valid number")
else:
    print("Invalid type")
# Output: Valid number

Works for multiple accepted types.

3. Checking Custom Classes

Works with user-defined classes too.

class Animal:
    pass

class Dog(Animal):
    pass

d = Dog()
print(isinstance(d, Dog))     # Output: True
print(isinstance(d, Animal))  # Output: True (Inheritance works)
print(isinstance(d, int))     # Output: False

Detects inheritance relationships automatically.

4. Using isinstance() for Safe Function Calls

def process(data):
    if isinstance(data, str):
        return data.upper()
    else:
        return "Invalid input"

print(process("hello"))  # Output: HELLO
print(process(123))      # Output: Invalid input

Helps in writing safer functions.

Key Notes

  • Prevents errors by checking types before operations.
  • Works with multiple types using a tuple.
  • Recognizes inheritance when checking object types.
  • Useful for validating function arguments.

By using isinstance(), you can ensure type safety, prevent bugs, and make your code more robust. 🚀

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top