Skip to content

Commit e0233a7

Browse files
committed
Clean up the remaining auto-fixes for the tcod package and scripts.
1 parent 77f4a43 commit e0233a7

19 files changed

+330
-315
lines changed

scripts/generate_charmap_table.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313

1414
import tcod.tileset
1515

16+
# ruff: noqa: INP001
17+
1618

1719
def get_charmaps() -> Iterator[str]:
1820
"""Return an iterator of the current character maps from tcod.tilest."""
@@ -53,6 +55,7 @@ def generate_table(charmap: Iterable[int]) -> str:
5355

5456

5557
def main() -> None:
58+
"""Main entry point."""
5659
parser = argparse.ArgumentParser(
5760
description="Generate an RST table for a tcod character map.",
5861
)

scripts/get_release_description.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
import re
66
from pathlib import Path
77

8+
# ruff: noqa: INP001
9+
810
TAG_BANNER = r"## \[[\w.]*\] - \d+-\d+-\d+\n"
911

1012
RE_BODY = re.compile(rf".*?{TAG_BANNER}(.*?){TAG_BANNER}", re.DOTALL)

tcod/_internal.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ def __exit__(
168168
class _CDataWrapper:
169169
"""A generally deprecated CData wrapper class used by libtcodpy."""
170170

171-
def __init__(self, *args: Any, **kwargs: Any): # noqa: ANN401
171+
def __init__(self, *args: Any, **kwargs: Any) -> None: # noqa: ANN401
172172
self.cdata = self._get_cdata_from_args(*args, **kwargs)
173173
if self.cdata is None:
174174
self.cdata = ffi.NULL

tcod/console.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
"""
2-
Libtcod consoles are a strictly tile-based representation of text and color.
1+
"""Libtcod consoles are a strictly tile-based representation of text and color.
32
To render a console you need a tileset and a window to render to.
43
See :ref:`getting-started` for info on how to set those up.
54
"""
@@ -117,7 +116,7 @@ def __init__(
117116
height: int,
118117
order: Literal["C", "F"] = "C",
119118
buffer: NDArray[Any] | None = None,
120-
):
119+
) -> None:
121120
self._key_color: tuple[int, int, int] | None = None
122121
self._order = tcod._internal.verify_order(order)
123122
if buffer is not None:

tcod/loader.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import platform
66
import sys
77
from pathlib import Path
8-
from typing import Any # noqa: F401
8+
from typing import Any
99

1010
import cffi
1111

@@ -54,7 +54,7 @@ def get_sdl_version() -> str:
5454
os.environ["PATH"] = f"""{Path(__file__).parent / get_architecture()}{os.pathsep}{os.environ["PATH"]}"""
5555

5656

57-
class _Mock(object):
57+
class _Mock:
5858
"""Mock object needed for ReadTheDocs."""
5959

6060
@staticmethod
@@ -64,7 +64,6 @@ def def_extern() -> Any:
6464

6565
def __getattr__(self, attr: str) -> None:
6666
"""Return None on any attribute."""
67-
return None
6867

6968
def __bool__(self) -> bool:
7069
"""Allow checking for this mock object at import time."""
@@ -80,7 +79,7 @@ def __bool__(self) -> bool:
8079
lib = ffi = _Mock()
8180
else:
8281
verify_dependencies()
83-
from tcod._libtcod import ffi, lib # type: ignore # noqa: F401
82+
from tcod._libtcod import ffi, lib # type: ignore
8483

8584
__sdl_version__ = get_sdl_version()
8685

tcod/los.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
"""This modules holds functions for NumPy-based line of sight algorithms."""
22
from __future__ import annotations
33

4-
from typing import Any, Tuple
4+
from typing import Any
55

66
import numpy as np
77
from numpy.typing import NDArray
88

99
from tcod.loader import ffi, lib
1010

1111

12-
def bresenham(start: Tuple[int, int], end: Tuple[int, int]) -> NDArray[np.intc]:
12+
def bresenham(start: tuple[int, int], end: tuple[int, int]) -> NDArray[np.intc]:
1313
"""Return a thin Bresenham line as a NumPy array of shape (length, 2).
1414
1515
`start` and `end` are the endpoints of the line.

tcod/map.py

Lines changed: 13 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,8 @@
1-
"""libtcod map attributes and field-of-view functions.
2-
3-
4-
"""
1+
"""libtcod map attributes and field-of-view functions."""
52
from __future__ import annotations
63

74
import warnings
8-
from typing import Any, Tuple
5+
from typing import Any
96

107
import numpy as np
118
from numpy.typing import ArrayLike, NDArray
@@ -16,7 +13,7 @@
1613
from tcod.loader import ffi, lib
1714

1815

19-
class Map(object):
16+
class Map:
2017
"""A map containing libtcod attributes.
2118
2219
.. versionchanged:: 4.1
@@ -77,7 +74,7 @@ def __init__(
7774
width: int,
7875
height: int,
7976
order: Literal["C", "F"] = "C",
80-
):
77+
) -> None:
8178
warnings.warn(
8279
"This class may perform poorly and is no longer needed.",
8380
DeprecationWarning,
@@ -140,15 +137,15 @@ def compute_fov(
140137
"""
141138
if not (0 <= x < self.width and 0 <= y < self.height):
142139
warnings.warn(
143-
"Index (%r, %r) is outside of this maps shape (%r, %r)."
144-
"\nThis will raise an error in future versions." % (x, y, self.width, self.height),
140+
"Index ({}, {}) is outside of this maps shape ({}, {})."
141+
"\nThis will raise an error in future versions.".format(x, y, self.width, self.height),
145142
RuntimeWarning,
146143
stacklevel=2,
147144
)
148145

149146
lib.TCOD_map_compute_fov(self.map_c, x, y, radius, light_walls, algorithm)
150147

151-
def __setstate__(self, state: Any) -> None:
148+
def __setstate__(self, state: dict[str, Any]) -> None:
152149
if "_Map__buffer" not in state: # deprecated
153150
# remove this check on major version update
154151
self.__buffer = np.zeros((state["height"], state["width"], 3), dtype=np.bool_)
@@ -157,20 +154,18 @@ def __setstate__(self, state: Any) -> None:
157154
self.__buffer[:, :, 2] = state["buffer"] & 0x04
158155
del state["buffer"]
159156
state["_order"] = "F"
160-
if "_order" not in state: # remove this check on major version update
161-
raise RuntimeError("This Map was saved with a bad version of tdl.")
162157
self.__dict__.update(state)
163158
self.map_c = self.__as_cdata()
164159

165-
def __getstate__(self) -> Any:
160+
def __getstate__(self) -> dict[str, Any]:
166161
state = self.__dict__.copy()
167162
del state["map_c"]
168163
return state
169164

170165

171166
def compute_fov(
172167
transparency: ArrayLike,
173-
pov: Tuple[int, int],
168+
pov: tuple[int, int],
174169
radius: int = 0,
175170
light_walls: bool = True,
176171
algorithm: int = tcod.constants.FOV_RESTRICTIVE,
@@ -240,14 +235,12 @@ def compute_fov(
240235
if len(transparency.shape) != 2:
241236
raise TypeError("transparency must be an array of 2 dimensions" " (shape is %r)" % transparency.shape)
242237
if isinstance(pov, int):
243-
raise TypeError(
244-
"The tcod.map.compute_fov function has changed. The `x` and `y`"
245-
" parameters should now be given as a single tuple."
246-
)
238+
msg = "The tcod.map.compute_fov function has changed. The `x` and `y` parameters should now be given as a single tuple."
239+
raise TypeError(msg)
247240
if not (0 <= pov[0] < transparency.shape[0] and 0 <= pov[1] < transparency.shape[1]):
248241
warnings.warn(
249-
"Given pov index %r is outside the array of shape %r."
250-
"\nThis will raise an error in future versions." % (pov, transparency.shape),
242+
"Given pov index {!r} is outside the array of shape {!r}."
243+
"\nThis will raise an error in future versions.".format(pov, transparency.shape),
251244
RuntimeWarning,
252245
stacklevel=2,
253246
)

tcod/noise.py

Lines changed: 34 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -30,20 +30,19 @@
3030
[ 92, 35, 33, 71, 90],
3131
[ 76, 54, 85, 144, 164],
3232
[ 63, 94, 159, 209, 203]], dtype=uint8)
33-
""" # noqa: E501
33+
"""
3434
from __future__ import annotations
3535

3636
import enum
3737
import warnings
38-
from typing import Any, List, Optional, Sequence, Tuple, Union
38+
from typing import Any, Sequence
3939

4040
import numpy as np
4141
from numpy.typing import ArrayLike, NDArray
4242
from typing_extensions import Literal
4343

4444
import tcod.constants
4545
import tcod.random
46-
from tcod._internal import deprecate
4746
from tcod.loader import ffi, lib
4847

4948

@@ -92,14 +91,15 @@ def __getattr__(name: str) -> Implementation:
9291
if name in Implementation.__members__:
9392
warnings.warn(
9493
f"'tcod.noise.{name}' is deprecated," f" use 'tcod.noise.Implementation.{name}' instead.",
95-
DeprecationWarning,
94+
FutureWarning,
9695
stacklevel=2,
9796
)
9897
return Implementation[name]
99-
raise AttributeError(f"module {__name__} has no attribute {name}")
98+
msg = f"module {__name__} has no attribute {name}"
99+
raise AttributeError(msg)
100100

101101

102-
class Noise(object):
102+
class Noise:
103103
"""A configurable noise sampler.
104104
105105
The ``hurst`` exponent describes the raggedness of the resultant noise,
@@ -130,10 +130,11 @@ def __init__(
130130
hurst: float = 0.5,
131131
lacunarity: float = 2.0,
132132
octaves: float = 4,
133-
seed: Optional[Union[int, tcod.random.Random]] = None,
134-
):
133+
seed: int | tcod.random.Random | None = None,
134+
) -> None:
135135
if not 0 < dimensions <= 4:
136-
raise ValueError("dimensions must be in range 0 < n <= 4, got %r" % (dimensions,))
136+
msg = f"dimensions must be in range 0 < n <= 4, got {dimensions}"
137+
raise ValueError(msg)
137138
self._seed = seed
138139
self._random = self.__rng_from_seed(seed)
139140
_random_c = self._random.random_c
@@ -149,7 +150,7 @@ def __init__(
149150
self.implementation = implementation # sanity check
150151

151152
@staticmethod
152-
def __rng_from_seed(seed: Union[None, int, tcod.random.Random]) -> tcod.random.Random:
153+
def __rng_from_seed(seed: None | int | tcod.random.Random) -> tcod.random.Random:
153154
if seed is None or isinstance(seed, int):
154155
return tcod.random.Random(seed=seed, algorithm=tcod.random.MERSENNE_TWISTER)
155156
return seed
@@ -174,11 +175,6 @@ def __repr__(self) -> str:
174175
def dimensions(self) -> int:
175176
return int(self._tdl_noise_c.dimensions)
176177

177-
@property
178-
@deprecate("This is a misspelling of 'dimensions'.", FutureWarning)
179-
def dimentions(self) -> int:
180-
return self.dimensions
181-
182178
@property
183179
def algorithm(self) -> int:
184180
noise_type = self.noise_c.noise_type
@@ -195,7 +191,8 @@ def implementation(self) -> int:
195191
@implementation.setter
196192
def implementation(self, value: int) -> None:
197193
if not 0 <= value < 3:
198-
raise ValueError("%r is not a valid implementation. " % (value,))
194+
msg = f"{value!r} is not a valid implementation. "
195+
raise ValueError(msg)
199196
self._tdl_noise_c.implementation = value
200197

201198
@property
@@ -242,7 +239,8 @@ def __getitem__(self, indexes: Any) -> NDArray[np.float32]:
242239
c_input = [ffi.NULL, ffi.NULL, ffi.NULL, ffi.NULL]
243240
for i, index in enumerate(indexes):
244241
if index.dtype.type == np.object_:
245-
raise TypeError("Index arrays can not be of dtype np.object_.")
242+
msg = "Index arrays can not be of dtype np.object_."
243+
raise TypeError(msg)
246244
indexes[i] = np.ascontiguousarray(index, dtype=np.float32)
247245
c_input[i] = ffi.from_buffer("float*", indexes[i])
248246

@@ -296,12 +294,12 @@ def sample_mgrid(self, mgrid: ArrayLike) -> NDArray[np.float32]:
296294
"""
297295
mgrid = np.ascontiguousarray(mgrid, np.float32)
298296
if mgrid.shape[0] != self.dimensions:
299-
raise ValueError(
300-
"mgrid.shape[0] must equal self.dimensions, " "%r[0] != %r" % (mgrid.shape, self.dimensions)
301-
)
297+
msg = f"mgrid.shape[0] must equal self.dimensions, {mgrid.shape!r}[0] != {self.dimensions!r}"
298+
raise ValueError(msg)
302299
out: np.ndarray[Any, np.dtype[np.float32]] = np.ndarray(mgrid.shape[1:], np.float32)
303300
if mgrid.shape[1:] != out.shape:
304-
raise ValueError("mgrid.shape[1:] must equal out.shape, " "%r[1:] != %r" % (mgrid.shape, out.shape))
301+
msg = f"mgrid.shape[1:] must equal out.shape, {mgrid.shape!r}[1:] != {out.shape!r}"
302+
raise ValueError(msg)
305303
lib.NoiseSampleMeshGrid(
306304
self._tdl_noise_c,
307305
out.size,
@@ -323,8 +321,9 @@ def sample_ogrid(self, ogrid: Sequence[ArrayLike]) -> NDArray[np.float32]:
323321
The ``dtype`` is `numpy.float32`.
324322
"""
325323
if len(ogrid) != self.dimensions:
326-
raise ValueError("len(ogrid) must equal self.dimensions, " "%r != %r" % (len(ogrid), self.dimensions))
327-
ogrids: List[NDArray[np.float32]] = [np.ascontiguousarray(array, np.float32) for array in ogrid]
324+
msg = f"len(ogrid) must equal self.dimensions, {len(ogrid)!r} != {self.dimensions!r}"
325+
raise ValueError(msg)
326+
ogrids: list[NDArray[np.float32]] = [np.ascontiguousarray(array, np.float32) for array in ogrid]
328327
out: np.ndarray[Any, np.dtype[np.float32]] = np.ndarray([array.size for array in ogrids], np.float32)
329328
lib.NoiseSampleOpenMeshGrid(
330329
self._tdl_noise_c,
@@ -335,7 +334,7 @@ def sample_ogrid(self, ogrid: Sequence[ArrayLike]) -> NDArray[np.float32]:
335334
)
336335
return out
337336

338-
def __getstate__(self) -> Any:
337+
def __getstate__(self) -> dict[str, Any]:
339338
state = self.__dict__.copy()
340339
if self.dimensions < 4 and self.noise_c.waveletTileData == ffi.NULL:
341340
# Trigger a side effect of wavelet, so that copies will be synced.
@@ -366,7 +365,7 @@ def __getstate__(self) -> Any:
366365
}
367366
return state
368367

369-
def __setstate__(self, state: Any) -> None:
368+
def __setstate__(self, state: dict[str, Any]) -> None:
370369
if isinstance(state, tuple): # deprecated format
371370
return self._setstate_old(state)
372371
# unpack wavelet tile data if it exists
@@ -384,6 +383,7 @@ def __setstate__(self, state: Any) -> None:
384383
state["_tdl_noise_c"]["noise"] = state["noise_c"]
385384
state["_tdl_noise_c"] = ffi.new("TDLNoise*", state["_tdl_noise_c"])
386385
self.__dict__.update(state)
386+
return None
387387

388388
def _setstate_old(self, state: Any) -> None:
389389
self._random = state[0]
@@ -403,11 +403,11 @@ def _setstate_old(self, state: Any) -> None:
403403

404404

405405
def grid(
406-
shape: Tuple[int, ...],
407-
scale: Union[Tuple[float, ...], float],
408-
origin: Optional[Tuple[int, ...]] = None,
406+
shape: tuple[int, ...],
407+
scale: tuple[float, ...] | float,
408+
origin: tuple[int, ...] | None = None,
409409
indexing: Literal["ij", "xy"] = "xy",
410-
) -> Tuple[NDArray[Any], ...]:
410+
) -> tuple[NDArray[Any], ...]:
411411
"""Generate a mesh-grid of sample points to use with noise sampling.
412412
413413
Args:
@@ -444,14 +444,16 @@ def grid(
444444
dtype=float32)
445445
446446
.. versionadded:: 12.2
447-
""" # noqa: E501
447+
"""
448448
if isinstance(scale, float):
449449
scale = (scale,) * len(shape)
450450
if origin is None:
451451
origin = (0,) * len(shape)
452452
if len(shape) != len(scale):
453-
raise TypeError("shape must have the same length as scale")
453+
msg = "shape must have the same length as scale"
454+
raise TypeError(msg)
454455
if len(shape) != len(origin):
455-
raise TypeError("shape must have the same length as origin")
456+
msg = "shape must have the same length as origin"
457+
raise TypeError(msg)
456458
indexes = (np.arange(i_shape) * i_scale + i_origin for i_shape, i_scale, i_origin in zip(shape, scale, origin))
457459
return tuple(np.meshgrid(*indexes, copy=False, sparse=True, indexing=indexing))

0 commit comments

Comments
 (0)