Determine the type of a python object

How to determine the type of a python object

This tutorial will show you how to get type of and Python object. To determine the type of a Python we use type built-in function.

type() built-in function

type(object)

With one argument, return the type of an object. The return value is a type object and generally the same object as returned by object.__class__.

Here are some example:

>>> type("This is string")
<class 'str'>
>>> type(123)
<class 'int'>
>>> type(list())
<class 'list'>
>>> type(dict())
<class 'dict'>
>>> type(set())
<class 'set'>
>>> type(None)
<class 'NoneType'>
>>>

isinstance() built-in function

If you would like to check the type of an object, isinstance() built-in function is recommended, because it takes subclasses into account.

isinstance(object, classinfo)

isinstance return true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof. If object is not an object of the given type, the function always returns false.

Example:

>>> isinstance("This is string", str)
True
>>> isinstance(1, int)
True
>>> isinstance(1.2, int)
False
>>> isinstance(1.2, float)
True
>>> isinstance((1, 2), list)
False
>>> isinstance((1, 2), tuple)
True
>>>
Last modified October 4, 2020