Skip to content

Commit

Permalink
Merge branch 'main' into 83-add-alias-for-x-and-y-in-standardstate-as…
Browse files Browse the repository at this point in the history
…-pandas-dataframe
  • Loading branch information
younesStrittmatter authored Aug 9, 2024
2 parents c3f88ba + f107389 commit 7c1d704
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions src/autora/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,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

0 comments on commit 7c1d704

Please sign in to comment.