Claude Code for types: Python Type Objects and Utilities — Claude Skills 360 Blog
Blog / AI / Claude Code for types: Python Type Objects and Utilities
AI

Claude Code for types: Python Type Objects and Utilities

Published: August 17, 2028
Read time: 5 min read
By: Claude Skills 360

Python’s types module exposes built-in type objects and utilities for runtime type work. import types. SimpleNamespace: ns = types.SimpleNamespace(x=1, y=2)ns.x == 1; settable; vars(ns) → dict; useful as anonymous structs. MappingProxyType: types.MappingProxyType(d) → immutable view of dict d; raises TypeError on mutation. ModuleType: m = types.ModuleType("mymod") — create synthetic module; assign to sys.modules["mymod"] to make importable. FunctionType: types.FunctionType — isinstance check for defs incl. lambdas. MethodType: types.MethodType(fn, instance) — bind a function to an instance. LambdaType: same as FunctionType. CodeType: types.CodeType — code objects from compile() or fn.__code__. GeneratorType / CoroutineType / AsyncGeneratorType — type checks for generators/coroutines. TracebackType: types.TracebackType. FrameType: types.FrameType. BuiltinFunctionType / BuiltinMethodType: isinstance check for C-level callables. NoneType: type(None) = types.NoneType (3.10+). EllipsisType / NotImplementedType (3.10+). new_class: types.new_class(name, bases, kwds, exec_body) — dynamic class with metaclass. DynamicClassAttribute: descriptor that works differently on instances vs classes (used by enum). GenericAlias: list[int]types.GenericAlias. UnionType: int | strtypes.UnionType (3.10+). Claude Code generates plugin systems, configuration namespaces, frozen configs, synthetic modules, and type-safe dispatchers.

CLAUDE.md for types

## types Stack
- Stdlib: import types
- Namespace: ns = types.SimpleNamespace(**d)  # attrs instead of dict keys
- Frozen:    proxy = types.MappingProxyType(config_dict)  # immutable
- Module:    m = types.ModuleType("name"); sys.modules["name"] = m
- IsFunc?:   isinstance(obj, types.FunctionType)
- IsMeth?:   isinstance(obj, types.MethodType)
- IsGen?:    isinstance(obj, types.GeneratorType)

types Runtime Type Pipeline

# app/typesutil.py — namespace, proxy, synthetic module, type checks, dispatch
from __future__ import annotations

import sys
import types
from collections.abc import Callable
from dataclasses import asdict, dataclass
from typing import Any, TypeVar

T = TypeVar("T")


# ─────────────────────────────────────────────────────────────────────────────
# 1. SimpleNamespace helpers
# ─────────────────────────────────────────────────────────────────────────────

def namespace(**kwargs: Any) -> types.SimpleNamespace:
    """
    Create a SimpleNamespace with the given keyword fields.

    Example:
        cfg = namespace(host="localhost", port=8080, debug=True)
        cfg.port  # 8080
    """
    return types.SimpleNamespace(**kwargs)


def namespace_from_dict(d: dict[str, Any]) -> types.SimpleNamespace:
    """
    Convert a flat dict to a SimpleNamespace.

    Example:
        ns = namespace_from_dict(config_dict)
        print(ns.timeout)
    """
    return types.SimpleNamespace(**d)


def namespace_to_dict(ns: types.SimpleNamespace) -> dict[str, Any]:
    """Return a dict copy of a SimpleNamespace."""
    return vars(ns).copy()


def merge_namespaces(*namespaces: types.SimpleNamespace) -> types.SimpleNamespace:
    """
    Merge multiple SimpleNamespaces left-to-right (later ones override).

    Example:
        defaults = namespace(timeout=30, retries=3)
        overrides = namespace(timeout=60)
        cfg = merge_namespaces(defaults, overrides)
        cfg.timeout   # 60
        cfg.retries   # 3
    """
    merged: dict[str, Any] = {}
    for ns in namespaces:
        merged.update(vars(ns))
    return types.SimpleNamespace(**merged)


def frozen_namespace(**kwargs: Any) -> types.MappingProxyType:
    """
    Create a MappingProxyType (immutable dict view) from keyword arguments.
    Attempting to set, delete, or modify keys raises TypeError.

    Example:
        config = frozen_namespace(host="localhost", port=5432)
        config["host"]       # "localhost"
        config["host"] = "x" # TypeError
    """
    return types.MappingProxyType(kwargs)


# ─────────────────────────────────────────────────────────────────────────────
# 2. MappingProxyType helpers
# ─────────────────────────────────────────────────────────────────────────────

def freeze(d: dict[str, Any]) -> types.MappingProxyType:
    """
    Return an immutable MappingProxyType view of dict d.
    The underlying dict is NOT copied — mutations to d will be visible
    through the proxy. Use freeze(dict(d)) for a true immutable snapshot.

    Example:
        proxy = freeze({"endpoints": [...], "version": "1.0"})
    """
    return types.MappingProxyType(d)


def frozen_copy(d: dict[str, Any]) -> types.MappingProxyType:
    """
    Return a frozen snapshot of d (creates a copy first).

    Example:
        DEFAULTS = frozen_copy({"timeout": 30, "retries": 3})
    """
    return types.MappingProxyType(dict(d))


def is_frozen(obj: Any) -> bool:
    """Return True if obj is a MappingProxyType."""
    return isinstance(obj, types.MappingProxyType)


# ─────────────────────────────────────────────────────────────────────────────
# 3. Synthetic module creation
# ─────────────────────────────────────────────────────────────────────────────

def make_module(name: str, doc: str = "", **attrs: Any) -> types.ModuleType:
    """
    Create a synthetic module with given attributes.
    The module is NOT registered in sys.modules automatically.

    Example:
        constants = make_module("myapp.constants", TIMEOUT=30, MAX_RETRIES=3)
        constants.TIMEOUT  # 30
    """
    m = types.ModuleType(name, doc)
    for k, v in attrs.items():
        setattr(m, k, v)
    return m


def register_module(module: types.ModuleType) -> types.ModuleType:
    """
    Register a module in sys.modules so it is importable.

    Example:
        constants = make_module("myapp.constants", VERSION="1.0")
        register_module(constants)
        from myapp.constants import VERSION  # works
    """
    sys.modules[module.__name__] = module
    return module


def ephemeral_module(name: str, code: str) -> types.ModuleType:
    """
    Create and execute a module from source code strings.
    The module is not registered in sys.modules.

    Example:
        m = ephemeral_module("calc", "def add(a,b): return a+b")
        m.add(1, 2)  # 3
    """
    m = types.ModuleType(name)
    exec(compile(code, f"<ephemeral:{name}>", "exec"), m.__dict__)
    return m


# ─────────────────────────────────────────────────────────────────────────────
# 4. Type predicate helpers
# ─────────────────────────────────────────────────────────────────────────────

def is_function(obj: Any) -> bool:
    """True for 'def' functions and lambdas (not bound methods or C callables)."""
    return isinstance(obj, types.FunctionType)


def is_method(obj: Any) -> bool:
    """True for bound methods."""
    return isinstance(obj, types.MethodType)


def is_builtin(obj: Any) -> bool:
    """True for C-level functions and methods (e.g., len, list.append)."""
    return isinstance(obj, (types.BuiltinFunctionType, types.BuiltinMethodType))


def is_generator_fn(obj: Any) -> bool:
    """True if obj is a generator function (uses yield)."""
    import inspect
    return inspect.isgeneratorfunction(obj)


def is_coroutine_fn(obj: Any) -> bool:
    """True if obj is an async def function."""
    import inspect
    return inspect.iscoroutinefunction(obj)


def is_generator_obj(obj: Any) -> bool:
    """True if obj is a generator iterator (yielded but not exhausted)."""
    return isinstance(obj, types.GeneratorType)


def callable_kind(obj: Any) -> str:
    """
    Return a string describing the kind of callable obj is.

    Example:
        callable_kind(len)                # "builtin"
        callable_kind(lambda: None)       # "function"
        callable_kind(str.upper)          # "method_descriptor"
        callable_kind(MyClass().method)   # "method"
    """
    if isinstance(obj, types.FunctionType):
        return "function"
    if isinstance(obj, types.MethodType):
        return "method"
    if isinstance(obj, (types.BuiltinFunctionType, types.BuiltinMethodType)):
        return "builtin"
    if isinstance(obj, types.MethodDescriptorType if hasattr(types, "MethodDescriptorType") else object):
        return "method_descriptor"
    if callable(obj):
        return "callable_object"
    return "not_callable"


# ─────────────────────────────────────────────────────────────────────────────
# 5. Dynamic method binding
# ─────────────────────────────────────────────────────────────────────────────

def bind_method(fn: Callable, instance: Any) -> types.MethodType:
    """
    Bind a function to an instance, creating a bound method.

    Example:
        class Adder:
            pass

        def add(self, x):
            return x + 1

        obj = Adder()
        obj.add = bind_method(add, obj)
        obj.add(5)   # 6
    """
    return types.MethodType(fn, instance)


def add_method(cls: type, fn: Callable, name: str | None = None) -> None:
    """
    Dynamically add a function to a class as an unbound method.

    Example:
        class Dog:
            pass

        def speak(self):
            return "Woof!"

        add_method(Dog, speak)
        Dog().speak()   # "Woof!"
    """
    setattr(cls, name or fn.__name__, fn)


# ─────────────────────────────────────────────────────────────────────────────
# Demo
# ─────────────────────────────────────────────────────────────────────────────

if __name__ == "__main__":
    print("=== types demo ===")

    print("\n--- namespace ---")
    cfg = namespace(host="localhost", port=8080, debug=True)
    print(f"  cfg.host={cfg.host}  cfg.port={cfg.port}")
    cfg.port = 9000           # mutable
    print(f"  after mutate:  cfg.port={cfg.port}")
    print(f"  as dict: {namespace_to_dict(cfg)}")

    print("\n--- merge_namespaces ---")
    defaults = namespace(timeout=30, retries=3, debug=False)
    overrides = namespace(timeout=60, debug=True)
    merged = merge_namespaces(defaults, overrides)
    print(f"  merged: timeout={merged.timeout}  retries={merged.retries}  debug={merged.debug}")

    print("\n--- MappingProxyType ---")
    CONSTS = frozen_copy({"PI": 3.14159, "E": 2.71828, "MAX": 100})
    print(f"  CONSTS['PI'] = {CONSTS['PI']}")
    print(f"  is_frozen: {is_frozen(CONSTS)}")
    try:
        CONSTS["PI"] = 0  # type: ignore
    except TypeError as e:
        print(f"  mutation blocked: {e}")

    print("\n--- make_module / register_module ---")
    myconsts = make_module("demo.consts", TIMEOUT=30, VERSION="1.0")
    print(f"  myconsts.TIMEOUT={myconsts.TIMEOUT}  VERSION={myconsts.VERSION}")
    register_module(myconsts)
    import demo.consts as dc
    print(f"  imported demo.consts.TIMEOUT={dc.TIMEOUT}")

    print("\n--- ephemeral_module ---")
    calc = ephemeral_module("calc", "def add(a, b): return a + b\nPI = 3.14")
    print(f"  calc.add(3, 4) = {calc.add(3, 4)}")
    print(f"  calc.PI = {calc.PI}")

    print("\n--- type predicates ---")
    import inspect

    async def async_fn(): pass
    def gen_fn():
        yield 1

    print(f"  is_function(lambda: None)    : {is_function(lambda: None)}")
    print(f"  is_function(len)             : {is_function(len)}")
    print(f"  is_method(str.upper)         : {is_method(str.upper)}")
    print(f"  is_builtin(len)              : {is_builtin(len)}")
    print(f"  is_coroutine_fn(async_fn)    : {is_coroutine_fn(async_fn)}")
    print(f"  is_generator_fn(gen_fn)      : {is_generator_fn(gen_fn)}")
    g = gen_fn()
    print(f"  is_generator_obj(gen_fn())   : {is_generator_obj(g)}")

    print("\n--- callable_kind ---")
    for obj in [len, print, lambda: None, "".upper, object()]:
        try:
            print(f"  {repr(obj)[:35]:38s}: {callable_kind(obj)}")
        except Exception:
            pass

    print("\n--- bind_method / add_method ---")
    class Counter:
        def __init__(self):
            self.count = 0

    def increment(self, by: int = 1) -> None:
        self.count += by

    add_method(Counter, increment)
    c = Counter()
    c.increment(5)
    c.increment(3)
    print(f"  counter after two increments: {c.count}")

    bound = bind_method(lambda self: self.count * 2, c)
    print(f"  bound method result: {bound()}")

    print("\n=== done ===")

For the dataclasses alternative — @dataclass generates __init__, __repr__, __eq__, and optionally __hash__ and comparison methods for structured data with typed fields; types.SimpleNamespace provides ad-hoc attribute bags without any schema — use @dataclass when the structure is stable and type annotations and validation matter; use SimpleNamespace for quick anonymous grouping of values in tests, scripts, and return values from functions where defining a full class is overkill. For the named_tuple (typing.NamedTuple) alternative — NamedTuple provides immutable, indexable, size-fixed records with named field access and tuple unpacking; SimpleNamespace is mutable, not indexable, and has no length — use NamedTuple for lightweight value objects and return types where immutability, hashing, or tuple interoperability is needed; use SimpleNamespace when fields may be added or changed after construction. The Claude Skills 360 bundle includes types skill sets covering namespace()/namespace_from_dict()/namespace_to_dict()/merge_namespaces() SimpleNamespace helpers, freeze()/frozen_copy()/frozen_namespace()/is_frozen() MappingProxyType utilities, make_module()/register_module()/ephemeral_module() synthetic module creation, is_function()/is_method()/is_builtin()/is_generator_fn()/is_coroutine_fn()/callable_kind() type predicates, and bind_method()/add_method() dynamic binding. Start with the free tier to try runtime type patterns and types module pipeline code generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free