Skip to content

Commit

Permalink
Fix Ruff warnings, update Mypy strategy to use local version
Browse files Browse the repository at this point in the history
  • Loading branch information
HexDecimal committed Jul 16, 2024
1 parent 3bc0ce0 commit 4b25bc4
Show file tree
Hide file tree
Showing 10 changed files with 33 additions and 21 deletions.
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
"files.associations": {
"*.spec": "python",
},
"mypy-type-checker.importStrategy": "fromEnvironment",
"cSpell.words": [
"aarch",
"ADDA",
Expand Down
3 changes: 2 additions & 1 deletion tcod/console.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ def __init__(
order: Literal["C", "F"] = "C",
buffer: NDArray[Any] | None = None,
) -> None:
"""Initialize the console."""
self._key_color: tuple[int, int, int] | None = None
self._order = tcod._internal.verify_order(order)
if buffer is not None:
Expand Down Expand Up @@ -930,7 +931,7 @@ def __repr__(self) -> str:

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

def print( # noqa: PLR0913
self,
Expand Down
3 changes: 2 additions & 1 deletion tcod/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,8 @@ def new_console(
scale = max(1, scale + event.y)
"""
if magnification < 0:
raise ValueError("Magnification must be greater than zero. (Got %f)" % magnification)
msg = f"Magnification must be greater than zero. (Got {magnification:f})"
raise ValueError(msg)
size = ffi.new("int[2]")
_check(lib.TCOD_context_recommended_console_size(self._p, magnification, size, size + 1))
width, height = max(min_columns, size[0]), max(min_rows, size[1])
Expand Down
15 changes: 8 additions & 7 deletions tcod/libtcodpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,7 @@ def nb_dices(self, value: int) -> None:
self.nb_rolls = value

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


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


class Key(_CDataWrapper):
Expand Down Expand Up @@ -418,9 +418,9 @@ def __repr__(self) -> str:
params = []
params.append(f"pressed={self.pressed!r}, vk=tcod.{_LOOKUP_VK[self.vk]}")
if self.c:
params.append("c=ord(%r)" % chr(self.c))
params.append(f"c=ord({chr(self.c)!r})")
if self.text:
params.append("text=%r" % self.text)
params.append(f"text={self.text!r}")
for attr in [
"shift",
"lalt",
Expand All @@ -432,7 +432,7 @@ def __repr__(self) -> str:
]:
if getattr(self, attr):
params.append(f"{attr}={getattr(self, attr)!r}")
return "tcod.Key(%s)" % ", ".join(params)
return "tcod.Key({})".format(", ".join(params))

@property
def key_p(self) -> Any:
Expand Down Expand Up @@ -510,7 +510,7 @@ def __repr__(self) -> str:
]:
if getattr(self, attr):
params.append(f"{attr}={getattr(self, attr)!r}")
return "tcod.Mouse(%s)" % ", ".join(params)
return "tcod.Mouse({})".format(", ".join(params))

@property
def mouse_p(self) -> Any:
Expand Down Expand Up @@ -2361,7 +2361,8 @@ def _heightmap_cdata(array: NDArray[np.float32]) -> ffi.CData:
msg = "array must be a contiguous segment."
raise ValueError(msg)
if array.dtype != np.float32:
raise ValueError("array dtype must be float32, not %r" % array.dtype)
msg = f"array dtype must be float32, not {array.dtype!r}"
raise ValueError(msg)
height, width = array.shape
pointer = ffi.from_buffer("float *", array)
return ffi.new("TCOD_heightmap_t *", (width, height, pointer))
Expand Down
4 changes: 3 additions & 1 deletion tcod/map.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ def __init__(
height: int,
order: Literal["C", "F"] = "C",
) -> None:
"""Initialize the map."""
warnings.warn(
"This class may perform poorly and is no longer needed.",
DeprecationWarning,
Expand Down Expand Up @@ -234,7 +235,8 @@ def compute_fov(
"""
transparency = np.asarray(transparency)
if len(transparency.shape) != 2: # noqa: PLR2004
raise TypeError("transparency must be an array of 2 dimensions" " (shape is %r)" % transparency.shape)
msg = f"transparency must be an array of 2 dimensions (shape is {transparency.shape!r})"
raise TypeError(msg)
if isinstance(pov, int):
msg = "The tcod.map.compute_fov function has changed. The `x` and `y` parameters should now be given as a single tuple."
raise TypeError(msg)
Expand Down
1 change: 1 addition & 0 deletions tcod/noise.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ def __init__( # noqa: PLR0913
octaves: float = 4,
seed: int | tcod.random.Random | None = None,
) -> None:
"""Initialize and seed the noise object."""
if not 0 < dimensions <= 4: # noqa: PLR2004
msg = f"dimensions must be in range 0 < n <= 4, got {dimensions}"
raise ValueError(msg)
Expand Down
10 changes: 6 additions & 4 deletions tcod/path.py
Original file line number Diff line number Diff line change
Expand Up @@ -591,7 +591,7 @@ def _world_array(shape: tuple[int, ...], dtype: DTypeLike = np.int32) -> NDArray
)


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

def __init__(self, shape: tuple[int, ...], *, order: str = "C") -> None:
"""Initialize the custom graph."""
self._shape = self._shape_c = tuple(shape)
self._ndim = len(self._shape)
self._order = order
Expand Down Expand Up @@ -894,8 +895,7 @@ def add_edges(
edge_array = np.transpose(edge_nz)
edge_array -= edge_center
for edge, edge_cost in zip(edge_array, edge_costs):
edge = tuple(edge)
self.add_edge(edge, edge_cost, cost=cost, condition=condition)
self.add_edge(tuple(edge), edge_cost, cost=cost, condition=condition)

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

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

def __init__(self, graph: CustomGraph | SimpleGraph) -> None:
"""Initialize the pathfinder from a graph."""
self._graph = graph
self._order = graph._order
self._frontier_p = ffi.gc(lib.TCOD_frontier_new(self._graph._ndim), lib.TCOD_frontier_delete)
Expand Down Expand Up @@ -1273,7 +1275,7 @@ def resolve(self, goal: tuple[int, ...] | None = None) -> None:
if self._order == "F":
# Goal is now ij indexed for the rest of this function.
goal = goal[::-1]
if self._distance[goal] != np.iinfo(self._distance.dtype).max:
if self._distance[goal] != np.iinfo(self._distance.dtype).max: # noqa: SIM102
if not lib.frontier_has_index(self._frontier_p, goal):
return
self._update_heuristic(goal)
Expand Down
2 changes: 2 additions & 0 deletions tcod/render.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ class SDLTilesetAtlas:
"""Prepares a tileset for rendering using SDL."""

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

def __init__(self, atlas: SDLTilesetAtlas) -> None:
"""Initialize the console renderer."""
self.atlas: Final[SDLTilesetAtlas] = atlas
"""The SDLTilesetAtlas used to create this SDLConsoleRender.
Expand Down
11 changes: 7 additions & 4 deletions tcod/tileset.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
from numpy.typing import ArrayLike, NDArray

import tcod.console
from tcod._internal import _check, _console, _path_encode, _raise_tcod_error, deprecate
from tcod._internal import _check, _check_p, _console, _path_encode, _raise_tcod_error, deprecate
from tcod.cffi import ffi, lib


Expand All @@ -33,9 +33,12 @@ class Tileset:
"""

def __init__(self, tile_width: int, tile_height: int) -> None:
self._tileset_p = ffi.gc(
lib.TCOD_tileset_new(tile_width, tile_height),
lib.TCOD_tileset_delete,
"""Initialize the tileset."""
self._tileset_p = _check_p(
ffi.gc(
lib.TCOD_tileset_new(tile_width, tile_height),
lib.TCOD_tileset_delete,
)
)

@classmethod
Expand Down
4 changes: 1 addition & 3 deletions tests/test_libtcodpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -671,9 +671,7 @@ def map_() -> Iterator[tcod.map.Map]:
@pytest.fixture()
def path_callback(map_: tcod.map.Map) -> Callable[[int, int, int, int, None], bool]:
def callback(ox: int, oy: int, dx: int, dy: int, user_data: None) -> bool:
if map_.walkable[dy, dx]:
return True
return False
return bool(map_.walkable[dy, dx])

return callback

Expand Down

0 comments on commit 4b25bc4

Please sign in to comment.