Skip to content
This repository was archived by the owner on Jun 10, 2020. It is now read-only.

Commit 45586ae

Browse files
authored
MAINT: broaden allowed lists in _DtypeLike (#43)
Closes #42. `np.dtype` accepts a wide variety of lists as dtypes, some examples include: - `[('R', 'u1'), ('G', np.unicode_, 1)]` - `[('R', 'u1', (2, 2)), ('G', np.unicode_, 1)]` Without further hints mypy is going to type those as `List[object]`, so precise hints will require that users add annotations. In addition, typing the above is challenging because the inputs have to be a list, which is invariant, so you can't use `Union`s inside the list to reduce the number of cases. Work around that by just accepting `List[Any]`.
1 parent f3c6315 commit 45586ae

File tree

2 files changed

+25
-9
lines changed

2 files changed

+25
-9
lines changed

numpy-stubs/__init__.pyi

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -56,12 +56,11 @@ _DtypeLike = Union[
5656
# (fixed_dtype, shape)
5757
Tuple[_DtypeLikeNested, _ShapeLike],
5858
# [(field_name, field_dtype, field_shape), ...]
59-
List[
60-
Union[
61-
Tuple[Union[str, Tuple[str, str]], _DtypeLikeNested],
62-
Tuple[Union[str, Tuple[str, str]], _DtypeLikeNested, _ShapeLike],
63-
]
64-
],
59+
#
60+
# The type here is quite broad because NumPy accepts quite a wide
61+
# range of inputs inside the list; see the tests for some
62+
# examples.
63+
List[Any],
6564
# {'names': ..., 'formats': ..., 'offsets': ..., 'titles': ...,
6665
# 'itemsize': ...}
6766
# TODO: use TypedDict when/if it's officially supported

tests/pass/simple.py

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,26 @@ def ndarray_func(x):
2525
np.dtype(np.dtype(float))
2626
np.dtype(('U', 10))
2727
np.dtype((np.int32, (2, 2)))
28-
np.dtype([('R', 'u1'), ('G', 'u1'), ('B', 'u1')])
29-
np.dtype([('R', 'u1', 1)])
30-
np.dtype([('R', 'u1', (2, 2))])
28+
# Define the arguments on the previous line to prevent bidirectional
29+
# type inference in mypy from broadening the types.
30+
two_tuples_dtype = [('R', 'u1'), ('G', 'u1'), ('B', 'u1')]
31+
np.dtype(two_tuples_dtype)
32+
33+
three_tuples_dtype = [('R', 'u1', 1)]
34+
np.dtype(three_tuples_dtype)
35+
36+
mixed_tuples_dtype = [('R', 'u1'), ('G', np.unicode_, 1)]
37+
np.dtype(mixed_tuples_dtype)
38+
39+
shape_tuple_dtype = [('R', 'u1', (2, 2))]
40+
np.dtype(shape_tuple_dtype)
41+
42+
shape_like_dtype = [('R', 'u1', (2, 2)), ('G', np.unicode_, 1)]
43+
np.dtype(shape_like_dtype)
44+
45+
object_dtype = [('field1', object)]
46+
np.dtype(object_dtype)
47+
3148
np.dtype({'col1': ('U10', 0), 'col2': ('float32', 10)})
3249
np.dtype((np.int32, {'real': (np.int16, 0), 'imag': (np.int16, 2)}))
3350
np.dtype((np.int32, (np.int8, 4)))

0 commit comments

Comments
 (0)