Python Glossary Русский

Python 3.7+dataclassesterm

dataclasses.InitVar

fields

A pseudo-type for a field passed to __init__/__post_init__ but not stored as an attribute.

Syntax

field: dataclasses.InitVar[T]

InitVar exists for input that is only needed to compute the real fields and should not live on the instance: once __init__ finishes, no such attribute exists. Hence the usual surprise — an InitVar never shows up in repr, equality, fields() or asdict(). Forget to define __post_init__ and the value is accepted and silently discarded; inside __post_init__ these parameters arrive positionally, in declaration order.

Examples

import dataclasses
@dataclasses.dataclass
class C:
    x: int
    add: dataclasses.InitVar[int]
    def __post_init__(self, add):
        self.x += add
print(C(10, 5).x)   # → 15

See also

Open in the full glossarydocs.python.orgReport an inaccuracy