Skip to content

Commit 3a261ca

Browse files
committed
Update Numpy type hints.
1 parent c811aa8 commit 3a261ca

File tree

15 files changed

+55
-51
lines changed

15 files changed

+55
-51
lines changed

examples/samples_tcod.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
import sys
1515
import time
1616
import warnings
17-
from typing import List
17+
from typing import Any, List
1818

1919
import numpy as np
2020
import tcod
@@ -101,14 +101,14 @@ class TrueColorSample(Sample):
101101
def __init__(self) -> None:
102102
self.name = "True colors"
103103
# corner colors
104-
self.colors = np.array(
104+
self.colors: NDArray[np.int16] = np.array(
105105
[(50, 40, 150), (240, 85, 5), (50, 35, 240), (10, 200, 130)],
106106
dtype=np.int16,
107107
)
108108
# color shift direction
109-
self.slide_dir = np.array([[1, 1, 1], [-1, -1, 1], [1, -1, 1], [1, 1, -1]], dtype=np.int16)
109+
self.slide_dir: NDArray[np.int16] = np.array([[1, 1, 1], [-1, -1, 1], [1, -1, 1], [1, 1, -1]], dtype=np.int16)
110110
# corner indexes
111-
self.corners = np.array([0, 1, 2, 3])
111+
self.corners: NDArray[np.int16] = np.array([0, 1, 2, 3], dtype=np.int16)
112112

113113
def on_draw(self) -> None:
114114
self.slide_corner_colors()
@@ -509,7 +509,7 @@ def ev_keydown(self, event: tcod.event.KeyDown) -> None:
509509
"##############################################",
510510
]
511511

512-
SAMPLE_MAP = np.array([list(line) for line in SAMPLE_MAP_]).transpose()
512+
SAMPLE_MAP: NDArray[Any] = np.array([list(line) for line in SAMPLE_MAP_]).transpose()
513513

514514
FOV_ALGO_NAMES = [
515515
"BASIC ",
@@ -545,17 +545,17 @@ def __init__(self) -> None:
545545

546546
map_shape = (SAMPLE_SCREEN_WIDTH, SAMPLE_SCREEN_HEIGHT)
547547

548-
self.walkable = np.zeros(map_shape, dtype=bool, order="F")
548+
self.walkable: NDArray[np.bool_] = np.zeros(map_shape, dtype=bool, order="F")
549549
self.walkable[:] = SAMPLE_MAP[:] == " "
550550

551-
self.transparent = np.zeros(map_shape, dtype=bool, order="F")
551+
self.transparent: NDArray[np.bool_] = np.zeros(map_shape, dtype=bool, order="F")
552552
self.transparent[:] = self.walkable[:] | (SAMPLE_MAP == "=")
553553

554554
# Lit background colors for the map.
555-
self.light_map_bg = np.full(SAMPLE_MAP.shape, LIGHT_GROUND, dtype="3B")
555+
self.light_map_bg: NDArray[np.uint8] = np.full(SAMPLE_MAP.shape, LIGHT_GROUND, dtype="3B")
556556
self.light_map_bg[SAMPLE_MAP[:] == "#"] = LIGHT_WALL
557557
# Dark background colors for the map.
558-
self.dark_map_bg = np.full(SAMPLE_MAP.shape, DARK_GROUND, dtype="3B")
558+
self.dark_map_bg: NDArray[np.uint8] = np.full(SAMPLE_MAP.shape, DARK_GROUND, dtype="3B")
559559
self.dark_map_bg[SAMPLE_MAP[:] == "#"] = DARK_WALL
560560

561561
def draw_ui(self) -> None:
@@ -948,7 +948,7 @@ class BSPSample(Sample):
948948
def __init__(self) -> None:
949949
self.name = "Bsp toolkit"
950950
self.bsp = tcod.bsp.BSP(1, 1, SAMPLE_SCREEN_WIDTH - 1, SAMPLE_SCREEN_HEIGHT - 1)
951-
self.bsp_map = np.zeros((SAMPLE_SCREEN_WIDTH, SAMPLE_SCREEN_HEIGHT), dtype=bool, order="F")
951+
self.bsp_map: NDArray[np.bool_] = np.zeros((SAMPLE_SCREEN_WIDTH, SAMPLE_SCREEN_HEIGHT), dtype=bool, order="F")
952952
self.bsp_generate()
953953

954954
def bsp_generate(self) -> None:
@@ -1214,7 +1214,7 @@ def ev_keydown(self, event: tcod.event.KeyDown) -> None:
12141214
# xc = [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
12151215
# yc = [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]
12161216
if numpy_available:
1217-
(xc, yc) = np.meshgrid(range(SCREEN_W), range(SCREEN_H)) # type: ignore
1217+
(xc, yc) = np.meshgrid(range(SCREEN_W), range(SCREEN_H))
12181218
# translate coordinates of all pixels to center
12191219
xc = xc - HALF_W
12201220
yc = yc - HALF_H

examples/ttf.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import freetype # type: ignore # pip install freetype-py
1414
import numpy as np
1515
import tcod
16+
from numpy.typing import NDArray
1617

1718
FONT = "VeraMono.ttf"
1819

@@ -36,10 +37,10 @@ def load_ttf(path: str, size: Tuple[int, int]) -> tcod.tileset.Tileset:
3637
ttf.load_glyph(glyph_index)
3738
bitmap = ttf.glyph.bitmap
3839
assert bitmap.pixel_mode == freetype.FT_PIXEL_MODE_GRAY
39-
bitmap_array = np.asarray(bitmap.buffer).reshape((bitmap.width, bitmap.rows), order="F")
40+
bitmap_array: NDArray[np.uint8] = np.asarray(bitmap.buffer).reshape((bitmap.width, bitmap.rows), order="F")
4041
if bitmap_array.size == 0:
4142
continue # Skip blank glyphs.
42-
output_image = np.zeros(size, dtype=np.uint8, order="F")
43+
output_image: NDArray[np.uint8] = np.zeros(size, dtype=np.uint8, order="F")
4344
out_slice = output_image
4445

4546
# Adjust the position to center this glyph on the tile.

tcod/_internal.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from typing import Any, AnyStr, Callable, TypeVar, cast
88

99
import numpy as np
10+
from numpy.typing import NDArray
1011
from typing_extensions import Literal, NoReturn
1112

1213
from tcod.loader import ffi, lib
@@ -225,7 +226,7 @@ class TempImage(object):
225226
"""An Image-like container for NumPy arrays."""
226227

227228
def __init__(self, array: Any):
228-
self._array = np.ascontiguousarray(array, dtype=np.uint8)
229+
self._array: NDArray[np.uint8] = np.ascontiguousarray(array, dtype=np.uint8)
229230
height, width, depth = self._array.shape
230231
if depth != 3:
231232
raise TypeError("Array must have RGB channels. Shape is: %r" % (self._array.shape,))

tcod/console.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ def __init__(
124124
if buffer is not None:
125125
if self._order == "F":
126126
buffer = buffer.transpose()
127-
self._tiles = np.ascontiguousarray(buffer, self.DTYPE)
127+
self._tiles: NDArray[Any] = np.ascontiguousarray(buffer, self.DTYPE)
128128
else:
129129
self._tiles = np.ndarray((height, width), dtype=self.DTYPE)
130130

tcod/event.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1091,8 +1091,8 @@ def get_keyboard_state() -> NDArray[np.bool_]:
10911091
"""
10921092
numkeys = ffi.new("int[1]")
10931093
keyboard_state = lib.SDL_GetKeyboardState(numkeys)
1094-
out: NDArray[np.bool_] = np.frombuffer(ffi.buffer(keyboard_state[0 : numkeys[0]]), dtype=np.bool_) # type: ignore
1095-
out.flags["WRITEABLE"] = False # This buffer is supposed to be const.
1094+
out: NDArray[np.bool_] = np.frombuffer(ffi.buffer(keyboard_state[0 : numkeys[0]]), dtype=np.bool_)
1095+
out.flags["WRITEABLE"] = False # type: ignore[index] # This buffer is supposed to be const.
10961096
return out
10971097

10981098

tcod/image.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from typing import Any, Dict, Tuple, Union
1212

1313
import numpy as np
14-
from numpy.typing import NDArray
14+
from numpy.typing import ArrayLike, NDArray
1515

1616
import tcod.console
1717
from tcod._internal import _console, deprecate
@@ -41,7 +41,7 @@ def _from_cdata(cls, cdata: Any) -> Image:
4141
return self
4242

4343
@classmethod
44-
def from_array(cls, array: Any) -> Image:
44+
def from_array(cls, array: ArrayLike) -> Image:
4545
"""Create a new Image from a copy of an array-like object.
4646
4747
Example:
@@ -52,10 +52,10 @@ def from_array(cls, array: Any) -> Image:
5252
5353
.. versionadded:: 11.4
5454
"""
55-
array = np.asarray(array)
55+
array = np.asarray(array, dtype=np.uint8)
5656
height, width, depth = array.shape
5757
image = cls(width, height)
58-
image_array = np.asarray(image)
58+
image_array: NDArray[np.uint8] = np.asarray(image)
5959
image_array[...] = array
6060
return image
6161

@@ -349,7 +349,7 @@ def load(filename: Union[str, PathLike[str]]) -> NDArray[np.uint8]:
349349
array: NDArray[np.uint8] = np.asarray(image, dtype=np.uint8)
350350
height, width, depth = array.shape
351351
if depth == 3:
352-
array = np.concatenate( # type: ignore
352+
array = np.concatenate(
353353
(
354354
array,
355355
np.full((height, width, 1), fill_value=255, dtype=np.uint8),

tcod/libtcodpy.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2305,7 +2305,7 @@ def _heightmap_cdata(array: NDArray[np.float32]) -> ffi.CData:
23052305
array = array.transpose()
23062306
if not array.flags["C_CONTIGUOUS"]:
23072307
raise ValueError("array must be a contiguous segment.")
2308-
if array.dtype != np.float32: # type: ignore
2308+
if array.dtype != np.float32:
23092309
raise ValueError("array dtype must be float32, not %r" % array.dtype)
23102310
height, width = array.shape
23112311
pointer = ffi.from_buffer("float *", array)

tcod/map.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ def __init__(
8787
self.height = height
8888
self._order = tcod._internal.verify_order(order)
8989

90-
self.__buffer = np.zeros((height, width, 3), dtype=np.bool_)
90+
self.__buffer: NDArray[np.bool_] = np.zeros((height, width, 3), dtype=np.bool_)
9191
self.map_c = self.__as_cdata()
9292

9393
def __as_cdata(self) -> Any:
@@ -251,7 +251,7 @@ def compute_fov(
251251
RuntimeWarning,
252252
stacklevel=2,
253253
)
254-
map_buffer = np.empty(
254+
map_buffer: NDArray[np.bool_] = np.empty(
255255
transparency.shape,
256256
dtype=[("transparent", bool), ("walkable", bool), ("fov", bool)],
257257
)

tcod/noise.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@
3838

3939
import enum
4040
import warnings
41-
from typing import Any, Optional, Sequence, Tuple, Union
41+
from typing import Any, List, Optional, Sequence, Tuple, Union
4242

4343
import numpy as np
4444
from numpy.typing import ArrayLike, NDArray
@@ -245,15 +245,15 @@ def __getitem__(self, indexes: Any) -> NDArray[np.float32]:
245245
raise IndexError(
246246
"This noise generator has %i dimensions, but was indexed with %i." % (self.dimensions, len(indexes))
247247
)
248-
indexes = np.broadcast_arrays(*indexes) # type: ignore
248+
indexes = np.broadcast_arrays(*indexes)
249249
c_input = [ffi.NULL, ffi.NULL, ffi.NULL, ffi.NULL]
250250
for i, index in enumerate(indexes):
251251
if index.dtype.type == np.object_:
252252
raise TypeError("Index arrays can not be of dtype np.object_.")
253253
indexes[i] = np.ascontiguousarray(index, dtype=np.float32)
254254
c_input[i] = ffi.from_buffer("float*", indexes[i])
255255

256-
out = np.empty(indexes[0].shape, dtype=np.float32)
256+
out: NDArray[np.float32] = np.empty(indexes[0].shape, dtype=np.float32)
257257
if self.implementation == Implementation.SIMPLE:
258258
lib.TCOD_noise_get_vectorized(
259259
self.noise_c,
@@ -332,7 +332,7 @@ def sample_ogrid(self, ogrid: Sequence[ArrayLike]) -> NDArray[np.float32]:
332332
"""
333333
if len(ogrid) != self.dimensions:
334334
raise ValueError("len(ogrid) must equal self.dimensions, " "%r != %r" % (len(ogrid), self.dimensions))
335-
ogrids = [np.ascontiguousarray(array, np.float32) for array in ogrid]
335+
ogrids: List[NDArray[np.float32]] = [np.ascontiguousarray(array, np.float32) for array in ogrid]
336336
out: np.ndarray[Any, np.dtype[np.float32]] = np.ndarray([array.size for array in ogrids], np.float32)
337337
lib.NoiseSampleOpenMeshGrid(
338338
self._tdl_noise_c,
@@ -461,4 +461,4 @@ def grid(
461461
if len(shape) != len(origin):
462462
raise TypeError("shape must have the same length as origin")
463463
indexes = (np.arange(i_shape) * i_scale + i_origin for i_shape, i_scale, i_origin in zip(shape, scale, origin))
464-
return tuple(np.meshgrid(*indexes, copy=False, sparse=True, indexing=indexing)) # type: ignore
464+
return tuple(np.meshgrid(*indexes, copy=False, sparse=True, indexing=indexing))

tcod/path.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -473,7 +473,7 @@ def dijkstra2d(
473473
.. versionchanged:: 12.1
474474
Added `out` parameter. Now returns the output array.
475475
"""
476-
dist = np.asarray(distance)
476+
dist: NDArray[Any] = np.asarray(distance)
477477
if out is ...: # type: ignore
478478
out = dist
479479
warnings.warn(
@@ -560,7 +560,7 @@ def hillclimb2d(
560560
Added `edge_map` parameter.
561561
"""
562562
x, y = start
563-
dist = np.asarray(distance)
563+
dist: NDArray[Any] = np.asarray(distance)
564564
if not (0 <= x < dist.shape[0] and 0 <= y < dist.shape[1]):
565565
raise IndexError("Starting point %r not in shape %r" % (start, dist.shape))
566566
c_dist = _export(dist)
@@ -582,7 +582,7 @@ def _world_array(shape: Tuple[int, ...], dtype: Any = np.int32) -> NDArray[Any]:
582582
"""Return an array where ``ij == arr[ij]``."""
583583
return np.ascontiguousarray(
584584
np.transpose(
585-
np.meshgrid( # type: ignore
585+
np.meshgrid(
586586
*(np.arange(i, dtype=dtype) for i in shape),
587587
indexing="ij",
588588
copy=False,

0 commit comments

Comments
 (0)