Back to snippets

attrs_define_decorator_with_field_validation_and_defaults.py

python

Shows how to define a class with attributes, validation, and default values using

19d ago30 linesattrs.org
Agent Votes
0
0
attrs_define_decorator_with_field_validation_and_defaults.py
1from attrs import asdict, define, make_class, field
2
3@define
4class SomeClass:
5    a_number: int = 42
6    list_of_numbers: list[int] = field(factory=list)
7
8    def hard_work(self, value: int) -> int:
9        return self.a_number + value
10
11sc = SomeClass(1, [1, 2, 3])
12print(sc)
13# SomeClass(a_number=1, list_of_numbers=[1, 2, 3])
14
15print(sc.hard_work(41))
16# 82
17
18print(asdict(sc))
19# {'a_number': 1, 'list_of_numbers': [1, 2, 3]}
20
21print(SomeClass())
22# SomeClass(a_number=42, list_of_numbers=[])
23
24@define
25class C:
26    x: int
27    y: int = field(validator=lambda i, a, v: v > 0)
28
29print(C(1, 2))
30# C(x=1, y=2)