Skip to content

Commit c7b6bc5

Browse files
committed
Clean up warnings
Specify specific warnings for Mypy ignores Narrow type hints Move image internals to image.py to avoid cyclic imports
1 parent 3a04143 commit c7b6bc5

File tree

15 files changed

+112
-130
lines changed

15 files changed

+112
-130
lines changed

tcod/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313

1414
__path__ = extend_path(__path__, __name__)
1515

16-
from tcod import bsp, color, console, context, event, image, los, map, noise, path, random, tileset
16+
from tcod import bsp, color, console, context, event, image, los, map, noise, path, random, tileset # noqa: A004
1717
from tcod.cffi import __sdl_version__, ffi, lib
1818
from tcod.tcod import __getattr__ # noqa: F401
1919
from tcod.version import __version__

tcod/_internal.py

Lines changed: 8 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
import warnings
88
from typing import TYPE_CHECKING, Any, AnyStr, Callable, NoReturn, SupportsInt, TypeVar
99

10-
import numpy as np
1110
from typing_extensions import Literal, LiteralString, deprecated
1211

1312
from tcod.cffi import ffi, lib
@@ -16,17 +15,18 @@
1615
from pathlib import Path
1716
from types import TracebackType
1817

19-
from numpy.typing import ArrayLike, NDArray
20-
21-
import tcod.image
2218

2319
FuncType = Callable[..., Any]
2420
F = TypeVar("F", bound=FuncType)
2521
T = TypeVar("T")
2622

2723

2824
def _deprecate_passthrough(
29-
message: str, /, *, category: type[Warning] = DeprecationWarning, stacklevel: int = 0
25+
message: str, # noqa: ARG001
26+
/,
27+
*,
28+
category: type[Warning] = DeprecationWarning, # noqa: ARG001
29+
stacklevel: int = 0, # noqa: ARG001
3030
) -> Callable[[F], F]:
3131
"""Return a decorator which skips wrapping a warning onto functions. This is used for non-debug runs."""
3232

@@ -51,7 +51,7 @@ def pending_deprecate(
5151

5252
def verify_order(order: Literal["C", "F"]) -> Literal["C", "F"]:
5353
"""Verify and return a Numpy order string."""
54-
order = order.upper() # type: ignore
54+
order = order.upper() # type: ignore[assignment]
5555
if order not in ("C", "F"):
5656
msg = f"order must be 'C' or 'F', not {order!r}"
5757
raise TypeError(msg)
@@ -91,7 +91,7 @@ def _check_warn(error: int, stacklevel: int = 2) -> int:
9191
def _unpack_char_p(char_p: Any) -> str: # noqa: ANN401
9292
if char_p == ffi.NULL:
9393
return ""
94-
return ffi.string(char_p).decode() # type: ignore
94+
return str(ffi.string(char_p), encoding="utf-8")
9595

9696

9797
def _int(int_or_str: SupportsInt | str | bytes) -> int:
@@ -171,7 +171,7 @@ def __enter__(self) -> Callable[[Any], None]:
171171
return self.propagate
172172

173173
def __exit__(
174-
self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None
174+
self, _type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None
175175
) -> None:
176176
"""If we're holding on to an exception, raise it now.
177177
@@ -232,42 +232,3 @@ def _console(console: Any) -> Any: # noqa: ANN401
232232
stacklevel=3,
233233
)
234234
return ffi.NULL
235-
236-
237-
class TempImage:
238-
"""An Image-like container for NumPy arrays."""
239-
240-
def __init__(self, array: ArrayLike) -> None:
241-
"""Initialize an image from the given array. May copy or reference the array."""
242-
self._array: NDArray[np.uint8] = np.ascontiguousarray(array, dtype=np.uint8)
243-
height, width, depth = self._array.shape
244-
if depth != 3: # noqa: PLR2004
245-
msg = f"Array must have RGB channels. Shape is: {self._array.shape!r}"
246-
raise TypeError(msg)
247-
self._buffer = ffi.from_buffer("TCOD_color_t[]", self._array)
248-
self._mipmaps = ffi.new(
249-
"struct TCOD_mipmap_*",
250-
{
251-
"width": width,
252-
"height": height,
253-
"fwidth": width,
254-
"fheight": height,
255-
"buf": self._buffer,
256-
"dirty": True,
257-
},
258-
)
259-
self.image_c = ffi.new(
260-
"TCOD_Image*",
261-
{
262-
"nb_mipmaps": 1,
263-
"mipmaps": self._mipmaps,
264-
"has_key_color": False,
265-
},
266-
)
267-
268-
269-
def _as_image(image: ArrayLike | tcod.image.Image) -> TempImage | tcod.image.Image:
270-
"""Convert this input into an Image-like object."""
271-
if hasattr(image, "image_c"):
272-
return image
273-
return TempImage(image)

tcod/bsp.py

Lines changed: 3 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -104,20 +104,9 @@ def __repr__(self) -> str:
104104
"""Provide a useful readout when printed."""
105105
status = "leaf"
106106
if self.children:
107-
status = "split at position=%i,horizontal=%r" % (
108-
self.position,
109-
self.horizontal,
110-
)
111-
112-
return "<%s(x=%i,y=%i,width=%i,height=%i) level=%i %s>" % (
113-
self.__class__.__name__,
114-
self.x,
115-
self.y,
116-
self.width,
117-
self.height,
118-
self.level,
119-
status,
120-
)
107+
status = f"split at position={self.position},horizontal={self.horizontal!r}"
108+
109+
return f"<{self.__class__.__name__}(x={self.x},y={self.y},width={self.width},height={self.height}) level={self.level} {status}>"
121110

122111
def _unpack_bsp_tree(self, cdata: Any) -> None: # noqa: ANN401
123112
self.x = cdata.x

tcod/cffi.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,8 +64,8 @@ def get_sdl_version() -> str:
6464
__sdl_version__ = get_sdl_version()
6565

6666

67-
@ffi.def_extern() # type: ignore
68-
def _libtcod_log_watcher(message: Any, userdata: None) -> None: # noqa: ANN401
67+
@ffi.def_extern() # type: ignore[misc]
68+
def _libtcod_log_watcher(message: Any, _userdata: None) -> None: # noqa: ANN401
6969
text = str(ffi.string(message.message), encoding="utf-8")
7070
source = str(ffi.string(message.source), encoding="utf-8")
7171
level = int(message.level)

tcod/console.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
import tcod._internal
1818
import tcod.constants
19+
import tcod.image
1920
from tcod._internal import _check, _path_encode
2021
from tcod.cffi import ffi, lib
2122

@@ -1444,7 +1445,7 @@ def draw_semigraphics(self, pixels: ArrayLike | tcod.image.Image, x: int = 0, y:
14441445
14451446
.. versionadded:: 11.4
14461447
"""
1447-
image = tcod._internal._as_image(pixels)
1448+
image = tcod.image._as_image(pixels)
14481449
lib.TCOD_image_blit_2x(image.image_c, self.console_c, x, y, 0, 0, -1, -1)
14491450

14501451

tcod/context.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -447,7 +447,7 @@ def __reduce__(self) -> NoReturn:
447447
raise pickle.PicklingError(msg)
448448

449449

450-
@ffi.def_extern() # type: ignore
450+
@ffi.def_extern() # type: ignore[misc]
451451
def _pycall_cli_output(catch_reference: Any, output: Any) -> None: # noqa: ANN401
452452
"""Callback for the libtcod context CLI.
453453

tcod/event.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1548,7 +1548,7 @@ def get_mouse_state() -> MouseState:
15481548
return MouseState((xy[0], xy[1]), (int(tile[0]), int(tile[1])), buttons)
15491549

15501550

1551-
@ffi.def_extern() # type: ignore
1551+
@ffi.def_extern() # type: ignore[misc]
15521552
def _sdl_event_watcher(userdata: Any, sdl_event: Any) -> int:
15531553
callback: Callable[[Event], None] = ffi.from_handle(userdata)
15541554
callback(_parse_event(sdl_event))

tcod/image.py

Lines changed: 40 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ def get_alpha(self, x: int, y: int) -> int:
145145
int: The alpha value of the pixel.
146146
With 0 being fully transparent and 255 being fully opaque.
147147
"""
148-
return lib.TCOD_image_get_alpha(self.image_c, x, y) # type: ignore
148+
return int(lib.TCOD_image_get_alpha(self.image_c, x, y))
149149

150150
def refresh_console(self, console: tcod.console.Console) -> None:
151151
"""Update an Image created with :any:`libtcodpy.image_from_console`.
@@ -351,17 +351,6 @@ def __array_interface__(self) -> dict[str, Any]:
351351
}
352352

353353

354-
def _get_format_name(format: int) -> str:
355-
"""Return the SDL_PIXELFORMAT_X name for this format, if possible."""
356-
for attr in dir(lib):
357-
if not attr.startswith("SDL_PIXELFORMAT"):
358-
continue
359-
if getattr(lib, attr) != format:
360-
continue
361-
return attr
362-
return str(format)
363-
364-
365354
@deprecated(
366355
"This function may be removed in the future."
367356
" It's recommended to load images with a more complete image library such as python-Pillow or python-imageio.",
@@ -388,3 +377,42 @@ def load(filename: str | PathLike[str]) -> NDArray[np.uint8]:
388377
axis=2,
389378
)
390379
return array
380+
381+
382+
class _TempImage:
383+
"""An Image-like container for NumPy arrays."""
384+
385+
def __init__(self, array: ArrayLike) -> None:
386+
"""Initialize an image from the given array. May copy or reference the array."""
387+
self._array: NDArray[np.uint8] = np.ascontiguousarray(array, dtype=np.uint8)
388+
height, width, depth = self._array.shape
389+
if depth != 3: # noqa: PLR2004
390+
msg = f"Array must have RGB channels. Shape is: {self._array.shape!r}"
391+
raise TypeError(msg)
392+
self._buffer = ffi.from_buffer("TCOD_color_t[]", self._array)
393+
self._mipmaps = ffi.new(
394+
"struct TCOD_mipmap_*",
395+
{
396+
"width": width,
397+
"height": height,
398+
"fwidth": width,
399+
"fheight": height,
400+
"buf": self._buffer,
401+
"dirty": True,
402+
},
403+
)
404+
self.image_c = ffi.new(
405+
"TCOD_Image*",
406+
{
407+
"nb_mipmaps": 1,
408+
"mipmaps": self._mipmaps,
409+
"has_key_color": False,
410+
},
411+
)
412+
413+
414+
def _as_image(image: ArrayLike | Image | _TempImage) -> _TempImage | Image:
415+
"""Convert this input into an Image-like object."""
416+
if isinstance(image, (Image, _TempImage)):
417+
return image
418+
return _TempImage(image)

tcod/libtcodpy.py

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -238,8 +238,8 @@ def set(
238238
def blit(
239239
self,
240240
dest: tcod.console.Console,
241-
fill_fore: bool = True,
242-
fill_back: bool = True,
241+
fill_fore: bool = True, # noqa: FBT001, FBT002
242+
fill_back: bool = True, # noqa: FBT001, FBT002
243243
) -> None:
244244
"""Use libtcod's "fill" functions to write the buffer to a console.
245245
@@ -313,12 +313,7 @@ def nb_dices(self, value: int) -> None:
313313

314314
def __str__(self) -> str:
315315
add = f"+({self.addsub})" if self.addsub != 0 else ""
316-
return "%id%ix%s%s" % (
317-
self.nb_dices,
318-
self.nb_faces,
319-
self.multiplier,
320-
add,
321-
)
316+
return f"{self.nb_dices}d{self.nb_faces}x{self.multiplier}{add}"
322317

323318
def __repr__(self) -> str:
324319
return f"{self.__class__.__name__}(nb_dices={self.nb_dices!r},nb_faces={self.nb_faces!r},multiplier={self.multiplier!r},addsub={self.addsub!r})"
@@ -3584,7 +3579,8 @@ def _unpack_union(type_: int, union: Any) -> Any: # noqa: PLR0911
35843579
return Dice(union.dice)
35853580
if type_ & lib.TCOD_TYPE_LIST:
35863581
return _convert_TCODList(union.list, type_ & 0xFF)
3587-
raise RuntimeError("Unknown libtcod type: %i" % type_)
3582+
msg = f"Unknown libtcod type: {type_}"
3583+
raise RuntimeError(msg)
35883584

35893585

35903586
def _convert_TCODList(c_list: Any, type_: int) -> Any:
@@ -3607,27 +3603,27 @@ def parser_new_struct(parser: Any, name: str) -> Any:
36073603
_parser_listener: Any = None
36083604

36093605

3610-
@ffi.def_extern() # type: ignore
3606+
@ffi.def_extern() # type: ignore[misc]
36113607
def _pycall_parser_new_struct(struct: Any, name: str) -> Any:
36123608
return _parser_listener.new_struct(struct, _unpack_char_p(name))
36133609

36143610

3615-
@ffi.def_extern() # type: ignore
3611+
@ffi.def_extern() # type: ignore[misc]
36163612
def _pycall_parser_new_flag(name: str) -> Any:
36173613
return _parser_listener.new_flag(_unpack_char_p(name))
36183614

36193615

3620-
@ffi.def_extern() # type: ignore
3616+
@ffi.def_extern() # type: ignore[misc]
36213617
def _pycall_parser_new_property(propname: Any, type: Any, value: Any) -> Any:
36223618
return _parser_listener.new_property(_unpack_char_p(propname), type, _unpack_union(type, value))
36233619

36243620

3625-
@ffi.def_extern() # type: ignore
3621+
@ffi.def_extern() # type: ignore[misc]
36263622
def _pycall_parser_end_struct(struct: Any, name: Any) -> Any:
36273623
return _parser_listener.end_struct(struct, _unpack_char_p(name))
36283624

36293625

3630-
@ffi.def_extern() # type: ignore
3626+
@ffi.def_extern() # type: ignore[misc]
36313627
def _pycall_parser_error(msg: Any) -> None:
36323628
_parser_listener.error(_unpack_char_p(msg))
36333629

tcod/noise.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -236,9 +236,8 @@ def __getitem__(self, indexes: Any) -> NDArray[np.float32]:
236236
if not isinstance(indexes, tuple):
237237
indexes = (indexes,)
238238
if len(indexes) > self.dimensions:
239-
raise IndexError(
240-
"This noise generator has %i dimensions, but was indexed with %i." % (self.dimensions, len(indexes))
241-
)
239+
msg = f"This noise generator has {self.dimensions} dimensions, but was indexed with {len(indexes)}."
240+
raise IndexError(msg)
242241
indexes = list(np.broadcast_arrays(*indexes))
243242
c_input = [ffi.NULL, ffi.NULL, ffi.NULL, ffi.NULL]
244243
for i, index in enumerate(indexes):

0 commit comments

Comments
 (0)