Python type()

In this tutorial, we will learn about the Python type() function with the help of examples.

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

Example

prime_numbers = [2, 3, 5, 7]

# check type of prime_numbers
result = type(prime_numbers)
print(result)

# Output: <class 'list'>

1. type() Syntax

The type() function has two different forms:

# type with single parameter
type(object)

# type with 3 parameters
type(name, bases, dict)

2. type() Parameters

The type() function either takes a single object parameter.

Or, it takes 3 parameters

  • 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

3. type() Return Value

The type() function returns

  • type of the object, if only one object parameter is passed
  • a new type, if 3 parameters passed

4. Example 1: type() with Object parameter

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.

5. Example 2: type() With 3 Parameters

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'