Python type() Method

The type() method either returns the type of the specified object or returns a new type object of the specified dynamic class, based on the specified class name, base classes and class body.

Syntax:

type(object)
type(name, bases, dict)

Parameters:

  1. object: Required. The object whose type is to be returned.
  2. name: Required. A class name.
  3. bases: Required. A tuple that itemizes the base class.
  4. dict: Required. A dictionary which is the namespace containing definitions for the class body.

Return Value:

  1. If object is passed, then it returns the type of object in angular brackets as <class 'name of the class'>.
  2. If name, bases and dict are passed, then it returns a new type object.

The following method returns the type of various objects.

Example: type()
lang = 'Python'
nums = [1,2,3,4]
nums_dict = {'one':1,'two':2,'three':3}

print(type(nums))
print(type(lang))
print(type(nums_dict))
Output
<class 'str'> <br>
<class 'list'><br>
<class 'dict'>

In the above example, an object is passed as a single parameter in the type() function, so it returns the class name of the object e.g. for string, it returns <class 'str'>. Use the isinstance() function to test object's type if you want to consider base classes also.

The type() method can be used to create a new class dynamically instead of using the class statement. For example, the following creates the student class dynamically by passing name, base, and dict paramters to the type() function.

Example: type()
std = type('student', (object,), dict(name='John', age=12))
print(std.name)
print(std.age)
Output
John
12

The type of the new object created using the type() function will be type. The __name__ attribute of the employee class will be employee, a tuple (object,) specifies the base class of the employee class and will assign to the __bases__ attribute. The third parameter dict(name='John', age=12) becomes the body of the class that contains two attributes name and age. This dict will be assigned to the __dict__ attribute.

Example: type()
std = type('student', (object,), dict(name='John', age=12))

print('Type = ', type(std))
print('__name__ = ', std.__name__)
print('__bases__ = ', std.__bases__)
print('__dict__ = ', std.__dict__)
Output
Type = <class 'type'>
name = student
bases = (<class 'object'>,)
dict = mappingproxy({'name': 'bill', 'age': 22, 'module': 'main', 'dict': <attribute 'dict' of 'employee' objects>, 'weakref': <attribute 'weakref' of 'employee' objects>, 'doc': None})

The dir function will returns the following attributes of the dynamic class created using the type() function.

Example:
std = type('student', (object,), dict(name='John', age=12))
dir(std)
Output
['class', 'delattr', 'dict', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'init_subclass', 'le', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook', 'weakref', 'age', 'name']