Skip to content

Commit 00b287c

Browse files
committed
Clean up type annotations and use future annotations.
1 parent f1135c3 commit 00b287c

17 files changed

Lines changed: 222 additions & 189 deletions

tcod/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
77
Read the documentation online: https://python-tcod.readthedocs.io/en/latest/
88
"""
9+
from __future__ import annotations
10+
911
import sys
1012
import warnings
1113

tcod/_internal.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
"""This module internal helper functions used by the rest of the library.
22
"""
3+
from __future__ import annotations
4+
35
import functools
46
import warnings
57
from typing import Any, AnyStr, Callable, TypeVar, cast

tcod/bsp.py

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@
2323
else:
2424
print('Dig a room for %s.' % node)
2525
"""
26+
from __future__ import annotations
27+
2628
from typing import Any, Iterator, List, Optional, Tuple, Union # noqa: F401
2729

2830
import tcod.random
@@ -64,8 +66,8 @@ def __init__(self, x: int, y: int, width: int, height: int):
6466
self.position = 0
6567
self.horizontal = False
6668

67-
self.parent: Optional["BSP"] = None
68-
self.children: Union[Tuple[()], Tuple["BSP", "BSP"]] = ()
69+
self.parent: Optional[BSP] = None
70+
self.children: Union[Tuple[()], Tuple[BSP, BSP]] = ()
6971

7072
@property
7173
def w(self) -> int:
@@ -172,15 +174,15 @@ def split_recursive(
172174
self._unpack_bsp_tree(cdata)
173175

174176
@deprecate("Use pre_order method instead of walk.")
175-
def walk(self) -> Iterator["BSP"]:
177+
def walk(self) -> Iterator[BSP]:
176178
"""Iterate over this BSP's hierarchy in pre order.
177179
178180
.. deprecated:: 2.3
179181
Use :any:`pre_order` instead.
180182
"""
181183
return self.post_order()
182184

183-
def pre_order(self) -> Iterator["BSP"]:
185+
def pre_order(self) -> Iterator[BSP]:
184186
"""Iterate over this BSP's hierarchy in pre order.
185187
186188
.. versionadded:: 8.3
@@ -189,7 +191,7 @@ def pre_order(self) -> Iterator["BSP"]:
189191
for child in self.children:
190192
yield from child.pre_order()
191193

192-
def in_order(self) -> Iterator["BSP"]:
194+
def in_order(self) -> Iterator[BSP]:
193195
"""Iterate over this BSP's hierarchy in order.
194196
195197
.. versionadded:: 8.3
@@ -201,7 +203,7 @@ def in_order(self) -> Iterator["BSP"]:
201203
else:
202204
yield self
203205

204-
def post_order(self) -> Iterator["BSP"]:
206+
def post_order(self) -> Iterator[BSP]:
205207
"""Iterate over this BSP's hierarchy in post order.
206208
207209
.. versionadded:: 8.3
@@ -210,29 +212,29 @@ def post_order(self) -> Iterator["BSP"]:
210212
yield from child.post_order()
211213
yield self
212214

213-
def level_order(self) -> Iterator["BSP"]:
215+
def level_order(self) -> Iterator[BSP]:
214216
"""Iterate over this BSP's hierarchy in level order.
215217
216218
.. versionadded:: 8.3
217219
"""
218-
next = [self] # type: List['BSP']
220+
next = [self]
219221
while next:
220-
level = next # type: List['BSP']
222+
level = next
221223
next = []
222224
yield from level
223225
for node in level:
224226
next.extend(node.children)
225227

226-
def inverted_level_order(self) -> Iterator["BSP"]:
228+
def inverted_level_order(self) -> Iterator[BSP]:
227229
"""Iterate over this BSP's hierarchy in inverse level order.
228230
229231
.. versionadded:: 8.3
230232
"""
231-
levels = [] # type: List[List['BSP']]
232-
next = [self] # type: List['BSP']
233+
levels: List[List[BSP]] = []
234+
next = [self]
233235
while next:
234236
levels.append(next)
235-
level = next # type: List['BSP']
237+
level = next
236238
next = []
237239
for node in level:
238240
next.extend(node.children)
@@ -252,7 +254,7 @@ def contains(self, x: int, y: int) -> bool:
252254
"""
253255
return self.x <= x < self.x + self.width and self.y <= y < self.y + self.height
254256

255-
def find_node(self, x: int, y: int) -> Optional["BSP"]:
257+
def find_node(self, x: int, y: int) -> Optional[BSP]:
256258
"""Return the deepest node which contains these coordinates.
257259
258260
Returns:
@@ -261,7 +263,7 @@ def find_node(self, x: int, y: int) -> Optional["BSP"]:
261263
if not self.contains(x, y):
262264
return None
263265
for child in self.children:
264-
found = child.find_node(x, y) # type: Optional["BSP"]
266+
found: Optional[BSP] = child.find_node(x, y)
265267
if found:
266268
return found
267269
return self

tcod/color.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
"""
22
33
"""
4+
from __future__ import annotations
5+
46
import warnings
57
from typing import Any, List
68

@@ -63,7 +65,7 @@ def b(self, value: int) -> None:
6365
self[2] = value & 0xFF
6466

6567
@classmethod
66-
def _new_from_cdata(cls, cdata: Any) -> "Color":
68+
def _new_from_cdata(cls, cdata: Any) -> Color:
6769
"""new in libtcod-cffi"""
6870
return cls(cdata.r, cdata.g, cdata.b)
6971

@@ -100,7 +102,7 @@ def __eq__(self, other: Any) -> bool:
100102
return False
101103

102104
@deprecate("Use NumPy instead for color math operations.")
103-
def __add__(self, other: Any) -> "Color":
105+
def __add__(self, other: Any) -> Color:
104106
"""Add two colors together.
105107
106108
.. deprecated:: 9.2
@@ -109,7 +111,7 @@ def __add__(self, other: Any) -> "Color":
109111
return Color._new_from_cdata(lib.TCOD_color_add(self, other))
110112

111113
@deprecate("Use NumPy instead for color math operations.")
112-
def __sub__(self, other: Any) -> "Color":
114+
def __sub__(self, other: Any) -> Color:
113115
"""Subtract one color from another.
114116
115117
.. deprecated:: 9.2
@@ -118,7 +120,7 @@ def __sub__(self, other: Any) -> "Color":
118120
return Color._new_from_cdata(lib.TCOD_color_subtract(self, other))
119121

120122
@deprecate("Use NumPy instead for color math operations.")
121-
def __mul__(self, other: Any) -> "Color":
123+
def __mul__(self, other: Any) -> Color:
122124
"""Multiply with a scaler or another color.
123125
124126
.. deprecated:: 9.2

tcod/console.py

Lines changed: 28 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,15 @@
33
To render a console you need a tileset and a window to render to.
44
See :ref:`getting-started` for info on how to set those up.
55
"""
6+
from __future__ import annotations
7+
68
import os
79
import warnings
810
from pathlib import Path
911
from typing import Any, Iterable, Optional, Sequence, Tuple, Union
1012

1113
import numpy as np
14+
from numpy.typing import NDArray
1215
from typing_extensions import Literal
1316

1417
import tcod._internal
@@ -114,9 +117,9 @@ def __init__(
114117
width: int,
115118
height: int,
116119
order: Literal["C", "F"] = "C",
117-
buffer: "Optional[np.ndarray[Any, Any]]" = None,
120+
buffer: Optional[NDArray[Any]] = None,
118121
):
119-
self._key_color = None # type: Optional[Tuple[int, int, int]]
122+
self._key_color: Optional[Tuple[int, int, int]] = None
120123
self._order = tcod._internal.verify_order(order)
121124
if buffer is not None:
122125
if self._order == "F":
@@ -150,25 +153,25 @@ def __init__(
150153
self.clear()
151154

152155
@classmethod
153-
def _from_cdata(cls, cdata: Any, order: Literal["C", "F"] = "C") -> "Console":
156+
def _from_cdata(cls, cdata: Any, order: Literal["C", "F"] = "C") -> Console:
154157
"""Return a Console instance which wraps this `TCOD_Console*` object."""
155158
if isinstance(cdata, cls):
156159
return cdata
157-
self = object.__new__(cls) # type: Console
160+
self: Console = object.__new__(cls)
158161
self.console_c = cdata
159162
self._init_setup_console_data(order)
160163
return self
161164

162165
@classmethod
163-
def _get_root(cls, order: Optional[Literal["C", "F"]] = None) -> "Console":
166+
def _get_root(cls, order: Optional[Literal["C", "F"]] = None) -> Console:
164167
"""Return a root console singleton with valid buffers.
165168
166169
This function will also update an already active root console.
167170
"""
168171
global _root_console
169172
if _root_console is None:
170173
_root_console = object.__new__(cls)
171-
self = _root_console # type: Console
174+
self: Console = _root_console
172175
if order is not None:
173176
self._order = order
174177
self.console_c = ffi.NULL
@@ -185,7 +188,7 @@ def _init_setup_console_data(self, order: Literal["C", "F"] = "C") -> None:
185188
else:
186189
self._console_data = ffi.cast("struct TCOD_Console*", self.console_c)
187190

188-
self._tiles = np.frombuffer( # type: ignore
191+
self._tiles: NDArray[Any] = np.frombuffer( # type: ignore
189192
ffi.buffer(self._console_data.tiles[0 : self.width * self.height]),
190193
dtype=self.DTYPE,
191194
).reshape((self.height, self.width))
@@ -203,7 +206,7 @@ def height(self) -> int:
203206
return lib.TCOD_console_get_height(self.console_c) # type: ignore
204207

205208
@property
206-
def bg(self) -> "np.ndarray[Any, np.dtype[np.uint8]]":
209+
def bg(self) -> NDArray[np.uint8]:
207210
"""A uint8 array with the shape (height, width, 3).
208211
209212
You can change the consoles background colors by using this array.
@@ -218,7 +221,7 @@ def bg(self) -> "np.ndarray[Any, np.dtype[np.uint8]]":
218221
return bg
219222

220223
@property
221-
def fg(self) -> "np.ndarray[Any, np.dtype[np.uint8]]":
224+
def fg(self) -> NDArray[np.uint8]:
222225
"""A uint8 array with the shape (height, width, 3).
223226
224227
You can change the consoles foreground colors by using this array.
@@ -232,7 +235,7 @@ def fg(self) -> "np.ndarray[Any, np.dtype[np.uint8]]":
232235
return fg
233236

234237
@property
235-
def ch(self) -> "np.ndarray[Any, np.dtype[np.intc]]":
238+
def ch(self) -> NDArray[np.intc]:
236239
"""An integer array with the shape (height, width).
237240
238241
You can change the consoles character codes by using this array.
@@ -244,7 +247,7 @@ def ch(self) -> "np.ndarray[Any, np.dtype[np.intc]]":
244247

245248
@property # type: ignore
246249
@deprecate("This attribute has been renamed to `rgba`.")
247-
def tiles(self) -> "np.ndarray[Any, Any]":
250+
def tiles(self) -> NDArray[Any]:
248251
"""An array of this consoles raw tile data.
249252
250253
This acts as a combination of the `ch`, `fg`, and `bg` attributes.
@@ -260,7 +263,7 @@ def tiles(self) -> "np.ndarray[Any, Any]":
260263

261264
@property # type: ignore
262265
@deprecate("This attribute has been renamed to `rgba`.")
263-
def buffer(self) -> "np.ndarray[Any, Any]":
266+
def buffer(self) -> NDArray[Any]:
264267
"""An array of this consoles raw tile data.
265268
266269
.. versionadded:: 11.4
@@ -272,7 +275,7 @@ def buffer(self) -> "np.ndarray[Any, Any]":
272275

273276
@property # type: ignore
274277
@deprecate("This attribute has been renamed to `rgb`.")
275-
def tiles_rgb(self) -> "np.ndarray[Any, Any]":
278+
def tiles_rgb(self) -> NDArray[Any]:
276279
"""An array of this consoles data without the alpha channel.
277280
278281
.. versionadded:: 11.8
@@ -284,7 +287,7 @@ def tiles_rgb(self) -> "np.ndarray[Any, Any]":
284287

285288
@property # type: ignore
286289
@deprecate("This attribute has been renamed to `rgb`.")
287-
def tiles2(self) -> "np.ndarray[Any, Any]":
290+
def tiles2(self) -> NDArray[Any]:
288291
"""This name is deprecated in favour of :any:`rgb`.
289292
290293
.. versionadded:: 11.3
@@ -295,7 +298,7 @@ def tiles2(self) -> "np.ndarray[Any, Any]":
295298
return self.rgb
296299

297300
@property
298-
def rgba(self) -> "np.ndarray[Any, Any]":
301+
def rgba(self) -> NDArray[Any]:
299302
"""An array of this consoles raw tile data.
300303
301304
The axes of this array is affected by the `order` parameter given to
@@ -316,7 +319,7 @@ def rgba(self) -> "np.ndarray[Any, Any]":
316319
return self._tiles.T if self._order == "F" else self._tiles
317320

318321
@property
319-
def rgb(self) -> "np.ndarray[Any, Any]":
322+
def rgb(self) -> NDArray[Any]:
320323
"""An array of this consoles data without the alpha channel.
321324
322325
The axes of this array is affected by the `order` parameter given to
@@ -468,8 +471,8 @@ def __deprecate_defaults(
468471
if not __debug__:
469472
return
470473

471-
fg = self.default_fg # type: Any
472-
bg = self.default_bg # type: Any
474+
fg: Optional[Tuple[int, int, int]] = self.default_fg
475+
bg: Optional[Tuple[int, int, int]] = self.default_bg
473476
if bg_blend == tcod.constants.BKGND_NONE:
474477
bg = None
475478
if bg_blend == tcod.constants.BKGND_DEFAULT:
@@ -737,7 +740,7 @@ def print_frame(
737740

738741
def blit(
739742
self,
740-
dest: "Console",
743+
dest: Console,
741744
dest_x: int = 0,
742745
dest_y: int = 0,
743746
src_x: int = 0,
@@ -837,7 +840,7 @@ def set_key_color(self, color: Optional[Tuple[int, int, int]]) -> None:
837840
"""
838841
self._key_color = color
839842

840-
def __enter__(self) -> "Console":
843+
def __enter__(self) -> Console:
841844
"""Returns this console in a managed context.
842845
843846
When the root console is used as a context, the graphical window will
@@ -898,7 +901,7 @@ def __getstate__(self) -> Any:
898901
def __setstate__(self, state: Any) -> None:
899902
self._key_color = None
900903
if "_tiles" not in state:
901-
tiles: np.ndarray[Any, Any] = np.ndarray((self.height, self.width), dtype=self.DTYPE)
904+
tiles: NDArray[Any] = np.ndarray((self.height, self.width), dtype=self.DTYPE)
902905
tiles["ch"] = state["_ch"]
903906
tiles["fg"][..., :3] = state["_fg"]
904907
tiles["fg"][..., 3] = 255
@@ -962,7 +965,7 @@ def print(
962965
.. versionchanged:: 13.0
963966
`x` and `y` are now always used as an absolute position for negative values.
964967
"""
965-
string_ = string.encode("utf-8") # type: bytes
968+
string_ = string.encode("utf-8")
966969
lib.TCOD_console_printn(
967970
self.console_c,
968971
x,
@@ -1017,7 +1020,7 @@ def print_box(
10171020
.. versionchanged:: 13.0
10181021
`x` and `y` are now always used as an absolute position for negative values.
10191022
"""
1020-
string_ = string.encode("utf-8") # type: bytes
1023+
string_ = string.encode("utf-8")
10211024
return int(
10221025
lib.TCOD_console_printn_rect(
10231026
self.console_c,
@@ -1118,7 +1121,7 @@ def draw_frame(
11181121
PendingDeprecationWarning,
11191122
stacklevel=2,
11201123
)
1121-
title_ = title.encode("utf-8") # type: bytes
1124+
title_ = title.encode("utf-8")
11221125
lib.TCOD_console_printn_frame(
11231126
self.console_c,
11241127
x,
@@ -1227,7 +1230,7 @@ def get_height_rect(width: int, string: str) -> int:
12271230
12281231
.. versionadded:: 9.2
12291232
"""
1230-
string_ = string.encode("utf-8") # type: bytes
1233+
string_ = string.encode("utf-8")
12311234
return int(lib.TCOD_console_get_height_rect_wn(width, len(string_), string_))
12321235

12331236

0 commit comments

Comments
 (0)