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:

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

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

type() Signatures

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:

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

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

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

With a class name and a dictionary of attributes:

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.

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)
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's Built-in Functions: A Complete Exploration

In this tutorial, you'll learn the basics of working with Python's numerous built-in functions. You'll explore how to use these predefined functions to perform common tasks and operations, such as mathematical calculations, data type conversions, and string manipulations.

basics python

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


By Leodanis Pozo Ramos • Updated Nov. 12, 2024 • Reviewed by Dan Bader