The type() function is used to check the type/class of the object passed in as an argument. It is also used with three arguments to create a new type as we will see later.

Syntax:
type(obj)
copy
obj The object whose type is to be checked.
ExampleEdit & Run
print( type("Hello") )

print( type(9) )

print( type(9.5) )

print( type([1, 2, 3]) )

print( type(type) )

print( type(print) )

import math
print( type(math) )
copy
Output:
<class 'str'> <class 'int'> <class 'float'> <class 'list'> <class 'type'> <class 'builtin_function_or_method'> <class 'module'> [Finished in 0.010592330247163773s]

We can use the type() function to check whether two values are of the same type. for Example:

ExampleEdit & Run
print(  type(9) == type(9.5) )

print( type("Hello") == type("World") )
copy
Output:
False True [Finished in 0.009983452968299389s]

The function is also used to check explicitly whether a given value is an instance of a particular class.

ExampleEdit & Run
print( type(5) == int )

print( type("Hello") == str )

print( type([1, 2]) == set )

print( type([1, 2]) == list )
copy
Output:
True True False True [Finished in 0.01018134830519557s]

The type() Function for creating a new type

The type() function can be used with three arguments in an entirely different context from the one described above. With three arguments, the function is used to create a class dynamically. The syntax for creating a class using type() function is as follows:

type(name, bases, class_dict, **kwargs)
copy
name This is a string that represents the name of the class you want to create.
bases This argument represents the base classes or parent classes that the new class inherits from. It can be a single base class or a tuple of base classes. If the class has no base classes, you can pass an empty tuple ().
class_dict This argument represents a dictionary that contains the attributes and methods of the class. The dictionary maps attribute names (as strings) to their corresponding values (e.g., variables, functions).
**kwargs Any other additional arbitrary keyword arguments.
Parameters:

The function returns the newly created class.

ExampleEdit & Run
#Define the constructor for the function.
def init(self, name, age, gender):
    self.name = name
    self.age = age
    self.gender = gender

Person = type("Person", (), {'__init__':init ,'__str__':lambda self: "{}, {} - {}".format(self.name, self.age, self.gender)})
p = Person('John', 30, 'Male')
print(p)
copy
Output:
John, 30 - Male [Finished in 0.00997375464066863s]