|
1 | 1 | import numpy as np
|
2 | 2 |
|
3 | 3 |
|
4 |
| -def test_fast_return(): |
5 |
| - """""" |
6 |
| - a = np.array([1, 2, 3], dtype='i') |
7 |
| - assert np.asarray(a) is a |
8 |
| - assert np.asarray(a, dtype='i') is a |
9 |
| - # This may produce a new view or a copy, but is never the same object. |
10 |
| - assert np.asarray(a, dtype='l') is not a |
| 4 | +def test_dtype_identity(): |
| 5 | + """Confirm the intended behavior for ``asarray`` results. |
11 | 6 |
|
| 7 | + The result of ``asarray()`` should have the dtype provided through the |
| 8 | + keyword argument, when used. This forces unique array handles to be |
| 9 | + produced for unique np.dtype objects, but (for equivalent dtypes), the |
| 10 | + underlying data (the base object) is shared with the original array object. |
| 11 | +
|
| 12 | + Ref https://github.com/numpy/numpy/issues/1468 |
| 13 | + """ |
| 14 | + int_array = np.array([1, 2, 3], dtype='i') |
| 15 | + assert np.asarray(int_array) is int_array |
| 16 | + |
| 17 | + # The character code resolves to the singleton dtype object provided |
| 18 | + # by the numpy package. |
| 19 | + assert np.asarray(int_array, dtype='i') is int_array |
| 20 | + |
| 21 | + # Derive a dtype from n.dtype('i'), but add a metadata object to force |
| 22 | + # the dtype to be distinct. |
12 | 23 | unequal_type = np.dtype('i', metadata={'spam': True})
|
13 |
| - b = np.asarray(a, dtype=unequal_type) |
14 |
| - assert b is not a |
15 |
| - assert b.base is a |
| 24 | + annotated_int_array = np.asarray(int_array, dtype=unequal_type) |
| 25 | + assert annotated_int_array is not int_array |
| 26 | + assert annotated_int_array.base is int_array |
| 27 | + |
| 28 | + # These ``asarray()`` calls may produce a new view or a copy, |
| 29 | + # but never the same object. |
| 30 | + long_int_array = np.asarray(int_array, dtype='l') |
| 31 | + assert long_int_array is not int_array |
| 32 | + assert np.asarray(int_array, dtype='q') is not int_array |
| 33 | + assert np.asarray(long_int_array, dtype='q') is not long_int_array |
| 34 | + assert np.asarray(int_array, dtype='l') is not np.asarray(int_array, dtype='l') |
| 35 | + assert np.asarray(int_array, dtype='l').base is np.asarray(int_array, dtype='l').base |
16 | 36 |
|
17 | 37 | equivalent_requirement = np.dtype('i', metadata={'spam': True})
|
18 |
| - c = np.asarray(b, dtype=equivalent_requirement) |
| 38 | + annotated_int_array_alt = np.asarray(annotated_int_array, dtype=equivalent_requirement) |
19 | 39 | # The descriptors are equivalent, but we have created
|
20 | 40 | # distinct dtype instances.
|
21 | 41 | assert unequal_type == equivalent_requirement
|
22 | 42 | assert unequal_type is not equivalent_requirement
|
23 |
| - assert c is not b |
24 |
| - assert c.dtype is equivalent_requirement |
| 43 | + assert annotated_int_array_alt is not annotated_int_array |
| 44 | + assert annotated_int_array_alt.dtype is equivalent_requirement |
0 commit comments