"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Choose Between Python's `type()` and `isinstance()` for Object Type Checking?

How to Choose Between Python's `type()` and `isinstance()` for Object Type Checking?

Published on 2024-12-23
Browse:507

How to Choose Between Python's `type()` and `isinstance()` for Object Type Checking?

How to Determine the Type of an Object

Determining the type of an object is crucial for ensuring data consistency and performing operations accordingly. Python provides two built-in functions for this purpose: type() and isinstance().

Using type()

The type() function returns the exact type of an object. For example:

>>> type([]) is list
True
>>> type({}) is dict
True
>>> type('') is str
True
>>> type(0) is int
True

Using isinstance()

The isinstance() function checks whether an object is an instance of a particular type, including inherited types. Unlike type(), it supports type inheritance.

>>> isinstance(b, Test1)
True
>>> isinstance(b, Test2)
True
>>> isinstance(a, Test1)
True
>>> isinstance(a, Test2)
False
>>> isinstance([], list)
True
>>> isinstance({}, dict)
True

Choosing Between type() and isinstance()

Generally, isinstance() is preferred for checking object types as it takes derived types into consideration. Type() is more appropriate if you need the exact type object for specific reasons. Here's an example where you might use isinstance():

def print_object_type(obj):
  if isinstance(obj, int):
    print("Integer")
  elif isinstance(obj, float):
    print("Float")
  elif isinstance(obj, str):
    print("String")
  else:
    print("Unknown type")
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3