2 min read

Python Types Module

The types module defines names for some object types that are used by the standard Python interpreter, but not exposed as built-ins (like int or str). It also provides some utility classes and functions for dynamic object creation.

Importing the Module

import types

Standard Interpreter Types

The module provides names for many types that are returned by standard functions.

Functions and Generators

  • types.FunctionType: The type of user-defined functions.
  • types.LambdaType: The type of user-defined functions created by lambda expressions (same as FunctionType).
  • types.GeneratorType: The type of generator-iterator objects, created by generator functions.
import types

def my_func():
    yield 1

gen = my_func()

print(isinstance(my_func, types.FunctionType))   # True
print(isinstance(gen, types.GeneratorType))      # True

Modules and Methods

  • types.ModuleType: The type of modules.
  • types.MethodType: The type of methods of user-defined class instances.
import types
import sys

print(isinstance(sys, types.ModuleType)) # True

class MyClass:
    def method(self):
        pass

obj = MyClass()
print(isinstance(obj.method, types.MethodType)) # True

SimpleNamespace

types.SimpleNamespace is a simple object subclass that provides attribute access to its namespace, as well as a meaningful repr. It is often used as a lightweight container for variables.

from types import SimpleNamespace

# Create a namespace with attributes
data = SimpleNamespace(x=10, y=20, name="Point")

print(data.x)       # Output: 10
print(data)         # Output: namespace(x=10, y=20, name='Point')

# Add new attributes
data.z = 30
print(data.z)       # Output: 30

Dynamic Class Creation

types.new_class()

The new_class() function allows you to create class objects dynamically using the appropriate metaclass.

import types

def method(self):
    return "Hello"

# Create a class named 'MyDynamicClass'
MyDynamicClass = types.new_class("MyDynamicClass", (object,), {}, lambda ns: ns.update(greet=method))

obj = MyDynamicClass()
print(obj.greet()) # Output: Hello

MappingProxyType

types.MappingProxyType is a read-only proxy of a mapping. It provides a dynamic view on the mapping’s entries, which means that when the mapping changes, the view reflects these changes.

from types import MappingProxyType

d = {'a': 1}
proxy = MappingProxyType(d)

print(proxy['a']) # Output: 1

# proxy['b'] = 2  # TypeError: 'mappingproxy' object does not support item assignment

d['b'] = 2
print(proxy['b']) # Output: 2

programming/python/python