Note
Python - type() - Determine the type of an object
Overview of the Python type() Function: Determine the Type of an Object
The type(object) function is a built-in Python function that returns the type of given object.
It is useful when you want to check the class of an object, whether it is a built-in data type or a custom class you've
created.
Using type() can be helpful when you want to determine the type of an object while debugging or understanding unfamiliar code.
But remember that the isinstance() function might be a better fit for such checks.
As a little side note, it is also worth noting that type() function may be used to create new classes in a very quick way.
The syntax for that looks like that - type(name, bases, dict) but I won't cover it here since it is not
a popular approach in Python programming.
Take a look at the examples below:
Using type() with Built-In Types
number = 42
text = "devcuriosity"
my_list = [1, 2, 3]
print(type(number)) # <class 'int'>
print(type(text)) # <class 'str'>
print(type(my_list)) # <class 'list'>
Output:
<class 'int'>
<class 'str'>
<class 'list'>
Using type() with Custom Classes
class Animal:
pass
class Dog(Animal):
pass
animal = Animal()
dog = Dog()
print(type(animal)) # <class '__main__.Animal'>
print(type(dog)) # <class '__main__.Dog'>
Output:
<class '__main__.Animal'>
<class '__main__.Dog'>
Key Difference between type() and isinstance()
While type() provides the exact type of an object, it does not consider class hierarchies.
If you need to check if an object is an instance of a class or its subclasses, use isinstance() instead.
To summarize, the type() function is a useful tool for determining the type of an object in Python.
The type() function might be useful while debugging your code but remember to also take a look at the
isinstance() function because it might be a better fit for your use case.
Key Points to Remember About the type() Function
-
Precision:
type()provides the exact type of an object but does not account for subclass relationships, for that option refer toisinstance(). -
For Debugging: A handy tool for analyzing objects and understanding unfamiliar code.
-
Class Creation: Advanced use cases of
type()include creating new classes dynamically.
I hope you found this helpful! If you have any feedback, questions or requests, please reach out to me through Contact page!