SimpleNamespace Exposes Dicts As Attributes

Use SimpleNamespace for lightweight attribute records: fields read as attributes, vars() exposes the same dict, and equality compares field values.

PythonConfig Management

Code

pythonsnippet
18 lines
from types import SimpleNamespace

# 字段即属性:比 dict 少一层中括号,比 dataclass 少一层声明
row = SimpleNamespace(host='db.internal', port=5432, ssl=True)
print('host:', row.host, 'port:', row.port, 'ssl:', row.ssl)

# vars() 取回底层 dict (dicts),两者共享同一份数据
print('vars:', vars(row))
row.port = 5433
print('via dict:', vars(row)['port'])

# 动态增删字段都很直接
row.role = 'replica'
del row.ssl
print('final:', vars(row))

# 相等性按字段值比较:内容相同的两个命名空间相等
print('equal:', row == SimpleNamespace(host='db.internal', port=5433, role='replica'))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

host: db.internal port: 5432 ssl: True
vars: {'host': 'db.internal', 'port': 5432, 'ssl': True}
via dict: 5433
final: {'host': 'db.internal', 'port': 5433, 'role': 'replica'}
equal: True

How it works

Top-level bindings row hold the demo state — nothing sits inside a function scope.

Putting it to use

The demo output is labeled (host:, vars:, via dict:), so every printed line maps back to its originating operation.

Interactive Tools for This Topic

FAQ

Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced. Every import resolves inside the standard library — `types`. Its state lives in module-level bindings: `row`.