Attribute Access Without a Class: Python's SimpleNamespace

This article explains how Python's types.SimpleNamespace groups values with attribute access, how it serves JSON configuration, what it costs against dictionaries and data classes, and why its freedom hides typos.

A green tree python with white flecks hangs in loose loops from a thin branch, its head tucked inside the coils.
Photo by Jadon Barnes on Unsplash

Small groups of values, such as a few settings or the fields of a parsed record, are often stored in dictionaries, whose string keys and brackets make code noisier than attribute access, while defining a class for each group adds code that nobody reuses. The present article addresses types.SimpleNamespace, available since Python 3.3, an object that accepts arbitrary attributes, prints them in a readable form and compares them by value. It shows the operations of the type, applies it to configuration loaded from JSON, measures its cost against dictionaries, data classes and named tuples, and identifies the situations in which its freedom becomes a source of errors. Attribute access and a readable representation for an ad hoc group of values, without declaring a class, is the secret weapon of SimpleNamespace.

Sandbox Mode: Attributes Without a Declaration

A SimpleNamespace is created with keyword arguments, each of which becomes an attribute stored in the instance's __dict__, and attributes can afterwards be added, changed or deleted without restriction. Two namespaces are equal when their attributes are equal, and the representation lists the attributes in insertion order, which replaced alphabetical order in Python 3.9. The following example shows these operations.

from types import SimpleNamespace

server = SimpleNamespace(host="localhost", port=8080)
server.debug = True
server.port += 1
del server.host
print(server)        # Output: namespace(port=8081, debug=True)
print(vars(server))  # Output: {'port': 8081, 'debug': True}

defaults = {"host": "0.0.0.0", "port": 80}
merged = SimpleNamespace(**defaults, debug=False)
print(merged == SimpleNamespace(host="0.0.0.0", port=80, debug=False))  # Output: True
print(merged == {"host": "0.0.0.0", "port": 80, "debug": False})        # Output: False

The function vars returns the dictionary that holds the attributes, which is the simplest way to convert a namespace back to a mapping. Equality applies only between namespaces, so a namespace never equals a dictionary with the same contents. Python 3.13 also accepts a mapping or an iterable of pairs as a positional argument, as in SimpleNamespace(defaults), and supports copy.replace, which returns a modified copy; on earlier versions, unpacking with ** produces the same result.

Configuration From JSON

Nested configuration is the most common use of the type, because json.loads can build a namespace for every JSON object through its object_hook argument, so that deep values are read as chains of attributes. The following example converts a configuration document and then serializes it again.

import json
from types import SimpleNamespace

text = '{"db": {"host": "db.local", "port": 5432}, "workers": 4}'
config = json.loads(text, object_hook=lambda fields: SimpleNamespace(**fields))
print(config.db.port, config.workers)  # Output: 5432 4

try:
    json.dumps(config)
except TypeError as error:
    print(error)  # Output: Object of type SimpleNamespace is not JSON serializable


def to_plain(value):
    if isinstance(value, SimpleNamespace):
        return {key: to_plain(item) for key, item in vars(value).items()}
    return value


print(json.dumps(to_plain(config)))
# Output: {"db": {"host": "db.local", "port": 5432}, "workers": 4}

Reading config.db.port is shorter than config["db"]["port"], but the conversion works in one direction only: json.dumps rejects namespaces, so serialization needs a function that turns them back into dictionaries recursively. The namespace is also mutable, unlike the read-only view described in the article devoted to MappingProxyType, so any code that receives the configuration can change it.

Pitfalls of SimpleNamespace

The type accepts any attribute and checks nothing, so its pitfalls are the price of that freedom and of the dictionary that every instance carries. Six pitfalls are distinguished, which are the following:

  1. Silent typos. Assigning to a misspelt name creates a new attribute instead of raising an error.
  2. No declared fields. Nothing documents which attributes an instance must have, and type checkers cannot verify them.
  3. Memory per instance. Every namespace owns a full dictionary, which makes it heavier than a data class instance, a slotted class or a named tuple.
  4. Unhashable. Namespaces cannot be dictionary keys or members of sets.
  5. Not serializable. json.dumps rejects them, and vars returns the live dictionary, not a copy.
  6. A different Namespace. argparse.Namespace is a separate class with similar behaviour, so isinstance checks against SimpleNamespace fail for parsed arguments.

The first, third and fourth pitfalls are reproduced in the following example, which measures the memory of 100,000 instances with two fields.

import tracemalloc
from dataclasses import dataclass
from types import SimpleNamespace


@dataclass
class Point:
    x: int
    y: int


@dataclass(slots=True)
class SlotPoint:
    x: int
    y: int


def size_of(build):
    tracemalloc.start()
    items = [build(n) for n in range(100_000)]
    used = tracemalloc.get_traced_memory()[0]
    tracemalloc.stop()
    return used


namespace = size_of(lambda n: SimpleNamespace(x=1, y=2))
plain = size_of(lambda n: Point(1, 2))
slotted = size_of(lambda n: SlotPoint(1, 2))
print(namespace > 2 * plain, plain > slotted)  # Output: True True

point = SimpleNamespace(x=1, y=2)
point.z_ = 3
print(point)  # Output: namespace(x=1, y=2, z_=3)
try:
    {point: "origin"}
except TypeError as error:
    print(error)  # Output: unhashable type: 'types.SimpleNamespace'

On CPython 3.12, a namespace occupied about 230 bytes against about 90 for a data class instance, whose dictionary shares its keys with the other instances of the class, and about 55 for a slotted data class, the mechanism examined in the article devoted to __slots__. Creating a namespace took about 92 nanoseconds, the same as a data class and twice as long as a dictionary literal, while reading an attribute took about 25 nanoseconds against 29 for a dictionary key, so the type is as fast to read as a dictionary but not lighter than a class.

Choosing a Container for a Few Fields

Consequently, SimpleNamespace suits short-lived, informal groups of values, whereas data that crosses module boundaries benefits from declared fields, as the following table summarizes.

Situation Recommended approach
Quick grouping of values in a script or a test SimpleNamespace
Nested configuration read with attribute access json.loads with an object_hook that builds namespaces
A record type used across a program A data class
Many instances in memory A slotted data class or a named tuple
An immutable, hashable record A frozen data class or a named tuple
Arbitrary keys or keys that are not identifiers A dictionary
A modified copy of a namespace in Python 3.13 or later copy.replace

The declared alternative is examined in the article devoted to data classes.

Conclusion

It is concluded that SimpleNamespace stores arbitrary attributes in its own dictionary, prints them in insertion order and compares namespaces by their attributes, which makes it convenient for configuration and quick groupings. This magic has a price: typos create attributes silently, instances weigh more than data class objects, and namespaces can be neither hashed nor serialized directly. Observing a program line by line while it runs, as debuggers and coverage tools do, is the purpose of sys.settrace, which is developed in a future article of this series.