MCPcopy Create free account
hub / github.com/numpy/numpy / test_0d_object_subclass

Method test_0d_object_subclass

numpy/core/tests/test_arrayprint.py:61–121  ·  view source on GitHub ↗
(self)

Source from the content-addressed store, hash-verified

59 assert_equal(str(x), '[None sub([None, None], dtype=object)]')
60
61 def test_0d_object_subclass(self):
62 # make sure that subclasses which return 0ds instead
63 # of scalars don't cause infinite recursion in str
64 class sub(np.ndarray):
65 def __new__(cls, inp):
66 obj = np.asarray(inp).view(cls)
67 return obj
68
69 def __getitem__(self, ind):
70 ret = super().__getitem__(ind)
71 return sub(ret)
72
73 x = sub(1)
74 assert_equal(repr(x), 'sub(1)')
75 assert_equal(str(x), '1')
76
77 x = sub([1, 1])
78 assert_equal(repr(x), 'sub([1, 1])')
79 assert_equal(str(x), '[1 1]')
80
81 # check it works properly with object arrays too
82 x = sub(None)
83 assert_equal(repr(x), 'sub(None, dtype=object)')
84 assert_equal(str(x), 'None')
85
86 # plus recursive object arrays (even depth > 1)
87 y = sub(None)
88 x[()] = y
89 y[()] = x
90 assert_equal(repr(x),
91 'sub(sub(sub(..., dtype=object), dtype=object), dtype=object)')
92 assert_equal(str(x), '...')
93 x[()] = 0 # resolve circular references for garbage collector
94
95 # nested 0d-subclass-object
96 x = sub(None)
97 x[()] = sub(None)
98 assert_equal(repr(x), 'sub(sub(None, dtype=object), dtype=object)')
99 assert_equal(str(x), 'None')
100
101 # gh-10663
102 class DuckCounter(np.ndarray):
103 def __getitem__(self, item):
104 result = super().__getitem__(item)
105 if not isinstance(result, DuckCounter):
106 result = result[...].view(DuckCounter)
107 return result
108
109 def to_string(self):
110 return {0: 'zero', 1: 'one', 2: 'two'}.get(self.item(), 'many')
111
112 def __str__(self):
113 if self.shape == ():
114 return self.to_string()
115 else:
116 fmt = {'all': lambda x: x.to_string()}
117 return np.array2string(self, formatter=fmt)
118

Callers

nothing calls this directly

Calls 3

assert_equalFunction · 0.90
subClass · 0.70
viewMethod · 0.45

Tested by

no test coverage detected