Skip to content

Commit 0d675d6

Browse files
committed
deepzoom: fix level_dimensions type hint
level_dimensions is always a tuple of 2-tuples. Prove this to the type checker. Signed-off-by: Benjamin Gilbert <[email protected]>
1 parent f24c1dd commit 0d675d6

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

openslide/deepzoom.py

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,17 @@
2727

2828
from io import BytesIO
2929
import math
30+
from typing import TYPE_CHECKING
3031
from xml.etree.ElementTree import Element, ElementTree, SubElement
3132

3233
from PIL import Image
3334

3435
import openslide
3536

37+
if TYPE_CHECKING:
38+
# Python 3.10+
39+
from typing import TypeGuard
40+
3641

3742
class DeepZoomGenerator:
3843
"""Generates Deep Zoom tiles and metadata."""
@@ -104,7 +109,8 @@ def __init__(
104109
while z_size[0] > 1 or z_size[1] > 1:
105110
z_size = tuple(max(1, int(math.ceil(z / 2))) for z in z_size)
106111
z_dimensions.append(z_size)
107-
self._z_dimensions = tuple(reversed(z_dimensions))
112+
# Narrow the type, for self.level_dimensions
113+
self._z_dimensions = self._pairs_from_n_tuples(tuple(reversed(z_dimensions)))
108114

109115
# Tile
110116
def tiles(z_lim: int) -> int:
@@ -161,7 +167,7 @@ def level_tiles(self) -> tuple[tuple[int, int], ...]:
161167
return self._t_dimensions
162168

163169
@property
164-
def level_dimensions(self) -> tuple[tuple[int, ...], ...]:
170+
def level_dimensions(self) -> tuple[tuple[int, int], ...]:
165171
"""A list of (pixels_x, pixels_y) tuples for each Deep Zoom level."""
166172
return self._z_dimensions
167173

@@ -255,6 +261,18 @@ def _l_from_z(self, dz_level: int, z: int) -> float:
255261
def _z_from_t(self, t: int) -> int:
256262
return self._z_t_downsample * t
257263

264+
@staticmethod
265+
def _pairs_from_n_tuples(
266+
tuples: tuple[tuple[int, ...], ...]
267+
) -> tuple[tuple[int, int], ...]:
268+
def all_pairs(
269+
tuples: tuple[tuple[int, ...], ...]
270+
) -> TypeGuard[tuple[tuple[int, int], ...]]:
271+
return all(len(t) == 2 for t in tuples)
272+
273+
assert all_pairs(tuples)
274+
return tuples
275+
258276
def get_tile_coordinates(
259277
self, level: int, address: tuple[int, int]
260278
) -> tuple[tuple[int, int], int, tuple[int, int]]:

0 commit comments

Comments
 (0)