Python type()

The type() function either returns the type of the object or returns a new type object based on the arguments passed.

The type() function has two different forms:

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

type() With a Single Object Parameter

If a single object is passed to type(), the function returns its type.


Example 1: Get Type of an Object

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

numbers_dict = {1: 'one', 2: 'two'}
print(type(numbers_dict))

class Foo:
    a = 0

foo = Foo()
print(type(foo))

Output

<class 'list'>
<class 'dict'>
<class '__main__.Foo'>

If you need to check the type of an object, it is better to use the Python isinstance() function instead. It's because the isinstance() function also checks if the given object is an instance of the subclass.


type() With name, bases and dict Parameters

If three parameters are passed to type(), it returns a new type object.

The three parameters are:

Parameter Description
name a class name; becomes the __name__ attribute
bases a tuple that itemizes the base class; becomes the __bases__ attribute
dict a dictionary which is the namespace containing definitions for the class body; becomes the __dict__ attribute

Example 2: Create a type object

o1 = type('X', (object,), dict(a='Foo', b=12))

print(type(o1))
print(vars(o1))

class test:
  a = 'Foo'
  b = 12
  
o2 = type('Y', (test,), dict(a='Foo', b=12))
print(type(o2))
print(vars(o2))

Output

<class 'type'>
{'a': 'Foo', 'b': 12, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'X' objects>, '__weakref__': <attribute '__weakref__' of 'X' objects>, '__doc__': None}
<class 'type'>
{'a': 'Foo', 'b': 12, '__module__': '__main__', '__doc__': None}

In the program, we have used the Python vars() function which returns the __dict__ attribute. __dict__ is used to store object's writable attributes.

You can easily change these attributes if necessary. For example, if you need to change the __name__ attribute of o1 to 'Z', use:

o1.__name = 'Z'