field metadata Describes Dataclass Columns
field(metadata=) hangs display hints on dataclass fields, and fields() returns them as read-only mappings that drive formatting and serialization.
Code
from dataclasses import dataclass, field, fields
@dataclass
class Measurement:
sensor: str
celsius: float = field(metadata={'unit': '°C', 'precision': 1})
humidity: float = field(default=0.0, metadata={'unit': '%', 'precision': 0})
# fields() 把 metadata 原样带回来:输出列、序列化格式都由它驱动
for f in fields(Measurement):
print(f.name, f.type, dict(f.metadata))
# metadata 是只读映射:按它拼格式串,而不是散落各处的 if/else
def render(row: Measurement) -> str:
parts = []
for f in fields(row):
value = getattr(row, f.name)
unit = f.metadata.get('unit', '')
precision = f.metadata.get('precision')
text = f'{value:.{precision}f}' if precision is not None else str(value)
parts.append(f'{f.name}={text}{unit}')
return ' | '.join(parts)
print(render(Measurement('bedroom', 21.4, 54.9)))Output
Captured from a sandboxed run of this snippet in the build pipeline.
sensor <class 'str'> {}
celsius <class 'float'> {'unit': '°C', 'precision': 1}
humidity <class 'float'> {'unit': '%', 'precision': 0}
sensor=bedroom | celsius=21.4°C | humidity=55%field metadata Describes Dataclass Columns: inside the code
The moving parts are the class class and the function render.
Iteration happens inside for f in fields(Measurement) — everything outside it runs once.
Caveats
- Everything here ships with the language; nothing to install.
Putting it to use
The load-bearing definition is def render(row: Measurement) -> str
The surface worth importing is render; the helpers around it are private to the snippet.
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
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. The file defines `render` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.