For working professionals
For fresh graduates
More
13. Print In Python
15. Python for Loop
19. Break in Python
23. Float in Python
25. List in Python
27. Tuples in Python
29. Set in Python
53. Python Modules
57. Python Packages
59. Class in Python
61. Object in Python
73. JSON Python
79. Python Threading
84. Map in Python
85. Filter in Python
86. Eval in Python
96. Sort in Python
101. Datetime Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
107. Append in Python
110. Assert in Python
113. Bool in Python
115. chr in Python
118. Count in python
119. Counter in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
125. Format in Python
131. Index in Python
132. Interface in Python
134. Isalpha in Python
136. Iterator in Python
137. Join in Python
140. Literals in Python
141. Matplotlib
144. Modulus in Python
147. OpenCV Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
156. Python Arrays
158. Python Frameworks
160. Python IDE
164. Python PIP
165. Python Seaborn
166. Python Slicing
168. Queue in Python
169. Replace in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
179. Split in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
195. What is Pygame
197. XOR in Python
198. Yield in Python
199. Zip in Python
The type function in Python helps you determine the type of an object at runtime. Whether you are working with strings, integers, or user-defined classes, this function quickly tells you what kind of object you are dealing with. It also plays a powerful role in dynamic class creation, allowing advanced use cases in Python programming.
In this article, we will explore everything about the type() function, starting from its basic syntax to advanced applications like creating classes dynamically. You will also learn best practices and practical examples to use this function effectively in your real-world Python code.
Pursue software engineering & development courses from top universities!
The type function in Python is a built-in utility that helps identify the data type of any object. Whether you're working with strings, lists, numbers, or custom classes, this function quickly reveals what kind of object you are handling. It plays a vital role in debugging and dynamic class creation.
In its simplest form, type() takes one argument and returns the type of that object. But it can also take three arguments to dynamically define a new class. This dual functionality makes it both simple and powerful.
Unlock a career at Big Four with the following courses:
The type function in Python supports two types of syntax, depending on how you intend to use it. You can either pass a single argument to get the type of an object or pass three arguments to create a new class dynamically.
Let’s break down both forms of type():
This version is most commonly used to find the type of an object.
type(object)
Let’s look at a basic code example:
# Example: Single argument with type()
number = 10 # Integer value
print(type(number)) # Output: <class 'int'>
text = "Python" # String value
print(type(text)) # Output: <class 'str'>
Output:
<class 'int'>
<class 'str'>
Explanation:
When passed three arguments, the type() function acts as a dynamic class generator.
type(class_name, base_classes, attributes_dict)
Now, let’s see an example where we create a new class using this form:
# Create a new class 'Student' with no parent class and one method
Student = type(
'Student', # Class name
(), # No base class
{'speak': lambda self: "Study!"} # Class body (dictionary)
)
# Create an object of the dynamically created class
a = Student()
print(a.speak())
Output:
Study!
Explanation:
Must Explore: Argument vs Parameter: Difference Between Argument and Parameter [With Example]
Let’s walk through real examples of how the type function in Python works. We’ll start from basic use cases and gradually move toward more advanced scenarios like creating classes and accessing metadata.
You can use the type() function to quickly check the data type of any object. This is useful when debugging or validating input values.
num = 42 # Integer
pi = 3.14 # Float
word = "Python" # String
values = [1, 2, 3] # List
# Print the type of each object
print(type(num))
print(type(pi))
print(type(word))
print(type(values))
Output:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>
Explanation:
You can apply type() inside an if or elif block to execute code based on data type.
data = [10, 20, 30] # A list object
# Use type() to make decisions based on data type
if type(data) == list:
print("The object is a list.")
elif type(data) == dict:
print("The object is a dictionary.")
else:
print("Unknown data type.")
Output:
The object is a list.
Explanation:
Must explore the Precedence of Operators in Python article!
Using type() with == works, but isinstance() is more robust, especially for subclasses. Here’s how both work.
name = "Python" # A string value
# Check type using type()
print(type(name) == str)
# Check type using isinstance()
print(isinstance(name, str))
Output:
True
True
Explanation:
The type() function can create a new class on the fly using three parameters: class name, base classes, and attributes.
# Dynamically create a class 'Car' with a method
Car = type(
'Car', # Name of the class
(), # No base classes
{'start': lambda self: "Engine on"} # Method in dict format
)
my_car = Car()
print(my_car.start())
Output:
Engine on
Explanation:
Let’s build a more complete class using the same type() approach, including properties and methods.
# Define the class structure in a dictionary
Movie = type(
'Movie',
(),
{
'__init__': lambda self, title: setattr(self, 'title', title),
'get_title': lambda self: self.title
}
)
# Create an object of the Movie class
film = Movie("Inception")
print(film.get_title())
Output:
Inception
Explanation:
You can extract metadata like class name and base classes using type() and class attributes such as __name__, __bases__, and __dict__.
class Book:
pass
# Use type() and built-in attributes to get metadata
print(type(Book))
print(Book.__name__)
print(Book.__bases__)
print(Book.__dict__['__module__'])
Output:
<class 'type'>
Book
(<class 'object'>,)
__main__
Explanation:
The type function in Python is not just limited to checking data types. It plays a crucial role in dynamic programming, debugging, unit testing, and even class creation. Let’s look at some real-world scenarios where type() becomes especially useful.
Sometimes, you work with data fetched from APIs, crawlers, or user input. In such cases, you can use type() to avoid unexpected runtime errors.
Here’s a practical example:
# Example: Use type() to debug unknown object types
from types import GeneratorType
def get_data():
yield "Python"
data = get_data()
# Before using string methods, verify the object type
if type(data) == GeneratorType:
print("Cannot apply string methods on a generator.")
else:
print(data.lower())
Output:
Cannot apply string methods on a generator.
Explanation:
Also read about the Identity Operator in Python to improve your coding skills!
With three arguments, type() can dynamically generate classes. This is helpful when you want to define behavior at runtime.
# Example: Dynamically create a class with methods and attributes
# Define the class using type()
User = type(
'User',
(),
{
'role': 'admin',
'get_role': lambda self: self.role
}
)
person = User()
print(person.get_role())
Output:
admin
Explanation:
In automated testing, you often verify if a function returns the correct type. Using type() ensures your logic behaves as expected.
# Example: Validate return type in a test
def square(x):
return x * x
result = square(4)
# Check the return type
if type(result) == int:
print("Test Passed: Output is of type int.")
else:
print("Test Failed: Incorrect type.")
Output:
Test Passed: Output is of type int.
Explanation:
In data pipelines, type() can help you apply operations based on the type of data received. This improves code robustness.
# Example: Handle different data types dynamically
def process(data):
if type(data) == list:
return [item * 2 for item in data]
elif type(data) == int:
return data * 2
else:
return None
print(process(5))
print(process([1, 2, 3]))
Output:
10
[2, 4, 6]
Explanation:
In some database frameworks like SQLAlchemy, developers use type() to register model classes dynamically. Though advanced, this shows how type() powers dynamic class creation for real-world applications.
The type() function is powerful and versatile, but to get the most value from it, you need to follow some standard practices. Below are the key recommendations for using the type function in Python effectively and safely.
The type function in Python is more than just a basic utility. It acts as a powerful tool that helps you identify object types, debug unexpected behavior, and dynamically create classes. Whether you're working with simple variables or developing complex metaprogramming logic, type() ensures better control and understanding of your data structures.
As Python continues to evolve, mastering built-in functions like type() will make your code more predictable, readable, and adaptable to dynamic requirements. It's a small function with massive utility when used the right way.
The type function in Python is mainly used to determine the data type of an object at runtime. It is useful for debugging, condition checking, and dynamic class creation. It helps developers write flexible and error-resistant code.
Yes, the type() function works seamlessly with custom classes. It returns the class type of the object created from a user-defined class. This helps in verifying object types while building larger, modular applications or frameworks.
The type() function checks for an exact type match, while isinstance() also returns True for objects that inherit from a class. For example, subclasses pass the isinstance() test but not the type() test.
When passed a single argument, the type function in Python returns the type of the given object. It identifies whether the object is a string, integer, list, dictionary, or any custom or built-in class instance.
With three parameters - name, bases, and dict, the type() function dynamically creates a new class. This advanced use case is commonly applied in metaprogramming, dynamic module creation, or working with frameworks that generate classes at runtime.
Using the type function in Python is acceptable for quick checks and debugging. However, in many cases, it is better to use isinstance() for type comparison and duck typing for flexibility and Pythonic code style.
Yes, the type() function can support runtime error handling. For example, you can verify an object’s type before performing operations that depend on specific methods, such as string or numeric operations. This prevents unexpected attribute errors.
No, the type() function returns the actual type object, not a string. For example, type(5) returns <class 'int'>, which is an object of Python's built-in type class, not just the word "int".
Absolutely. One of the most advanced uses of the type function in Python is in metaprogramming. It allows developers to generate new classes at runtime, modify existing ones, and even customize object behaviors dynamically.
You cannot pass multiple arguments to type() for checking the type of multiple objects. Instead, you should loop through a collection and call type() on each item individually to get their respective data types.
Yes, the type function in Python is often used in unit testing to validate return types from functions. It helps ensure that a function outputs the correct data type, which is crucial in automated testing environments.
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Author|900 articles published
Previous
Next
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.