Skip to content

Commit

Permalink
add dataclass_nested_eq decorator (#378)
Browse files Browse the repository at this point in the history
* add `dataclass_nested_eq` decorator

* decorate SpatialData with `dataclass_nested_eq`

* update CHANGELOG.md

* docstring

* formatting
  • Loading branch information
CagtayFabry authored Jun 22, 2021
1 parent f2dcc43 commit 713a8e0
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
- added `WeldxFile` wrapper to handle asdf files with history and schemas more
easily. [[#341]](https://github.com/BAMWelDX/weldx/pull/341).
- add `"step"` as additional method to `util.xr_interp_like` [[#363]](https://github.com/BAMWelDX/weldx/pull/363)
- add `util.compare_nested_eq` decorator for dataclasses with array-like
fields [[#378]](https://github.com/BAMWelDX/weldx/pull/378)

### changes

Expand Down
1 change: 1 addition & 0 deletions weldx/geometry.py
Original file line number Diff line number Diff line change
Expand Up @@ -2294,6 +2294,7 @@ def spatial_data(
# SpatialData --------------------------------------------------------------------------


@ut.dataclass_nested_eq
@dataclass
class SpatialData:
"""Represent 3D point cloud data with optional triangulation.
Expand Down
42 changes: 42 additions & 0 deletions weldx/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,48 @@ def inner_decorator(
return inner_decorator


def dataclass_nested_eq(original_class):
"""Set class :code:`__eq__` using :code:`util.compare_nested` on :code:`__dict__`.
Useful for implementing :code:`__eq__` on classes
created with :code:`@dataclass` decorator.
Parameters
----------
original_class:
original class to decorate
Returns
-------
type
The class with overridden :code:`__eq__` function.
Examples
--------
A simple dataclass could look like this::
@dataclass_nested_eq
@dataclass
class A:
a: np.ndarray
a = A(np.arange(3))
b = A(np.arange(3))
assert a==b
"""

def new_eq(self, other):
if not isinstance(other, type(self)):
return False

return compare_nested(self.__dict__, other.__dict__)

# set new eq function
original_class.__eq__ = new_eq # Set the class' __eq__ to the new one
return original_class


def _clean_notebook(file: Union[str, Path]): # pragma: no cover
"""Clean ID metadata, output and execution count from jupyter notebook cells.
Expand Down

0 comments on commit 713a8e0

Please sign in to comment.