Python type() Function

Python type() function has two variants. The more common variant with a single argument is used to determine the data type of a variable or object in Python. It returns the class of the object that is passed as an argument. This page explains this variant and its use cases.

There is another variant with three arguments, used to create a new type object (effectively dynamically create a class). It is explained on another page.

Examples

For example, if you pass an integer like 123 as argument to the type() function, it returns the class (type) int.

If you pass a string like 'PyTut', it returns the class str.

>>> type(123)
<class 'int'>
>>> type(123.456)
<class 'float'>
>>> type(True)
<class 'bool'>
>>> type('PyTut')
<class 'str'>
>>> type([1, 2, 3])
<class 'list'>
>>> type({'a' : 1, 'b' : 4, 'c' : 18})
<class 'dict'>

It works not only for built-in data types, but for any classes from any module.

>>> import datetime as dt
>>> type(dt.date(2023, 12, 31))
<class 'datetime.date'>

It also works with other functions as arguments (their data type is function).

>>> type(open)
<class 'builtin_function_or_method'>
>>> type(len)
<class 'builtin_function_or_method'>

You can also pass classes themselves to the type() function. It returns the type meta class. Classes are also objects in Python.

>>> type(str)
<class 'type'>
>>> type(type)
<class 'type'>

So there is a subtle difference:

  • The type of 123 is int.
  • The type of int is type.
  • The type of type is... type.
>>> type(123)
<class 'int'>
>>> type(type(123))
<class 'type'>
>>> type(type(type(123)))
<class 'type'>

Typical use cases

Checking the data type of an object or variable is useful in many situations, including conditional statements, input validation, error handling, or debugging.

Conditional statements

Python is a dynamically typed language, which means the same variable can have different data types at different times (this is known as polymorphism). A script or function can then do different things based on the data type. To implement this, you can use the type() function in a conditional statement.

if type(x) is str:
    ...  # do something with a string
elif type(x) is int:
    ...  # do something with an int

Note: Using the identity operator is is better than the equality operator == when checking data type.

Input validation and error handling

Many functions and classes only work for certain input data type. If that is the case, it is good practice to validate the inputs and raise errors (often the TypeError) if an unsupported data type is passed as argument.

For example, the following function add_dot_com() only works if the domain input is a string.

def add_dot_com(domain):
    """
    Add '.com' to the end of domain
    Input: domain (str)
    Raise TypeError is domain is not str
    """
    if type(domain) is str:
        return domain + '.com'
    else:
        msg = "Input domain must be a str, passed {} ({})"
        raise TypeError(msg.format(domain, type(domain)))

Before it does what it is supposed to do (add '.com' to the end of the input string), it checks whether the input is indeed a string, using type(domain).

If the input is of different type, it raises a TypeError with custom error message, using type(domain) to inform the user which data type has been passed.

Here are the outputs of this function:

>>> add_dot_com('pytut')
'pytut.com'
>>> add_dot_com('google')
'google.com'
>>> add_dot_com(123)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 11, in add_dot_com
TypeError: Input domain must be a str, passed 123 (<class 'int'>)

Debugging

The type() function can be used in debugging to determine an object's data type at runtime. Thereby you can identify any type-related errors or causes of unexpected behaviour.

This can be particularly useful when working with complex data structures or when debugging code that has been written by someone else.

type() vs. isinstance()

In some cases, instead of type() we can use another built-in function, isinstance().

There are two main differences between the two:

  • type() takes the object as argument and returns its class (type object).
  • isinstance() takes two arguments: the object and the class to check (type object or tuple of type objects). It returns True if the object is of the given class (or its subclass), and False if not.

For example, these are almost equivalent:

if type(s) is str:
    ...
if isinstance(s, str):
    ...

However, the important difference is that the first condition (using type()) will be True only if s type is str, while the second condition (using isinstance()) will be True if s type is str or a subclass of str.

Official documentation

https://docs.python.org/3/library/functions.html#type

By remaining on this website or using its content, you confirm that you have read and agree with the Terms of Use Agreement.

We are not liable for any damages resulting from using this website. Any information may be inaccurate or incomplete. See full Limitation of Liability.

Content may include affiliate links, which means we may earn commission if you buy on the linked website. See full Affiliate and Referral Disclosure.

We use cookies and similar technology to improve user experience and analyze traffic. See full Cookie Policy.

See also Privacy Policy on how we collect and handle user data.

© 2024 PyTut