Last active
June 17, 2021 21:20
-
-
Save yoniLavi/3e7517c6e27ee17f2c6befaaa76acf6e to your computer and use it in GitHub Desktop.
A numpy array that supports addition of different types
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import numpy as np | |
| class AdditiveHeterogenousArray(np.lib.mixins.NDArrayOperatorsMixin): | |
| """A numpy array that supports addition of different types""" | |
| def __init__(self, *args, **kwargs): | |
| self.array = np.array(*args, **kwargs) | |
| def __repr__(self): | |
| return f'{self.__class__.__name__}({self.array.__repr__()})' | |
| def __getattr__(self, name): | |
| return getattr(self.array, name) | |
| def __getitem__(self, name): | |
| return self.array[name] | |
| def __array__(self): | |
| return self.array | |
| def __iadd__(self, other): | |
| if self.array.dtype.names is None: | |
| self.array.__iadd__(other) | |
| else: | |
| for field in self.array.dtype.names: | |
| self.array[field] += other[field] | |
| return self | |
| def __add__(self, other): | |
| if self.dtype.names is None: | |
| return self.__class__(self.array.__add__(other)) | |
| output = self.array.copy() | |
| for field in output.dtype.names: | |
| output[field] += other[field] | |
| return self.__class__(output) | |
| if __name__ == "__main__": | |
| a = AdditiveHeterogenousArray(np.array([(1, 2.0, False)], dtype=[('a', 'i4'), ('b', 'f4'), ('c', 'bool')])) | |
| b = AdditiveHeterogenousArray(np.array([(2, 4.5, True)], dtype=[('a', 'i4'), ('b', 'f4'), ('c', 'bool')])) | |
| c = AdditiveHeterogenousArray(np.array([(3, -1, False)], dtype=[('a', 'i4'), ('b', 'f4'), ('c', 'bool')])) | |
| d = AdditiveHeterogenousArray(np.array([(4, 11, True)], dtype=[('a', 'i4'), ('b', 'f4'), ('c', 'bool')])) | |
| print(a + b + c + d) | |
| a += b | |
| a += c | |
| a += d | |
| print(a) # same as above |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment