Sub topic 7
InitVar: arguments that are not stored
This chapter assumes you know @dataclass, field() options such as init=False and repr=False, and the basics of __post_init__. You should also be comfortable with class inheritance and with the difference between instance and class attributes. InitVar itself works on any Python 3.7 or newer.
The problem: input that is needed once
Some constructor arguments are only inputs to a calculation. A password becomes a hash. A diameter becomes a radius. A database connection is used to load data and never kept. If you store such a value as a normal field, it shows up in repr(), takes part in ==, appears in asdict() and stays in memory.
A dataclass has two partial answers for this:
field(init=False)creates a field that is not a constructor parameter. That is the opposite problem, because it stores a value the caller never supplies.field(repr=False)hides the value fromrepr(), but the value is still stored and still compared.
InitVar fills the gap. It is a parameter of __init__ and __post_init__ that never becomes an instance attribute.
Declaring an InitVar
Annotate a name with InitVar[T], where T is the type of the argument:
import hashlib
from dataclasses import dataclass, field, InitVar
@dataclass
class User:
name: str
password: InitVar[str]
password_hash: str = field(init=False, repr=False)
def __post_init__(self, password):
self.password_hash = hashlib.sha256(password.encode()).hexdigest()
u = User("ana", "secret")
print(u) # User(name='ana')
print(hasattr(u, "password")) # False
print(len(u.password_hash)) # 64The generated __init__ has the signature __init__(self, name, password). It stores name, then calls self.__post_init__(password). It never executes self.password = password.
__post_init__ receives every InitVar as a positional argument, in the order the InitVars were declared. Name the parameters the same as the fields. Dataclasses passes them by position, so a mismatch in order silently swaps values.
What InitVar affects and what it ignores
An InitVar is a pseudo-field. Dataclasses records it so that __init__ can take the parameter, and then mostly ignores it.
| Feature | Includes the InitVar? |
|---|---|
| Parameter of `__init__` | Yes |
| Parameter of `__post_init__` | Yes |
| `__repr__` output | No |
| `__eq__` and ordering | No |
| `fields()` | No |
| `asdict()` and `astuple()` | No |
| Instance attribute | No (see the default-value gotcha below) |
| `replace()` | Must be supplied if it has no default |
You can see this in practice:
import hashlib
from dataclasses import dataclass, field, InitVar, fields, asdict, replace
@dataclass
class User:
name: str
password: InitVar[str]
password_hash: str = field(init=False, repr=False)
def __post_init__(self, password):
self.password_hash = hashlib.sha256(password.encode()).hexdigest()
u = User("ana", "secret")
print([f.name for f in fields(u)]) # ['name', 'password_hash']
print(list(asdict(u))) # ['name', 'password_hash']
try:
replace(u, name="bob")
except ValueError as e:
print(e) # InitVar 'password' must be specified with replace()
print(replace(u, name="bob", password="secret").name) # bobThe replace() behavior follows from the design. replace() builds a new instance by calling the constructor. It copies stored fields from the old instance, but the InitVar was never stored, so you must supply it again. Fields declared with init=False, such as password_hash, are not copied. They are recomputed by __post_init__.
Note that asdict() still contains password_hash, even though repr=False hides it from the printed output. If you serialize the object, you leak the hash.
InitVar with a default value
An InitVar can have a default, which makes the parameter optional:
from dataclasses import dataclass, field, InitVar
@dataclass
class Account:
owner: str
balance: float = field(init=False)
initial_deposit: InitVar[float] = 0.0
def __post_init__(self, initial_deposit):
if initial_deposit < 0:
raise ValueError("initial_deposit must be non-negative")
self.balance = initial_deposit
print(Account("ana")) # Account(owner='ana', balance=0.0)
print(Account("ben", 50.0)) # Account(owner='ben', balance=50.0)Two rules apply here.
- Default ordering still applies. An
InitVaris a parameter of__init__, so a parameter without a default cannot follow one that has a default. Dataclasses raisesTypeErrorwhen it builds the class. Thebalancefield hasinit=False, so it is not a parameter and can sit before a defaulted parameter. - The default becomes a class attribute. Dataclasses leaves a plain default value on the class. The
InitVaris not stored on instances, but reading it falls back to the class attribute:
acct = Account("ben", 50.0)
print(acct.initial_deposit) # 0.0, the class default, not the 50.0 you passedThis is a trap. The value looks like real data, but it is the default and not what the caller passed. Without a default, reading u.password raises AttributeError, which is the safer failure. Do not read an InitVar from the instance in either case. Use only the parameter inside __post_init__.
Computing a field from an InitVar
A common use is converting between representations. This circle accepts a diameter but stores a radius:
from dataclasses import dataclass, field, InitVar
@dataclass
class Circle:
radius: float = field(init=False)
diameter: InitVar[float]
def __post_init__(self, diameter):
if diameter <= 0:
raise ValueError("diameter must be positive")
self.radius = diameter / 2
c = Circle(10)
print(c) # Circle(radius=5.0)
print(c == Circle(10)) # TrueEquality compares only radius. Two circles built from the same diameter are equal, and the diameter never needs to exist after construction.
InitVar and frozen dataclasses
In a frozen dataclass, normal assignment raises FrozenInstanceError, including inside __post_init__. Use object.__setattr__ to set derived fields:
import hashlib
from dataclasses import dataclass, field, InitVar
@dataclass(frozen=True)
class Token:
user: str
raw: InitVar[str]
digest: str = field(init=False)
def __post_init__(self, raw):
digest = hashlib.sha256(raw.encode()).hexdigest()[:8]
object.__setattr__(self, "digest", digest)
t = Token("ana", "abc123")
print(len(t.digest)) # 8
print(hash(t) == hash(Token("ana", "abc123"))) # TrueThe frozen instance is hashable because eq=True and frozen=True together generate __hash__. The hash uses user and digest, and never sees raw.
InitVar under inheritance
The InitVars of a base class are part of the subclass constructor too. The subclass __post_init__ therefore receives all of them, base class first. It must pass the base ones on to the parent:
from dataclasses import dataclass, InitVar
@dataclass
class Base:
name: str
secret: InitVar[str]
def __post_init__(self, secret):
self.token = secret[::-1]
@dataclass
class Child(Base):
extra: InitVar[int] = 0
def __post_init__(self, secret, extra):
super().__post_init__(secret)
self.token += str(extra)
c = Child("a", "abc", 5)
print(c) # Child(name='a')
print(c.token) # cba5Two mistakes are common here:
- Overriding
__post_init__with too few parameters. IfChild.__post_init__took onlyextra, the generated__init__would still call it withsecretandextra, and you would get aTypeError. - Forgetting
super().__post_init__(...). The parent's validation and derived values then never run. Dataclasses does not chain__post_init__for you.
token here is a plain attribute set in __post_init__, not a field. It is invisible to repr, ==, fields() and asdict(). If you want it compared or shown, declare it as field(init=False).
When not to use InitVar
InitVar fits when the input is part of the normal way to construct the object. Consider alternatives in these cases:
- Several construction routes. If an object can be built from a diameter, a radius or an area, give the class a
@classmethodsuch asCircle.from_diameter(d)and keep the dataclass fields honest. TheInitVarapproach allows only one signature. - Heavy dependencies. Passing a database connection through
InitVarmakes the class hard to test and ties it to one source of data. Load the data outside and pass the result in. - Values you may need later. If any method might need the argument again, store it as a field. An
InitVaris gone after construction.
Summary of rules
InitVar[T]adds a parameter to__init__and__post_init__without storing it.- It does not appear in
repr,==,fields()orasdict(). __post_init__receives allInitVars positionally, in declaration order, with base classes first.- A default on an
InitVaris left as a class attribute, so never read the value from the instance. replace()requires you to pass anyInitVarthat has no default.- Frozen classes need
object.__setattr__inside__post_init__. - Subclasses must accept the parent's
InitVars and callsuper().__post_init__.
Exercise
A dataclass declares name: str, scale: InitVar[float] = 1.0 and size: float = field(init=False). Its __post_init__(self, scale) sets self.size = 10 * scale. After s = Shape("box", 3.0), what do s.size and s.scale evaluate to, and does fields(s) list scale?
Show answer
s.size is 30.0. s.scale is 1.0, not 3.0. The InitVar default stays as a class attribute, and the passed value 3.0 was never stored on the instance. fields(s) does not list scale, only name and size.
Exercise
You have a dataclass User with name: str and password: InitVar[str], plus a stored password_hash field. Why does replace(user, name="bob") raise ValueError, and how do you fix the call?
Show answer
replace() creates the new instance through __init__, and the password InitVar was never stored on the old instance, so it cannot be copied. Pass it explicitly: replace(user, name="bob", password="..."). The hash is then recomputed in __post_init__.
Exercise
A subclass adds extra: InitVar[int] = 0 and defines __post_init__(self, extra). The base class has secret: InitVar[str]. What happens when you construct the subclass, and what should the signature look like?
Show answer
The generated __init__ calls __post_init__(secret, extra), so the subclass method with only extra raises TypeError. Define __post_init__(self, secret, extra) and call super().__post_init__(secret) so the base class logic runs.