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.
Code
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: TrueHow 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.