Python type()

Python type() is a built-in function that returns the type of the object or returns a new type object when all the three arguments are passed to the type() method.

# retruns dict
sample_dict = {"name": "Chandler Bing", "Age": 45}
print(type(sample_dict))

Output

<class 'dict'>

type() Syntax

The type() method has two different forms and the syntax follows as shown below:

# type with a single parameter
type(object)

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

type() Parameters

The type() method takes either a single argument or it can take three parameters.

  • name – a string becomes the class name. It is the same as the __name__ attribute of the class.
  • bases – a tuple that specifies the base class. It is the same as the __bases__ attribute of the class.
  • dict – a dictionary that helps to create the class body. It is the same as the __dict__ attribute of the class.

type() Return Value

When a single argument is passed to the type() function, it returns the type of the object. The value is the same as the object.__class__ instance variable.

When three arguments are passed, the type() method returns a new type object by creating the class dynamically.

Difference between type() function and isinstance() function

Python is a dynamically typed language. So, for example, if we want to know the type of the argument, then it is recommended to use the type() function, whereas if you want to make sure that your method works on specific types of object, then it is recommended to use the isinstance() method. It also considers inheritance.

Example of isinstance() method in Python

def add(x, y):
    if not (isinstance(x, int) and isinstance(y, int)):
        print(f"Invalid Types of Arguments - x:{type(x)}, y:{type(y)}")
        raise TypeError("Invalid Argument type. Please pass only integers")

    return x + y


print(add(5, 6))
print(add(3.43, 4.3))

Output

11

Invalid Types of Arguments - x:<class 'float'>, y:<class 'float'>
TypeError: Invalid Argument type. Please pass only integers

Example 1: Finding the type of a Python object

In this example, let us use the type() method to check some of the variables and values that we have declared and used.

from collections import OrderedDict

# retruns integer
num = 10
print(type(num))

# retruns string
text = "Python Tutorials"
print(type(text))

# retruns list
lst = [1, 2, 3, 4]
print(type(lst))

# retruns dict
sample_dict = {"name": "Chandler Bing", "Age": 45}
print(type(sample_dict))

# retruns OrderedDict
od = OrderedDict()
print(type(od))

class Person:
    name = "Ross"

# retruns type of class
person = Person()
print(type(person))

Output

<class 'int'>
<class 'str'>
<class 'list'>
<class 'dict'>
<class 'collections.OrderedDict'>
<class '__main__.Person'>

Example 2: type() With 3 Parameters

When three arguments are passed, the type() method returns a new type object by creating the class dynamically.

The name represents the class name, the bases represent the base class and the dict is the dictionary of base class attributes.

data1 = type("A", (object,), {"id": 1, "__doc__": "DataClass"})

print(data1.__class__)
print(data1.__bases__)
print(data1.__dict__)
print(data1.__doc__)


class Person:
    name = "Jack"
    age = 12


data2 = type("A", (Person,), dict(name="Jack", age=12, __doc__= "DataClass2"))
print(data2.__class__)
print(data2.__bases__)
print(data2.__dict__)
print(data2.__doc__)

Output

<class 'type'>
(<class 'object'>,)
{'id': 1, '__doc__': 'DataClass', '__module__': '__main__', '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>}
DataClass

<class 'type'>
(<class '__main__.Person'>,)
{'name': 'Jack', 'age': 12, '__doc__': 'DataClass2', '__module__': '__main__'}
DataClass2
Leave a Reply

Your email address will not be published. Required fields are marked *

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like