Skip to content

Commit 513c00b

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 e1774f6 commit 513c00b

File tree

1 file changed

+12
-2
lines changed

1 file changed

+12
-2
lines changed

examples/units/basic_units.py

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -120,8 +120,13 @@ def __new__(cls, value, unit):
120120
# generate a new subclass for value
121121
value_class = type(value)
122122
try:
123+
methods = {}
124+
if hasattr(value_class, '__getitem__'):
125+
# Only implement `__getitem__` if the wrapped class implements
126+
# it as well.
127+
methods['__getitem__'] = cls._getitem
123128
subcls = type(f'TaggedValue_of_{value_class.__name__}',
124-
(cls, value_class), {})
129+
(cls, value_class), methods)
125130
return object.__new__(subcls)
126131
except TypeError:
127132
return object.__new__(cls)
@@ -154,7 +159,12 @@ def __str__(self):
154159
def __len__(self):
155160
return len(self.value)
156161

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

160170
def __iter__(self):

0 commit comments

Comments
 (0)