Sub topic 7
InitVar: arguments that are not stored
This chapter assumes you know how __post_init__ works and how field(init=False) excludes a field from the constructor. Sometimes the constructor needs a value that the finished object should not keep. A raw password, a unit multiplier, and a database connection used only to look something up are common examples. InitVar handles this case.
What InitVar does
You annotate a name with InitVar[T]. The dataclass decorator then treats it as an __init__ parameter, but not as a field. It passes the value to __post_init__, and it never stores it on the instance.
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')
try:
u.password
except AttributeError:
print("password was not stored")The constructor accepts password, and __post_init__ turns it into password_hash. After that the plain text is gone from the object.
Where the value goes
The diagram shows the path of each argument.
An InitVar is invisible to the other generated features:
| Feature | Includes InitVar? |
|---|---|
| `__init__` parameters | Yes |
| `__post_init__` parameters | Yes |
| `__repr__` and `__eq__` | No |
| `fields()` and `asdict()` | No |
Defaults and ordering
An InitVar follows the normal field ordering rules. A parameter without a default cannot come after one that has a default. You can give an InitVar a default, which makes the argument optional.
from dataclasses import dataclass, InitVar
@dataclass
class Rectangle:
width: float
height: float
scale: InitVar[float] = 1.0
def __post_init__(self, scale):
self.width *= scale
self.height *= scale
print(Rectangle(2, 3)) # Rectangle(width=2, height=3)
print(Rectangle(2, 3, scale=10)) # Rectangle(width=20.0, height=30.0)If you have several InitVar fields, __post_init__ receives them in the order you declared them, after self.
Common errors
- Signature mismatch. If you declare an
InitVarbut your__post_init__does not accept it, construction fails with aTypeError. Likewise, if you define anInitVarand no__post_init__at all, the value is silently dropped. - Expecting the attribute to exist. Without a default,
instance.passwordraisesAttributeError. With a default, the class attribute holds that default value, soinstance.scalereturns1.0no matter what you passed. Do not rely on it. - Using
replace(). Thereplace()helper builds a new instance by calling__init__again. It cannot read anInitVarfrom the old object, so anInitVarwithout a default must be passed again, for examplereplace(u, name="bob", password="secret"). Otherwise it raisesValueError.
When to choose InitVar
Use InitVar when a value is needed only to build the object. If the value is still needed later, make it a normal field. If it can be computed from other fields, use field(init=False) and compute it in __post_init__, as the area field in the Rectangle example from the previous chapter did. Reach for InitVar only when the input is a separate argument that must not become part of the object's state.
Exercise
A dataclass Celsius has the field degrees: float and the declaration unit: InitVar[str] = "C". Its __post_init__(self, unit) converts degrees from Fahrenheit when unit == "F". What does print(Celsius(212, "F")) show, assuming the conversion is (degrees - 32) * 5 / 9, and can you read Celsius(212, "F").unit to get "F"?
Show answer
It prints Celsius(degrees=100.0). The unit argument is not a field, so it does not appear in the repr. Reading .unit does not return "F". Because unit has a default, the class attribute holds "C", so the attribute lookup returns the default "C", not the value you passed.