Skip to content

Commit 4b25bc4

Browse files
committed
Fix Ruff warnings, update Mypy strategy to use local version
1 parent 3bc0ce0 commit 4b25bc4

File tree

10 files changed

+33
-21
lines changed

10 files changed

+33
-21
lines changed

.vscode/settings.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
"files.associations": {
1616
"*.spec": "python",
1717
},
18+
"mypy-type-checker.importStrategy": "fromEnvironment",
1819
"cSpell.words": [
1920
"aarch",
2021
"ADDA",

tcod/console.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,7 @@ def __init__(
120120
order: Literal["C", "F"] = "C",
121121
buffer: NDArray[Any] | None = None,
122122
) -> None:
123+
"""Initialize the console."""
123124
self._key_color: tuple[int, int, int] | None = None
124125
self._order = tcod._internal.verify_order(order)
125126
if buffer is not None:
@@ -930,7 +931,7 @@ def __repr__(self) -> str:
930931

931932
def __str__(self) -> str:
932933
"""Return a simplified representation of this consoles contents."""
933-
return "<%s>" % "\n ".join("".join(chr(c) for c in line) for line in self._tiles["ch"])
934+
return "<{}>".format("\n ".join("".join(chr(c) for c in line) for line in self._tiles["ch"]))
934935

935936
def print( # noqa: PLR0913
936937
self,

tcod/context.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -344,7 +344,8 @@ def new_console(
344344
scale = max(1, scale + event.y)
345345
"""
346346
if magnification < 0:
347-
raise ValueError("Magnification must be greater than zero. (Got %f)" % magnification)
347+
msg = f"Magnification must be greater than zero. (Got {magnification:f})"
348+
raise ValueError(msg)
348349
size = ffi.new("int[2]")
349350
_check(lib.TCOD_context_recommended_console_size(self._p, magnification, size, size + 1))
350351
width, height = max(min_columns, size[0]), max(min_rows, size[1])

tcod/libtcodpy.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -317,7 +317,7 @@ def nb_dices(self, value: int) -> None:
317317
self.nb_rolls = value
318318

319319
def __str__(self) -> str:
320-
add = "+(%s)" % self.addsub if self.addsub != 0 else ""
320+
add = f"+({self.addsub})" if self.addsub != 0 else ""
321321
return "%id%ix%s%s" % (
322322
self.nb_dices,
323323
self.nb_faces,
@@ -330,7 +330,7 @@ def __repr__(self) -> str:
330330

331331

332332
# reverse lookup table for KEY_X attributes, used by Key.__repr__
333-
_LOOKUP_VK = {value: "KEY_%s" % key[6:] for key, value in lib.__dict__.items() if key.startswith("TCODK")}
333+
_LOOKUP_VK = {value: f"KEY_{key[6:]}" for key, value in lib.__dict__.items() if key.startswith("TCODK")}
334334

335335

336336
class Key(_CDataWrapper):
@@ -418,9 +418,9 @@ def __repr__(self) -> str:
418418
params = []
419419
params.append(f"pressed={self.pressed!r}, vk=tcod.{_LOOKUP_VK[self.vk]}")
420420
if self.c:
421-
params.append("c=ord(%r)" % chr(self.c))
421+
params.append(f"c=ord({chr(self.c)!r})")
422422
if self.text:
423-
params.append("text=%r" % self.text)
423+
params.append(f"text={self.text!r}")
424424
for attr in [
425425
"shift",
426426
"lalt",
@@ -432,7 +432,7 @@ def __repr__(self) -> str:
432432
]:
433433
if getattr(self, attr):
434434
params.append(f"{attr}={getattr(self, attr)!r}")
435-
return "tcod.Key(%s)" % ", ".join(params)
435+
return "tcod.Key({})".format(", ".join(params))
436436

437437
@property
438438
def key_p(self) -> Any:
@@ -510,7 +510,7 @@ def __repr__(self) -> str:
510510
]:
511511
if getattr(self, attr):
512512
params.append(f"{attr}={getattr(self, attr)!r}")
513-
return "tcod.Mouse(%s)" % ", ".join(params)
513+
return "tcod.Mouse({})".format(", ".join(params))
514514

515515
@property
516516
def mouse_p(self) -> Any:
@@ -2361,7 +2361,8 @@ def _heightmap_cdata(array: NDArray[np.float32]) -> ffi.CData:
23612361
msg = "array must be a contiguous segment."
23622362
raise ValueError(msg)
23632363
if array.dtype != np.float32:
2364-
raise ValueError("array dtype must be float32, not %r" % array.dtype)
2364+
msg = f"array dtype must be float32, not {array.dtype!r}"
2365+
raise ValueError(msg)
23652366
height, width = array.shape
23662367
pointer = ffi.from_buffer("float *", array)
23672368
return ffi.new("TCOD_heightmap_t *", (width, height, pointer))

tcod/map.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ def __init__(
7676
height: int,
7777
order: Literal["C", "F"] = "C",
7878
) -> None:
79+
"""Initialize the map."""
7980
warnings.warn(
8081
"This class may perform poorly and is no longer needed.",
8182
DeprecationWarning,
@@ -234,7 +235,8 @@ def compute_fov(
234235
"""
235236
transparency = np.asarray(transparency)
236237
if len(transparency.shape) != 2: # noqa: PLR2004
237-
raise TypeError("transparency must be an array of 2 dimensions" " (shape is %r)" % transparency.shape)
238+
msg = f"transparency must be an array of 2 dimensions (shape is {transparency.shape!r})"
239+
raise TypeError(msg)
238240
if isinstance(pov, int):
239241
msg = "The tcod.map.compute_fov function has changed. The `x` and `y` parameters should now be given as a single tuple."
240242
raise TypeError(msg)

tcod/noise.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,7 @@ def __init__( # noqa: PLR0913
133133
octaves: float = 4,
134134
seed: int | tcod.random.Random | None = None,
135135
) -> None:
136+
"""Initialize and seed the noise object."""
136137
if not 0 < dimensions <= 4: # noqa: PLR2004
137138
msg = f"dimensions must be in range 0 < n <= 4, got {dimensions}"
138139
raise ValueError(msg)

tcod/path.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -591,7 +591,7 @@ def _world_array(shape: tuple[int, ...], dtype: DTypeLike = np.int32) -> NDArray
591591
)
592592

593593

594-
def _as_hashable(obj: np.ndarray[Any, Any] | None) -> Any | None:
594+
def _as_hashable(obj: np.ndarray[Any, Any] | None) -> object | None:
595595
"""Return NumPy arrays as a more hashable form."""
596596
if obj is None:
597597
return obj
@@ -661,6 +661,7 @@ class CustomGraph:
661661
"""
662662

663663
def __init__(self, shape: tuple[int, ...], *, order: str = "C") -> None:
664+
"""Initialize the custom graph."""
664665
self._shape = self._shape_c = tuple(shape)
665666
self._ndim = len(self._shape)
666667
self._order = order
@@ -894,8 +895,7 @@ def add_edges(
894895
edge_array = np.transpose(edge_nz)
895896
edge_array -= edge_center
896897
for edge, edge_cost in zip(edge_array, edge_costs):
897-
edge = tuple(edge)
898-
self.add_edge(edge, edge_cost, cost=cost, condition=condition)
898+
self.add_edge(tuple(edge), edge_cost, cost=cost, condition=condition)
899899

900900
def set_heuristic(self, *, cardinal: int = 0, diagonal: int = 0, z: int = 0, w: int = 0) -> None:
901901
"""Set a pathfinder heuristic so that pathfinding can done with A*.
@@ -1028,6 +1028,7 @@ class SimpleGraph:
10281028
"""
10291029

10301030
def __init__(self, *, cost: ArrayLike, cardinal: int, diagonal: int, greed: int = 1) -> None:
1031+
"""Initialize the graph."""
10311032
cost = np.asarray(cost)
10321033
if cost.ndim != 2: # noqa: PLR2004
10331034
msg = f"The cost array must e 2 dimensional, array of shape {cost.shape!r} given."
@@ -1087,6 +1088,7 @@ class Pathfinder:
10871088
"""
10881089

10891090
def __init__(self, graph: CustomGraph | SimpleGraph) -> None:
1091+
"""Initialize the pathfinder from a graph."""
10901092
self._graph = graph
10911093
self._order = graph._order
10921094
self._frontier_p = ffi.gc(lib.TCOD_frontier_new(self._graph._ndim), lib.TCOD_frontier_delete)
@@ -1273,7 +1275,7 @@ def resolve(self, goal: tuple[int, ...] | None = None) -> None:
12731275
if self._order == "F":
12741276
# Goal is now ij indexed for the rest of this function.
12751277
goal = goal[::-1]
1276-
if self._distance[goal] != np.iinfo(self._distance.dtype).max:
1278+
if self._distance[goal] != np.iinfo(self._distance.dtype).max: # noqa: SIM102
12771279
if not lib.frontier_has_index(self._frontier_p, goal):
12781280
return
12791281
self._update_heuristic(goal)

tcod/render.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ class SDLTilesetAtlas:
4242
"""Prepares a tileset for rendering using SDL."""
4343

4444
def __init__(self, renderer: tcod.sdl.render.Renderer, tileset: tcod.tileset.Tileset) -> None:
45+
"""Initialize the tileset atlas."""
4546
self._renderer = renderer
4647
self.tileset: Final[tcod.tileset.Tileset] = tileset
4748
"""The tileset used to create this SDLTilesetAtlas."""
@@ -64,6 +65,7 @@ class SDLConsoleRender:
6465
"""Holds an internal cache console and texture which are used to optimized console rendering."""
6566

6667
def __init__(self, atlas: SDLTilesetAtlas) -> None:
68+
"""Initialize the console renderer."""
6769
self.atlas: Final[SDLTilesetAtlas] = atlas
6870
"""The SDLTilesetAtlas used to create this SDLConsoleRender.
6971

tcod/tileset.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
from numpy.typing import ArrayLike, NDArray
2323

2424
import tcod.console
25-
from tcod._internal import _check, _console, _path_encode, _raise_tcod_error, deprecate
25+
from tcod._internal import _check, _check_p, _console, _path_encode, _raise_tcod_error, deprecate
2626
from tcod.cffi import ffi, lib
2727

2828

@@ -33,9 +33,12 @@ class Tileset:
3333
"""
3434

3535
def __init__(self, tile_width: int, tile_height: int) -> None:
36-
self._tileset_p = ffi.gc(
37-
lib.TCOD_tileset_new(tile_width, tile_height),
38-
lib.TCOD_tileset_delete,
36+
"""Initialize the tileset."""
37+
self._tileset_p = _check_p(
38+
ffi.gc(
39+
lib.TCOD_tileset_new(tile_width, tile_height),
40+
lib.TCOD_tileset_delete,
41+
)
3942
)
4043

4144
@classmethod

tests/test_libtcodpy.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -671,9 +671,7 @@ def map_() -> Iterator[tcod.map.Map]:
671671
@pytest.fixture()
672672
def path_callback(map_: tcod.map.Map) -> Callable[[int, int, int, int, None], bool]:
673673
def callback(ox: int, oy: int, dx: int, dy: int, user_data: None) -> bool:
674-
if map_.walkable[dy, dx]:
675-
return True
676-
return False
674+
return bool(map_.walkable[dy, dx])
677675

678676
return callback
679677

0 commit comments

Comments
 (0)