Python type()


Python - type() Built-in Function

In Python, the datatype of variable is not declared, but inferred from the value stored in it. So, if you would like to know the type of data that is stored in a variable, you can use type() function.

Python type() built-in function is used to get the data type of given argument. It can also be used to create a new type dynamically.

In this tutorial, you will learn how to use type() function to get the type of a given object, or create a new type dynamically.

Syntax of type()

The syntax of type() function is

type(object)

type() returns the type of object.

Examples

1. Type of an integer argument

In this example, we will assign an integer to a variable, and pass this object to type() function. type() function should return that the object is of type int.

Python Program

x = 69
print(type(x))

Output

<class 'int'>

2. Create a class dynamically

In this example, we will create a class named MyClass with an attribute x dynamically using type() function.

Python Program

MyClass = type('MyClass', (object,), {'x': 42})

obj = MyClass()
print(obj.x)

Output

42

3. Get the type for built-in type values

In this example, we will try to find the type of values stored in variables for all builtin datatypes.

In the following program, we will take a variable named x, assign it a value, find its type, reassign another value, find its, and continue the process for all builtin datatypes.

Python Program

x = 'Hello World'
print(type(x))
x = 69
print(type(x))
x = 3.14159
print(type(x))
x = 3 + 2j
print(type(x))
x = ['apple', 'banana', 'mango']
print(type(x))
x = ('apple', 'banana', 'mango')
print(type(x))
x = range(6)
print(type(x))
x = {'a' : 65, 'b' : 66}
print(type(x))
x = {'apple', 'banana', 'mango'}
print(type(x))
x = frozenset({'apple', 'banana', 'mango'})
print(type(x))
x = True
print(type(x))
x = b'mango juice'
print(type(x))
x = bytearray(5)
print(type(x))
x = memoryview(bytes(5))
print(type(x))

Output

<class 'str'>
<class 'int'>
<class 'float'>
<class 'complex'>
<class 'list'>
<class 'tuple'>
<class 'range'>
<class 'dict'>
<class 'set'>
<class 'frozenset'>
<class 'bool'>
<class 'bytes'>
<class 'bytearray'>
<class 'memoryview'>

4. Get type for user defined objects

In this example, we will create a new type using class, and find the class objects type using type() function.

Python Program

class Fruit:
    def __init__(self, name):
        self.name = name

x = Fruit('banana')
print(type(x))

Output

<class '__main__.Fruit'>

5. Type of type object

This is deep. We will try to find the type of object returned by type() function using type() function.

Python Program

x = 12
print(type(type(x)))

Output

<class 'type'>

The type of type object is type.

Related Tutorials

Summary

In this tutorial of Python Examples, we learned how to use type() function to find the type of object passed to it.