Python type() Function



The Python type() function is a built-in function that returns the type of specified object and is commonly used for debugging purposes. The two main use cases of the type() function are as follows −

  • When we pass a single argument to this function, it returns the type of the given object.

  • When three arguments are passed, it allows for the dynamic creation of a new type object.

In the next few sections, we will learn about this function in more detail.

Syntax

Following is the syntax of the Python type() function −

<
type(object, bases, dict)
or,
type(object)

Parameters

The Python type() function accepts two parameters −

  • object − It represents an object such as a list, string, or any other iterable.

  • bases − It is an optional parameter that specifies a base class.

  • dict − It is also an optional parameter. It represents a dictionary that stores the namespace.

Return Value

The Python type() function returns the type of a given object. If we pass three arguments, it will return a new type object.

Examples

In this section, we will see some examples of type() function −

Example 1

The following example shows the basic usage of Python type() function. In the code below, we are displaying the classes for the most used Python data types.

var1 = 5
var2 = 5.2
var3 = 'hello'
var4 = [1,4,7]
var5 = {'Day1':'Sun','Day2':"Mon",'Day3':'Tue'}
var6 = ('Sky','Blue','Vast')
print(type(var1))
print(type(var2))
print(type(var3))
print(type(var4))
print(type(var5))
print(type(var6))

Following is an output of the above code −

<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>
<class 'dict'>
<class 'tuple'>

Example 2

The class named "type" is a superclass, from which all other classes are derived. The type object is also an instance of this class. Therefore, applying type() function to the Python classes will return "class type" as a result.

print("Displaying the type of Python classes:")
print("Type of int class is", type(int))
print("Type of dict class is", type(dict))
print("Type of list class is", type(list))
print("Type of type class is", type(type))

Output of the above code is as follows −

Displaying the type of Python classes:
Type of int class is <class 'type'>
Type of dict class is <class 'type'>
Type of list class is <class 'type'>
Type of type class is <class 'type'>

Example 3

If we pass three arguments to the type() function, it will create a new type object. In the code below, we have created "Tutorialspoint" as a main class, an object as a base and a dictionary with two keys and values.

Object = type("Tutorialspoint", (object, ), dict(loc="Hyderabad", rank=1))
print(type(Object))
print(Object)

Following is the output of the above Python code −

<class 'type'>
<class '__main__.Tutorialspoint'>
python_built_in_functions.htm
Advertisements