How to Check Data Type in Python (type vs isinstance)
Learn how to check data types in Python. Understand when to use type() vs isinstance(), handle custom classes, and write safe type check validations.
Explanation
Python is a dynamically typed language, meaning that variables can hold values of any data type and their type can change during execution. While this flexibility speeds up initial development, it also requires you to verify variable types at runtime before running type-specific operations, such as performing arithmetic on integers or calling string methods.
To check the data type of an object, Python provides two primary functions: `type()` and `isinstance()`. The `type(obj)` function returns the precise class type of the object. While you can use `type(obj) == int` to verify if a number is an integer, this method is generally discouraged because it does not support inheritance structures (a subclass of an integer would evaluate to `False`).
The recommended, pythonic way to check types is `isinstance(obj, class_info)`. This function checks if an object is an instance of the specified class or any subclass inherited from it. It also supports checking against a tuple of classes (e.g., `isinstance(value, (int, float))`), making validation code highly flexible and robust.
Step-by-Step Implementation
- 1
Use isinstance(variable, type_name) for general type checking (conforming to inheritance).
- 2
Pass a tuple of types like isinstance(variable, (int, float)) to check against multiple classes.
- 3
Use type(variable) is type_name only when you must guarantee the exact class match, ignoring subclasses.
Code Example
This script demonstrates checking variable types using both type() and isinstance(), showing the differences in inheritance.
value_int = 42
value_str = "hello"
# 1. Checking type using isinstance() (Recommended)
is_number = isinstance(value_int, int)
print(f"Is {value_int} an int? {is_number}")
# Checking against multiple possible types
is_num_or_str = isinstance(value_str, (int, float, str))
print(f"Is '{value_str}' int, float, or str? {is_num_or_str}")
# 2. Checking type using type() (For exact class matches)
print(f"Exact type of value_int: {type(value_int).__name__}")
print("Is value_int exactly an int?", type(value_int) is int)
# 3. Inheritance difference
class CustomList(list):
pass
my_list = CustomList([1, 2, 3])
print("\nInheritance testing:")
print("isinstance(my_list, list):", isinstance(my_list, list))
print("type(my_list) is list:", type(my_list) is list)Is 42 an int? True
Is 'hello' int, float, or str? True
Exact type of value_int: int
Is value_int exactly an int? True
Inheritance testing:
isinstance(my_list, list): True
type(my_list) is list: FalseFrequently Asked Questions
Why is isinstance() preferred over type()?
isinstance() supports object inheritance and polymorphism. If you subclass a built-in type, isinstance() will correctly recognize it as an instance of the parent class, whereas type() will evaluate to False.
How can I check if an object is callable (like a function)?
Use the built-in callable() function, which returns True if the object can be invoked like a function.
Related How-To Guides
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Type Hints
Learn how to write type hints in Python. Improve code quality, enable autocompletion, and leverage mypy for static code analysis.
Python Type Conversions
Learn implicit and explicit type conversions in Python. Convert between strings, integers, floats, lists, sets, and dictionaries.
Python vs TypeScript: Dynamic Scripting vs Type-Safe Web
Compare Python and TypeScript. Learn about structural type systems, decorator metadata, compiler checks, web runtimes, and developer tooling.