On this page
  1. types
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Exposing Immutable Public Registries with MappingProxyType
  7. 2. Lightweight Ad-Hoc Objects with SimpleNamespace
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects

types

Prev: turtledemo | Up: stdlib_module | Next: typing
Rel: datetime, zoneinfo, calendar, collections, heapq
Ref: docs.python.org — types
Tags: #public #python3 #stdlib


Import

import types

Overview

Exposes names for built-in interpreter types that aren't in builtins (ModuleType, FunctionType, MethodType, UnionType, GenericAlias) plus two practical everyday utilities: SimpleNamespace (lightweight attribute bag) and MappingProxyType (read-only view over a dict).

Quick Start

from types import MappingProxyType, SimpleNamespace

cfg = SimpleNamespace(host="127.0.0.1", port=8000)
assert cfg.port == 8000

readonly = MappingProxyType({"env": "prod", "debug": False})
assert readonly["env"] == "prod"

Implementation Walkthrough

1. Exposing Immutable Public Registries with MappingProxyType

Wrap an internal dictionary in MappingProxyType so callers can read and iterate over it without mutating your internal state:

from types import MappingProxyType

_REGISTRY: dict[str, int] = {"alpha": 1, "beta": 2}
REGISTRY = MappingProxyType(_REGISTRY)

assert REGISTRY["alpha"] == 1
try:
    REGISTRY["gamma"] = 3  # type: ignore[index]
except TypeError:
    pass  # read-only view rejects mutation

2. Lightweight Ad-Hoc Objects with SimpleNamespace

Great for quick test doubles and fixture objects without defining a full class:

from types import SimpleNamespace

fake_resp = SimpleNamespace(status=200, text="ok")
assert fake_resp.status == 200

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes