-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsafe_dataclass_replace.py
More file actions
34 lines (22 loc) · 861 Bytes
/
safe_dataclass_replace.py
File metadata and controls
34 lines (22 loc) · 861 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
"""Type-safe `dataclass.replace`.
This example shows how you can make a type-safe version of `dataclass.replace`
that will report if you try passing an argument that isn't a valid dataclass field
or has invalid type.
"""
from __future__ import annotations
import dataclasses
from typing_extensions import Unpack
import typed_dict
@dataclasses.dataclass
class _User:
name: str
age: int = 99
UserDict = typed_dict.from_dataclass(_User)
class User(_User):
# The `Unpack` support in mypy is experimental, so you need to run mypy with
# `--enable-incomplete-feature=Unpack` for it to work.
def evolve(self, **kwargs: Unpack[UserDict]) -> User:
"""Create a copy of User with the given fields replaced."""
return dataclasses.replace(self, **kwargs)
user = User(name='Aragorn')
user = user.evolve(age=88) # noqa: WPS432