Skip to content

type()

The built-in type() function serves dual purposes: it can be used to determine the type of an object or to create new classes dynamically. Here’s a quick example of how to use this function:

Language: Python
>>> type(42)
<class 'int'>

>>> DemoClass = type("DemoClass", (), {"value": 42})
>>> instance = DemoClass()
>>> instance.value
42

type() Signatures

Language: Python Syntax
type(object)
type(name, bases, dict, **kwds)

Arguments

Argument Description
object Any Python object whose type is to be determined
name The class’s name
bases A tuple containing the base classes
dict A dictionary of attributes and methods defined in the class body
**kwds Additional keyword arguments that are passed to the metaclass constructor

Return Value

  • Returns the type of the input object
  • Returns a Python class object when called with the type(name, bases, dict, **kwds) signature

type() Examples

With different objects as arguments:

Language: Python
>>> type(42)
<class 'int'>

>>> type(2.75)
<class 'float'>

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

With a class name and a dictionary of attributes:

Language: Python
>>> DemoClass = type("DemoClass", (), {"value": 42})
>>> DemoClass()
<class '__main__.DemoClass'>

type() Common Use Cases

The most common use cases for the type() include:

  • Checking the type of an object at runtime.
  • Dynamically creating new classes.
  • Implementing factories that produce classes based on input data.

type() Real-World Example

In a scenario where you need to create multiple data classes dynamically based on a schema, you can use the type() function to automate class creation. This can be especially useful in frameworks or libraries that need to generate classes on the fly.

Language: Python
def create_class(name, custom_members):
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

    def __repr__(self):
        return f"{name}({self.__dict__})"

    class_members = {
        "__init__": __init__,
        "__repr__": __repr__,
    }
    class_members.update(custom_members)

    return type(name, (), class_members)
Language: Python
>>> User = create_class("User", {"name": "", "age": 0, "email": ""})
>>> john = User(name="John", age=30, email="john@example.com")
>>> john.name
'John'

In this example, the type() function allows for the dynamic creation of classes based on a given schema, enabling flexible and reusable code structures.

Tutorial

Python Built-in Functions: A Complete Guide

Use Python's built-in functions for math, data types, iterables, and I/O to write shorter, more Pythonic code.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Feb. 9, 2026 • Reviewed by Dan Bader