Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add convenience method to deepcopy a state #86

Merged
merged 1 commit into from
Aug 9, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions src/autora/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,53 @@ def update(self, **kwargs):
"""
return self + Delta(**kwargs)

def copy(self):
"""
Return a deepcopy of the State
Examples:
>>> @dataclass(frozen=True)
... class DfState(State):
... q: pd.DataFrame = field(default_factory=pd.DataFrame,
... metadata={"delta": "replace",
... "converter": pd.DataFrame})
>>> data = pd.DataFrame({'x': [1, 2, 3]})
>>> s_1 = DfState(q=data)
>>> s_replace = replace(s_1)
>>> s_copy = s_1.copy()

The build in replace method doesn't create a deepcopy:
>>> s_1.q is s_replace.q
True
>>> s_1.q['y'] = [1,2,3]
>>> s_replace.q
x y
0 1 1
1 2 2
2 3 3

But this copy method does:
>>> s_1.q is s_copy.q
False
>>> s_copy.q
x
0 1
1 2
2 3


"""
# Create a dictionary to hold the field copies
field_copies = {}

# Iterate over all fields of the class
for _field in fields(self):
value = getattr(self, _field.name)
# Use deepcopy to ensure that mutable fields are also copied
field_copies[_field.name] = copy.deepcopy(value)

# Use replace with **field_copies to create a new instance of the same class
return replace(self, **field_copies)


def _get_value(f, other: Union[Delta, Mapping]):
"""
Expand Down
Loading