__init__ and Instance State
On this page
__init__ Sets Invariants
Constructor validation prevents bad state from entering your system. Fail early so errors are close to the source.
Validate on Construction
class TimeoutConfig:
def __init__(self, timeout_seconds: int) -> None:
if timeout_seconds <= 0:
raise ValueError("timeout_seconds must be > 0")
self.timeout_seconds = timeout_seconds
Prefer Immutable-Like State
When possible, keep objects stable after construction and provide explicit methods for changes.
Operational Checklist
- Validate required parameters in
__init__. - Document expected units (seconds vs milliseconds).
- Initialize all fields; avoid creating attributes later ad-hoc.
Failure Modes
- Partially initialized objects: attributes appear later and cause runtime surprises.
- Late validation: invalid state travels far before crashing.