Namedtuple Records With Named Fields

namedtuple turns plain tuples into records with named fields: _make builds from sequences, _replace copies with edits, _asdict exports a dict.

PythonData Integrity

Code

pythonsnippet
19 lines
from collections import namedtuple

# 轻量不可变记录(records):字段名(named fields)取代索引访问
Metric = namedtuple("Metric", ["host", "p95_ms", "errors"])
row = Metric("web-1", 182.5, 3)
print(row.host, row.p95_ms, row.errors)

# _make 直接从序列建实例:解析 CSV 行时不用手工拆字段
parsed = Metric._make(["db-1", "44.2", "0"])
print(parsed.host, float(parsed.p95_ms))

# _replace 返回修改后的副本:实例本身不可变
updated = row._replace(errors=0)
print("updated:", updated.errors, "original:", row.errors)

# defaults 从右往左补齐缺省值
WithDefault = namedtuple("Metric", ["host", "p95_ms", "errors"], defaults=[0])
print(WithDefault("cache-1", 12.0))
print(row._asdict())

Output

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

web-1 182.5 3
db-1 44.2
updated: 0 original: 3
Metric(host='cache-1', p95_ms=12.0, errors=0)
{'host': 'web-1', 'p95_ms': 182.5, 'errors': 3}

How it works

Module-level bindings hold the data — row, parsed, updated — with no function scope in between.

Applying it

Running the file prints labeled results such as updated: — each operation’s effect is visible in the output.

Interactive Tools for This Topic

FAQ

Is a package install part of the setup?
No. Installation is unnecessary because only built-in APIs are used. Every import resolves inside the standard library — `collections`. Its state lives in module-level bindings: `row`, `parsed`, `updated`.