forked from GalacticDynamics/dataclassish
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathregister_copyreplace.py
More file actions
178 lines (129 loc) · 4.37 KB
/
Copy pathregister_copyreplace.py
File metadata and controls
178 lines (129 loc) · 4.37 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
"""Register dispatches for CanReplace objects."""
__all__: tuple[str, ...] = ()
import copy
import sys
from collections.abc import Mapping
from typing import Any
import optype as opt
from plum import dispatch
from .register_base import _recursive_replace_helper
# ===================================================================
# Get field
@dispatch
def get_field(obj: opt.copy.CanReplaceSelf, k: str, /) -> Any:
"""Get a field of a dataclass instance by name.
Examples:
>>> from dataclasses import dataclass
>>> from dataclassish import get_field
% invisible-code-block: python
%
% import sys
% skip: start if(sys.version_info < (3, 13), reason="py3.13+")
>>> @dataclass
... class Point:
... x: float
... y: float
>>> p = Point(1.0, 2.0)
>>> get_field(p, "x")
1.0
% skip: end
This works for any object that implements the ``__replace__`` method.
>>> class Point:
... def __init__(self, x, y):
... self.x = x
... self.y = y
... def __replace__(self, **changes):
... return Point(**(self.__dict__ | changes))
... def __repr__(self):
... return f"Point(x={self.x}, y={self.y})"
>>> p = Point(1.0, 2.0)
>>> get_field(p, "x")
1.0
"""
return getattr(obj, k)
# ===================================================================
# Replace
@dispatch
def replace(obj: opt.copy.CanReplaceSelf, /, **kwargs: Any) -> opt.copy.CanReplaceSelf:
"""Replace the fields of an object.
Examples:
>>> from dataclassish import replace
% invisible-code-block: python
%
% import sys
% skip: start if(sys.version_info < (3, 13), reason="py3.13+")
As of Python 3.13, dataclasses implement the ``__replace__`` method.
>>> from dataclasses import dataclass
>>> @dataclass
... class Point:
... x: float
... y: float
>>> p = Point(1.0, 2.0)
>>> p
Point(x=1.0, y=2.0)
>>> replace(p, x=3.0)
Point(x=3.0, y=2.0)
% skip: end
>>> class Point:
... def __init__(self, x, y):
... self.x = x
... self.y = y
... def __replace__(self, **changes):
... return Point(**(self.__dict__ | changes))
... def __repr__(self):
... return f"Point(x={self.x}, y={self.y})"
>>> p = Point(1.0, 2.0)
>>> replace(p, x=2.0)
Point(x=2.0, y=2.0)
The ``__replace__`` method was introduced in Python 3.13 to bring
``dataclasses.replace``-like functionality to any implementing object. The
method is publicly exposed via the ``copy.replace`` function.
% invisible-code-block: python
%
% import sys
% skip: start if(sys.version_info < (3, 13), reason="py3.13+")
>>> import copy
>>> copy.replace(p, x=3.0)
Point(x=3.0, y=2.0)
% skip: end
"""
return (
obj.__replace__(**kwargs)
if sys.version_info < (3, 13)
else copy.replace(obj, **kwargs)
)
@dispatch # type: ignore[no-redef]
def replace(
obj: opt.copy.CanReplaceSelf, fs: Mapping[str, Any], /
) -> opt.copy.CanReplaceSelf:
"""Replace the fields of a dataclass instance.
Examples:
>>> from dataclasses import dataclass
>>> from dataclassish import replace, F
>>> class Point:
... def __init__(self, x, y):
... self.x = x
... self.y = y
... def __replace__(self, **changes):
... return Point(**(self.__dict__ | changes))
... def __repr__(self):
... return f"Point(x={self.x}, y={self.y})"
>>> @dataclass
... class TwoPoint:
... a: Point
... b: Point
>>> p = TwoPoint(Point(1.0, 2.0), Point(3.0, 4.0))
>>> p
TwoPoint(a=Point(x=1.0, y=2.0), b=Point(x=3.0, y=4.0))
>>> replace(p, {"a": {"x": 5.0}, "b": {"y": 6.0}})
TwoPoint(a=Point(x=5.0, y=2.0), b=Point(x=3.0, y=6.0))
>>> replace(p, {"a": {"x": F({"thing": 5.0})}})
TwoPoint(a=Point(x={'thing': 5.0}, y=2.0),
b=Point(x=3.0, y=4.0))
This also works on mixed-type structures, e.g. a dictionary of objects.
>>> p = {"a": Point(1.0, 2.0), "b": Point(3.0, 4.0)}
>>> replace(p, {"a": {"x": 5.0}, "b": {"y": 6.0}})
{'a': Point(x=5.0, y=2.0), 'b': Point(x=3.0, y=6.0)}
"""
kwargs = {k: _recursive_replace_helper(obj, k, v) for k, v in fs.items()}
return replace(obj, **kwargs)