Python type()

If a single argument (object) is passed to type() built-in, it returns type of the given object. If three arguments (name, bases and dict) are passed, it returns a new type object.

Different forms of type() in Python are:

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

type() With a Single Object Parameter

If the single object argument is passed to type(), it returns type of the given object.


Example 1: How to get type of an object?

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

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

class Foo:
    a = 0

InstanceOfFoo = Foo()
print(type(InstanceOfFoo))

When you run the program, the output will be:

<class 'dict'>
<class 'Foo'>

If you need to check type of an object, it is recommended to use Python isinstance() function instead. It's because 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.

Three parameters to the type() function are:

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

Example 2: Create a type object Using type()

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))

When you run the program, the output will be:

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

In the program, we have used Python vars() function return 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 __name__ attribute of o1 to 'Z', simply use:

o1.__name = 'Z'