Skip to content

Commit 4d9f28f

Browse files
committed
Update NumPy type hints.
1 parent 03676bb commit 4d9f28f

File tree

13 files changed

+148
-118
lines changed

13 files changed

+148
-118
lines changed

examples/cavegen.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,14 @@
66
This will print the result to the console, so be sure to run this from the
77
command line.
88
"""
9+
from typing import Any
10+
911
import numpy as np
1012
import scipy.signal # type: ignore
13+
from numpy.typing import NDArray
1114

1215

13-
def convolve(tiles: np.ndarray, wall_rule: int = 5) -> np.ndarray:
16+
def convolve(tiles: NDArray[Any], wall_rule: int = 5) -> NDArray[np.bool_]:
1417
"""Return the next step of the cave generation algorithm.
1518
1619
`tiles` is the input array. (0: wall, 1: floor)
@@ -19,12 +22,12 @@ def convolve(tiles: np.ndarray, wall_rule: int = 5) -> np.ndarray:
1922
walls then the tile will become a wall.
2023
"""
2124
# Use convolve2d, the 2nd input is a 3x3 ones array.
22-
neighbors: np.ndarray = scipy.signal.convolve2d(tiles == 0, [[1, 1, 1], [1, 1, 1], [1, 1, 1]], "same")
23-
next_tiles: np.ndarray = neighbors < wall_rule # Apply the wall rule.
25+
neighbors: NDArray[Any] = scipy.signal.convolve2d(tiles == 0, [[1, 1, 1], [1, 1, 1], [1, 1, 1]], "same")
26+
next_tiles: NDArray[np.bool_] = neighbors < wall_rule # Apply the wall rule.
2427
return next_tiles
2528

2629

27-
def show(tiles: np.ndarray) -> None:
30+
def show(tiles: NDArray[Any]) -> None:
2831
"""Print out the tiles of an array."""
2932
for line in tiles:
3033
print("".join("# "[int(cell)] for cell in line))
@@ -35,7 +38,7 @@ def show(tiles: np.ndarray) -> None:
3538
INITIAL_CHANCE = 0.45 # Initial wall chance.
3639
CONVOLVE_STEPS = 4
3740
# 0: wall, 1: floor
38-
tiles = np.random.random((HEIGHT, WIDTH)) > INITIAL_CHANCE
41+
tiles: NDArray[np.bool_] = np.random.random((HEIGHT, WIDTH)) > INITIAL_CHANCE
3942
for _ in range(CONVOLVE_STEPS):
4043
tiles = convolve(tiles)
4144
tiles[[0, -1], :] = 0 # Ensure surrounding wall.

examples/samples_tcod.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919
import numpy as np
2020
import tcod
21+
from numpy.typing import NDArray
2122

2223
if not sys.warnoptions:
2324
warnings.simplefilter("default") # Show all warnings.
@@ -839,51 +840,51 @@ def ev_mousemotion(self, event: tcod.event.MouseMotion) -> None:
839840

840841

841842
# draw a vertical line
842-
def vline(m: np.ndarray, x: int, y1: int, y2: int) -> None:
843+
def vline(m: NDArray[np.bool_], x: int, y1: int, y2: int) -> None:
843844
if y1 > y2:
844845
y1, y2 = y2, y1
845846
for y in range(y1, y2 + 1):
846847
m[x, y] = True
847848

848849

849850
# draw a vertical line up until we reach an empty space
850-
def vline_up(m: np.ndarray, x: int, y: int) -> None:
851+
def vline_up(m: NDArray[np.bool_], x: int, y: int) -> None:
851852
while y >= 0 and not m[x, y]:
852853
m[x, y] = True
853854
y -= 1
854855

855856

856857
# draw a vertical line down until we reach an empty space
857-
def vline_down(m: np.ndarray, x: int, y: int) -> None:
858+
def vline_down(m: NDArray[np.bool_], x: int, y: int) -> None:
858859
while y < SAMPLE_SCREEN_HEIGHT and not m[x, y]:
859860
m[x, y] = True
860861
y += 1
861862

862863

863864
# draw a horizontal line
864-
def hline(m: np.ndarray, x1: int, y: int, x2: int) -> None:
865+
def hline(m: NDArray[np.bool_], x1: int, y: int, x2: int) -> None:
865866
if x1 > x2:
866867
x1, x2 = x2, x1
867868
for x in range(x1, x2 + 1):
868869
m[x, y] = True
869870

870871

871872
# draw a horizontal line left until we reach an empty space
872-
def hline_left(m: np.ndarray, x: int, y: int) -> None:
873+
def hline_left(m: NDArray[np.bool_], x: int, y: int) -> None:
873874
while x >= 0 and not m[x, y]:
874875
m[x, y] = True
875876
x -= 1
876877

877878

878879
# draw a horizontal line right until we reach an empty space
879-
def hline_right(m: np.ndarray, x: int, y: int) -> None:
880+
def hline_right(m: NDArray[np.bool_], x: int, y: int) -> None:
880881
while x < SAMPLE_SCREEN_WIDTH and not m[x, y]:
881882
m[x, y] = True
882883
x += 1
883884

884885

885886
# the class building the dungeon from the bsp nodes
886-
def traverse_node(bsp_map: np.ndarray, node: tcod.bsp.BSP) -> None:
887+
def traverse_node(bsp_map: NDArray[np.bool_], node: tcod.bsp.BSP) -> None:
887888
if not node.children:
888889
# calculate the room size
889890
if bsp_room_walls:
@@ -1216,7 +1217,7 @@ def ev_keydown(self, event: tcod.event.KeyDown) -> None:
12161217
# xc = [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
12171218
# yc = [[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]]
12181219
if numpy_available:
1219-
(xc, yc) = np.meshgrid(range(SCREEN_W), range(SCREEN_H))
1220+
(xc, yc) = np.meshgrid(range(SCREEN_W), range(SCREEN_H)) # type: ignore
12201221
# translate coordinates of all pixels to center
12211222
xc = xc - HALF_W
12221223
yc = yc - HALF_H

tcod/console.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ def __init__(
110110
width: int,
111111
height: int,
112112
order: Literal["C", "F"] = "C",
113-
buffer: Optional[np.ndarray] = None,
113+
buffer: "Optional[np.ndarray[Any, Any]]" = None,
114114
):
115115
self._key_color = None # type: Optional[Tuple[int, int, int]]
116116
self._order = tcod._internal.verify_order(order)
@@ -181,7 +181,7 @@ def _init_setup_console_data(self, order: Literal["C", "F"] = "C") -> None:
181181
else:
182182
self._console_data = ffi.cast("struct TCOD_Console*", self.console_c)
183183

184-
self._tiles = np.frombuffer(
184+
self._tiles = np.frombuffer( # type: ignore
185185
ffi.buffer(self._console_data.tiles[0 : self.width * self.height]),
186186
dtype=self.DTYPE,
187187
).reshape((self.height, self.width))
@@ -199,7 +199,7 @@ def height(self) -> int:
199199
return lib.TCOD_console_get_height(self.console_c) # type: ignore
200200

201201
@property
202-
def bg(self) -> np.ndarray:
202+
def bg(self) -> "np.ndarray[Any, np.dtype[np.uint8]]":
203203
"""A uint8 array with the shape (height, width, 3).
204204
205205
You can change the consoles background colors by using this array.
@@ -208,27 +208,27 @@ def bg(self) -> np.ndarray:
208208
``console.bg[x, y, channel] # order='F'``.
209209
210210
"""
211-
bg = self._tiles["bg"][..., :3] # type: np.ndarray
211+
bg: np.ndarray[Any, np.dtype[np.uint8]] = self._tiles["bg"][..., :3]
212212
if self._order == "F":
213213
bg = bg.transpose(1, 0, 2)
214214
return bg
215215

216216
@property
217-
def fg(self) -> np.ndarray:
217+
def fg(self) -> "np.ndarray[Any, np.dtype[np.uint8]]":
218218
"""A uint8 array with the shape (height, width, 3).
219219
220220
You can change the consoles foreground colors by using this array.
221221
222222
Index this array with ``console.fg[i, j, channel] # order='C'`` or
223223
``console.fg[x, y, channel] # order='F'``.
224224
"""
225-
fg = self._tiles["fg"][..., :3] # type: np.ndarray
225+
fg: np.ndarray[Any, np.dtype[np.uint8]] = self._tiles["fg"][..., :3]
226226
if self._order == "F":
227227
fg = fg.transpose(1, 0, 2)
228228
return fg
229229

230230
@property
231-
def ch(self) -> np.ndarray:
231+
def ch(self) -> "np.ndarray[Any, np.dtype[np.intc]]":
232232
"""An integer array with the shape (height, width).
233233
234234
You can change the consoles character codes by using this array.
@@ -240,7 +240,7 @@ def ch(self) -> np.ndarray:
240240

241241
@property # type: ignore
242242
@deprecate("This attribute has been renamed to `rgba`.")
243-
def tiles(self) -> np.ndarray:
243+
def tiles(self) -> "np.ndarray[Any, Any]":
244244
"""An array of this consoles raw tile data.
245245
246246
This acts as a combination of the `ch`, `fg`, and `bg` attributes.
@@ -256,7 +256,7 @@ def tiles(self) -> np.ndarray:
256256

257257
@property # type: ignore
258258
@deprecate("This attribute has been renamed to `rgba`.")
259-
def buffer(self) -> np.ndarray:
259+
def buffer(self) -> "np.ndarray[Any, Any]":
260260
"""An array of this consoles raw tile data.
261261
262262
.. versionadded:: 11.4
@@ -268,7 +268,7 @@ def buffer(self) -> np.ndarray:
268268

269269
@property # type: ignore
270270
@deprecate("This attribute has been renamed to `rgb`.")
271-
def tiles_rgb(self) -> np.ndarray:
271+
def tiles_rgb(self) -> "np.ndarray[Any, Any]":
272272
"""An array of this consoles data without the alpha channel.
273273
274274
.. versionadded:: 11.8
@@ -280,7 +280,7 @@ def tiles_rgb(self) -> np.ndarray:
280280

281281
@property # type: ignore
282282
@deprecate("This attribute has been renamed to `rgb`.")
283-
def tiles2(self) -> np.ndarray:
283+
def tiles2(self) -> "np.ndarray[Any, Any]":
284284
"""This name is deprecated in favour of :any:`rgb`.
285285
286286
.. versionadded:: 11.3
@@ -291,7 +291,7 @@ def tiles2(self) -> np.ndarray:
291291
return self.rgb
292292

293293
@property
294-
def rgba(self) -> np.ndarray:
294+
def rgba(self) -> "np.ndarray[Any, Any]":
295295
"""An array of this consoles raw tile data.
296296
297297
The axes of this array is affected by the `order` parameter given to
@@ -312,7 +312,7 @@ def rgba(self) -> np.ndarray:
312312
return self._tiles.T if self._order == "F" else self._tiles
313313

314314
@property
315-
def rgb(self) -> np.ndarray:
315+
def rgb(self) -> "np.ndarray[Any, Any]":
316316
"""An array of this consoles data without the alpha channel.
317317
318318
The axes of this array is affected by the `order` parameter given to
@@ -888,13 +888,13 @@ def __getstate__(self) -> Any:
888888
"back": self.default_bg,
889889
}
890890
if self.console_c == ffi.NULL:
891-
state["_tiles"] = np.copy(self._tiles)
891+
state["_tiles"] = np.array(self._tiles, copy=True)
892892
return state
893893

894894
def __setstate__(self, state: Any) -> None:
895895
self._key_color = None
896896
if "_tiles" not in state:
897-
tiles = np.ndarray((self.height, self.width), dtype=self.DTYPE)
897+
tiles: np.ndarray[Any, Any] = np.ndarray((self.height, self.width), dtype=self.DTYPE)
898898
tiles["ch"] = state["_ch"]
899899
tiles["fg"][..., :3] = state["_fg"]
900900
tiles["fg"][..., 3] = 255

tcod/event.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1030,7 +1030,7 @@ def _pycall_event_watch(userdata: Any, sdl_event: Any) -> int:
10301030
return 0
10311031

10321032

1033-
def get_keyboard_state() -> np.ndarray:
1033+
def get_keyboard_state() -> "np.ndarray[Any, np.dtype[np.bool_]]":
10341034
"""Return a boolean array with the current keyboard state.
10351035
10361036
Index this array with a scancode. The value will be True if the key is
@@ -1052,7 +1052,7 @@ def get_keyboard_state() -> np.ndarray:
10521052
"""
10531053
numkeys = ffi.new("int[1]")
10541054
keyboard_state = lib.SDL_GetKeyboardState(numkeys)
1055-
out: np.ndarray = np.frombuffer(ffi.buffer(keyboard_state[0 : numkeys[0]]), dtype=bool)
1055+
out: np.ndarray[Any, Any] = np.frombuffer(ffi.buffer(keyboard_state[0 : numkeys[0]]), dtype=bool) # type: ignore
10561056
out.flags["WRITEABLE"] = False # This buffer is supposed to be const.
10571057
return out
10581058

tcod/image.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -333,7 +333,7 @@ def _get_format_name(format: int) -> str:
333333
" It's recommended to load images with a more complete image library such as python-Pillow or python-imageio.",
334334
category=PendingDeprecationWarning,
335335
)
336-
def load(filename: Union[str, Path]) -> np.ndarray:
336+
def load(filename: Union[str, Path]) -> "np.ndarray[Any, np.dtype[np.uint8]]":
337337
"""Load a PNG file as an RGBA array.
338338
339339
`filename` is the name of the file to load.
@@ -346,7 +346,7 @@ def load(filename: Union[str, Path]) -> np.ndarray:
346346
array = np.asarray(image, dtype=np.uint8)
347347
height, width, depth = array.shape
348348
if depth == 3:
349-
array = np.concatenate(
349+
array = np.concatenate( # type: ignore
350350
(
351351
array,
352352
np.full((height, width, 1), fill_value=255, dtype=np.uint8),

0 commit comments

Comments
 (0)