Python is a programming language that’s easy to learn but difficult to master. One of the most fundamental concepts in Python is data types.
In this article, we will be discussing the Python type function. This function can take input as an argument, i.e., object, and return its type. The most common use for the function is when you are writing object-oriented code because it helps with debugging, but there are also other uses for the type function in general.
It’s important to know what kind of data you are dealing with so you don’t make errors when running your cod
Table of Contents
Python Type Function: How to use?
Python type function is used to either return the class type of an object or return a new type object in Python. This can be decided by passing a parameter to the type() function.
We can provide two types of arguments in the type function in Python, either a single argument or three arguments at a time.
- Single Argument: when type(object) is passed, the type function returns the specified object’s type.
- Three Arguments: When type(name, bases, dictionary) is used, a new type object is returned in the output
Python Type Function: What is the syntax?
In the following two forms, we can use the type function in Python.
type(object)
type(name, bases, dict)
- Name: class name is converted to name attribute.
- Bases: tuple that is converted to bases attribute.
- Dict: the dictionary which has class body definitions converted to dict attribute.
Example Code # 01:
print(type({}) is dict)
print(type([]) is list)
print(type({}) is list)
print(type([]) is not list)
print(type({}) is tuple)
Output

Example Code # 02:
Following is the use of type(object).
List = [2, 4, 6, 8, 10]
print(type(List))
Dict = {1: 'Welcome', 2: 'CodeLeaks'}
print(type(Dict))
Tuple = ('Learn', 'With', 'Code Leaks')
print(type(Tuple))
Output

Example Code # 03:
Folloiwng is the use of type(name, bases, dict)
Num1 = type('A', (object,), dict(x='Codeleaks', y='Tutorial'))
print(type(Num1))
print(vars(Num1))
class test:
x = 'Codeleaks'
y = 'Tutorial'
Num2= type('B', (test,), dict(x='Codeleaks', y='Tutorial'))
print(type(Num2))
print(vars(Num2))
Output

Conclusion:
The type() function is an excellent tool for debugging your code and writing object-oriented programs. It’s also helpful to know the data type of an input argument or value before using it. I hope this article helped you understand what type() does and how it might be used in specific scenarios.