Skip to content

Commit 9304b6e

Browse files
committed
extended function osw.model.static.OswBaseModel.cast
1 parent 122b2a4 commit 9304b6e

1 file changed

Lines changed: 52 additions & 20 deletions

File tree

‎src/osw/model/static.py‎

Lines changed: 52 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
from typing import TYPE_CHECKING, Literal, Optional, Type, TypeVar, Union
66
from uuid import UUID
7+
from warnings import warn
78

89
from pydantic.v1 import BaseModel, Field, constr
910

@@ -84,7 +85,7 @@ def custom_isinstance(obj: Union[type, T], class_name: str) -> bool:
8485
class OswBaseModel(BaseModel):
8586

8687
class Config:
87-
# strict = False
88+
# strict = False
8889
# Additional fields are allowed
8990
validate_assignment = True
9091
# Ensures that the assignment of a value to a field is validated
@@ -123,30 +124,34 @@ def full_dict(self, **kwargs): # extent BaseClass export function
123124
# considered as discriminator
124125
return d
125126

126-
def cast(self, cls: Union[Type[T], type], **kwargs) -> T:
127+
def cast(
128+
self,
129+
cls: Union[Type[T], type],
130+
none_to_default: bool = False,
131+
remove_extra: bool = False,
132+
silent: bool = True,
133+
**kwargs,
134+
) -> T:
127135
"""Casting self into target class
128136
129137
Parameters
130138
----------
131-
cls
132-
target class
133-
kwargs
134-
additional attributes to be set
135-
139+
cls
140+
target class
141+
kwargs
142+
additional attributes to be set
143+
none_to_default
144+
If True, attributes that are None will be set to their default value
145+
remove_extra
146+
If True, extra attributes that are passed to the constructor are removed
147+
silent
148+
If True, no warnings are printed
136149
Returns
137150
-------
138151
instance of target class
139152
"""
140-
combined_args = {**self.dict(), **kwargs}
141-
del combined_args["type"]
142-
return cls(**combined_args)
143153

144-
def cast_none_to_default(self, cls: Union[Type[T], type], **kwargs) -> T:
145-
"""Casting self into target class. If the passed attribute is None or solely
146-
includes None values, the attribute is not passed to the instance of the
147-
target class, which will then fall back to the default."""
148-
149-
def test_if_empty_list_or_none(
154+
def empty_list_or_none(
150155
obj: Union[
151156
NoneType,
152157
list,
@@ -161,14 +166,41 @@ def test_if_empty_list_or_none(
161166
return True
162167
return False
163168

164-
self_args = {
165-
k: v for k, v in self.dict().items() if not test_if_empty_list_or_none(v)
166-
}
167-
combined_args = {**self_args, **kwargs}
169+
combined_args = {**self.dict(), **kwargs}
170+
none_args = []
171+
if none_to_default:
172+
reduced = {}
173+
for k, v in combined_args.items():
174+
if empty_list_or_none(v):
175+
none_args.append(k)
176+
else:
177+
reduced[k] = v
178+
combined_args = reduced
179+
extra_args = []
180+
if remove_extra:
181+
reduced = {}
182+
for k, v in combined_args.items():
183+
if k not in cls.__fields__.keys():
184+
extra_args.append(k)
185+
else:
186+
reduced[k] = v
187+
combined_args = reduced
188+
if not silent:
189+
if none_to_default and none_args:
190+
warn(f"Removed attributes with None or empty list values: {none_args}")
191+
if remove_extra and extra_args:
192+
warn(f"Removed extra attributes: {extra_args}")
168193
if "type" in combined_args:
169194
del combined_args["type"]
170195
return cls(**combined_args)
171196

197+
def cast_none_to_default(self, cls: Union[Type[T], type], **kwargs) -> T:
198+
"""Casting self into target class. If the passed attribute is None or solely
199+
includes None values, the attribute is not passed to the instance of the
200+
target class, which will then fall back to the default."""
201+
202+
return self.cast(cls, none_to_default=True, **kwargs)
203+
172204
def get_uuid(self) -> Union[str, UUID, NoneType]:
173205
"""Getter for the attribute 'uuid' of the entity
174206

0 commit comments

Comments
 (0)