Skip to content

Commit dc89aba

Browse files
committed
DOC: Only implement __getitem__ if the wrapped class implements it.
For example, this will be added for ndarray, but not float. Otherwise, NumPy will treat float TaggedValue's as arrays when they aren't.
1 parent 99f05a4 commit dc89aba

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

examples/units/basic_units.py

+10-1
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,10 @@ def __new__(cls, value, unit):
122122
try:
123123
subcls = type(f'TaggedValue_of_{value_class.__name__}',
124124
(cls, value_class), {})
125+
if hasattr(value_class, '__getitem__'):
126+
# Only implement `__getitem__` if the wrapped class implements
127+
# it as well.
128+
subcls.__getitem__ = subcls._getitem
125129
return object.__new__(subcls)
126130
except TypeError:
127131
return object.__new__(cls)
@@ -154,7 +158,12 @@ def __str__(self):
154158
def __len__(self):
155159
return len(self.value)
156160

157-
def __getitem__(self, key):
161+
def _getitem(self, key):
162+
# This implements `__getitem__`, but with a different name. This will
163+
# be renamed on subclasses that wrap values that would have a
164+
# `__getitem__` implementation (e.g., ndarray, but not float).
165+
# Otherwise, NumPy will treat float TaggedValue's as arrays when they
166+
# aren't.
158167
return TaggedValue(self.value[key], self.unit)
159168

160169
def __iter__(self):

0 commit comments

Comments
 (0)