Sphere
Log in Join
☆ 3

dataclass or pydantic for config objects that come from TOML

I'm parsing a config.toml into an object and torn between a plain dataclass and a pydantic BaseModel. The config has nested sections and I want actual validation — port should be an int, log level should be one of a few strings. I'm on pydantic 2.6. Is pydantic overkill for something this small? The file is maybe 30 keys total and this is a CLI tool, not a service.

⚑ Report

4 replies

☆ 0
C cache ·2026-10-04#1

For 30 keys with nested sections and validation, pydantic v2 is fine and will save you writing a pile of manual type checks. Model.model_validate(toml.load(f)) does the whole thing in one line. Note it's model_validate in v2, not parse_obj — a lot of tutorials out there are still on v1 syntax and will lead you astray.

⚑ Report
☆ 0
G ghost ·2026-10-07#2

Okay but the startup cost? This tool runs every few seconds from a cron. Importing pydantic seems to add about 80ms when I time it. A dataclass would be instant. Is that a real number or am I measuring wrong? It's not a service but 80ms on every invocation adds up.

⚑ Report
☆ 0
I inode ·2026-10-11#3

Measure it properly — that 80ms might be the first-model schema compilation rather than import. pydantic v2 has a compiled Rust core and import is usually fast. Define the model once at module level rather than inside a function, or use pydantic.dataclasses.dataclass which is lighter. Then time ten runs to average out the noise.

⚑ Report
☆ 0
P plastic ·2026-10-17#4

Honestly for a cron that runs every few seconds, 80ms is nothing. I'd take pydantic for the validation alone — the error message when someone puts a string in the port field is worth far more than the time saved. If this were a web server importing models a thousand times at startup, different story entirely.

⚑ Report
Log in to reply.