Skip to content

Commit 8041109

Browse files
committed
added the new function to the const_class decorator
1 parent 61fd373 commit 8041109

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

src/constclasses/const_class.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
ConstClassBase,
66
)
77

8+
from copy import deepcopy
9+
810

911
def const_class_impl(
1012
cls,
@@ -58,6 +60,17 @@ def __setattr__(self, attr_name: str, attr_value) -> None:
5860
attr_name, cls.__annotations__.get(attr_name), attr_value
5961
)
6062

63+
def new(self, **kwargs):
64+
def _get_value(key: str):
65+
return kwargs.get(key, deepcopy(getattr(self, key)))
66+
67+
if with_kwargs:
68+
init_params = {key: _get_value(key) for key in self.__annotations__}
69+
return ConstClass(**init_params)
70+
else:
71+
init_params = [_get_value(key) for key in self.__annotations__]
72+
return ConstClass(*init_params)
73+
6174
ConstClass.__name__ = cls.__name__
6275
ConstClass.__module__ = cls.__module__
6376

test/test_const_class.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,3 +198,45 @@ def _initialize():
198198
util.assert_does_not_throw(_initialize)
199199
assert const_instance.x == x_value
200200
assert const_instance.s == str(x_value)
201+
202+
203+
def test_new_with_kwargs():
204+
@const_class(with_kwargs=True)
205+
class ConstClassWithKwargs:
206+
x: int
207+
s: str
208+
209+
def __eq__(self, other: object) -> bool:
210+
return isinstance(other, self.__class__) and other.x == self.x and other.s == self.s
211+
212+
const_instance = ConstClassWithKwargs(**ATTR_VALS_1)
213+
214+
# should create an exact copy by default
215+
const_instance_new_default = const_instance.new()
216+
assert const_instance_new_default == const_instance
217+
218+
const_instance_new = const_instance.new(x=ATTR_VALS_2[X_ATTR_NAME])
219+
assert isinstance(const_instance_new, ConstClassWithKwargs)
220+
assert const_instance_new.s == const_instance.s
221+
assert const_instance_new.x == ATTR_VALS_2[X_ATTR_NAME]
222+
223+
224+
def test_new_with_args():
225+
@const_class(with_kwargs=False)
226+
class ConstClassWithKwargs:
227+
x: int
228+
s: str
229+
230+
def __eq__(self, other: object) -> bool:
231+
return isinstance(other, self.__class__) and other.x == self.x and other.s == self.s
232+
233+
const_instance = ConstClassWithKwargs(*(ATTR_VALS_1.values()))
234+
235+
# should create an exact copy by default
236+
const_instance_new_default = const_instance.new()
237+
assert const_instance_new_default == const_instance
238+
239+
const_instance_new = const_instance.new(x=ATTR_VALS_2[X_ATTR_NAME])
240+
assert isinstance(const_instance_new, ConstClassWithKwargs)
241+
assert const_instance_new.s == const_instance.s
242+
assert const_instance_new.x == ATTR_VALS_2[X_ATTR_NAME]

0 commit comments

Comments
 (0)