Skip to content

Commit cade8e3

Browse files
committed
add __getattr__ to pass unknown attributes to numpy
1 parent 8112796 commit cade8e3

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

DynamicVector/DynamicVector.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -881,6 +881,33 @@ def __setitem__(self, index, value):
881881

882882
self._data[: self._size][index] = value
883883

884+
def __getattr__(self, name):
885+
"""
886+
Handles unknown attributes by forwarding them to the NumPy.ndarray that holds the vector.
887+
This allows the DynamicVector to support NumPy attributes such as `shape`, `dtype`, etc.
888+
889+
Parameters:
890+
name (str): The name of the missing attribute.
891+
892+
Returns:
893+
The value of the attribute from `self.view`.
894+
895+
Raises:
896+
AttributeError: If the attribute does not exist in `self` or `self.view`.
897+
"""
898+
try:
899+
# Forward any unknown attribute to the NumPy component
900+
attr = getattr(self._data[: self._size], name) # self.view = self._data[: self._size]
901+
if callable(attr):
902+
903+
def method(*args, **kwargs):
904+
return attr(*args, **kwargs)
905+
906+
return method
907+
return attr
908+
except AttributeError:
909+
raise AttributeError(f"'DynamicVector' object has no attribute '{name}'")
910+
884911
def __len__(self) -> int:
885912
return self._size
886913

0 commit comments

Comments
 (0)