InitVar Passes Transient Inputs to __post_init__
Declare initialization-only parameters with dataclasses.InitVar so __post_init__ can derive or normalize state without leaking extra fields to asdict.
Code
from dataclasses import InitVar, asdict, dataclass, field, fields
@dataclass(frozen=True)
class ApiUser:
username: str
tags: tuple[str, ...] = field(init=False)
# InitVar values are forwarded to __post_init__ only and never stored on self
raw_tags: InitVar[list[str]]
lowercase: InitVar[bool] = True
def __post_init__(self, raw_tags: list[str], lowercase: bool) -> None:
if lowercase:
object.__setattr__(self, "username", self.username.strip().lower())
cleaned = tuple(sorted({t.strip().lower() for t in raw_tags if t.strip()}))
object.__setattr__(self, "tags", cleaned)
user = ApiUser(" Ada_Lovelace ", raw_tags=["Admin", " billing ", "admin"])
print("repr :", repr(user))
print("dict :", asdict(user))
print("fields:", [f.name for f in fields(ApiUser)])
print("has raw_tags attr:", hasattr(user, "raw_tags"))Output
Captured from a sandboxed run of this snippet in the build pipeline.
repr : ApiUser(username='ada_lovelace', tags=('admin', 'billing'))
dict : {'username': 'ada_lovelace', 'tags': ('admin', 'billing')}
fields: ['username', 'tags']
has raw_tags attr: FalseExecution path — InitVar Passes Transient Inputs to post_init
The snippet is organized around the class ApiUser and the function __post_init__.
Points of care
- Everything it calls is documented as part of the language core.
Applying it
The entry-point signature is def __post_init__(self, raw_tags: list[str], lowercase: bool) -> None
The run emits 4 labeled sections — repr :, dict :, fields:, has raw_tags attr: — one per step.
Statements that matter
def __post_init__(self, raw_tags: list[str], lowercase: bool) -> None:
if lowercase:
object.__setattr__(self, "username", self.username.strip().lower())
cleaned = tuple(sorted({t.strip().lower() for t in raw_tags if t.strip()}))
object.__setattr__(self, "tags", cleaned)
Interactive Tools for This Topic
FAQ
- Does it depend on any third-party library?
- No third-party library is referenced; the standard library covers it. The file defines `__post_init__` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.