Skip to content

Commit 8a811f2

Browse files
h-jooXarray-Beam authors
authored andcommitted
Adding type suppressions for pyrefly
PiperOrigin-RevId: 944352684
1 parent 877f598 commit 8a811f2

6 files changed

Lines changed: 69 additions & 68 deletions

File tree

docs/conf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ def linkcode_resolve(domain, info):
118118
except Exception as e:
119119
print(f'did not find source code for: {info}: {e}')
120120
return None
121-
filename = os.path.relpath(
121+
filename = os.path.relpath( # pyrefly: ignore[no-matching-overload]
122122
filename, start=os.path.dirname(xarray_beam.__file__)
123123
)
124124
lines = f'#L{linenum}-L{linenum + len(source)}' if linenum else ''

examples/xbeam_rechunk.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,10 +88,10 @@ def main(argv):
8888

8989
with beam.Pipeline(runner=RUNNER.value, argv=argv) as root:
9090
root |= (
91-
xbeam.Dataset.from_zarr(INPUT_PATH.value, split_vars=True)
91+
xbeam.Dataset.from_zarr(INPUT_PATH.value, split_vars=True) # pyrefly: ignore[bad-argument-type]
9292
.rechunk(target_chunks if target_shards is None else target_shards)
9393
.to_zarr(
94-
OUTPUT_PATH.value,
94+
OUTPUT_PATH.value, # pyrefly: ignore[bad-argument-type]
9595
zarr_chunks=target_chunks,
9696
zarr_shards=target_shards,
9797
zarr_format=ZARR_FORMAT.value,

xarray_beam/_src/core.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ def replace(
158158
vars = self.vars
159159
if indices is _DEFAULT:
160160
indices = self.indices
161-
return type(self)(offsets, vars, indices)
161+
return type(self)(offsets, vars, indices) # pyrefly: ignore[bad-argument-type]
162162

163163
def with_offsets(self, **offsets: int | None) -> Key:
164164
"""Replace some offsets with new values.
@@ -401,15 +401,15 @@ def normalize_expanded_chunks(
401401
if dim not in chunks or chunks[dim] == -1:
402402
result[dim] = (dim_size,)
403403
elif isinstance(chunks[dim], tuple):
404-
total = sum(chunks[dim])
404+
total = sum(chunks[dim]) # pyrefly: ignore[no-matching-overload]
405405
if total != dim_size:
406406
raise ValueError(
407407
f"sum of provided chunks does not match size of dimension {dim}: "
408408
f"{total} vs {dim_size}"
409409
)
410410
result[dim] = chunks[dim]
411411
else:
412-
multiple, remainder = divmod(dim_size, chunks[dim])
412+
multiple, remainder = divmod(dim_size, chunks[dim]) # pyrefly: ignore[no-matching-overload]
413413
result[dim] = multiple * (chunks[dim],) + (
414414
(remainder,) if remainder else ()
415415
)
@@ -439,9 +439,9 @@ def __init__(
439439
dask_chunks = self._first.chunks
440440
if not dask_chunks:
441441
raise ValueError("dataset must be chunked or chunks must be provided")
442-
chunks = dask_to_xbeam_chunks(dask_chunks)
442+
chunks = dask_to_xbeam_chunks(dask_chunks) # pyrefly: ignore[bad-assignment]
443443

444-
for k in chunks:
444+
for k in chunks: # pyrefly: ignore[not-iterable]
445445
if k not in self._first.dims:
446446
raise ValueError(
447447
f"chunks key {k!r} is not a dimension on the provided dataset(s)"
@@ -538,7 +538,7 @@ def _key_to_chunks(self, key: Key) -> tuple[Key, DatasetOrDatasets]:
538538
if isinstance(self.dataset, xarray.Dataset):
539539
return key, results[0]
540540
else:
541-
return key, results
541+
return key, results # pyrefly: ignore[bad-return]
542542

543543

544544
@export
@@ -588,7 +588,7 @@ def sharded_dim(self) -> str | None:
588588
# We use the simple heuristic of only sharding inputs along the dimension
589589
# with the most chunks.
590590
lengths = {
591-
k: math.ceil(size / self.chunks.get(k, size))
591+
k: math.ceil(size / self.chunks.get(k, size)) # pyrefly: ignore[missing-attribute]
592592
for k, size in self._first.sizes.items()
593593
}
594594
return max(lengths, key=lengths.get) if lengths else None # pytype: disable=bad-return-type
@@ -624,29 +624,29 @@ def _iter_shard_keys(
624624
if var_name is None:
625625
offsets = self.offsets
626626
else:
627-
offsets = {dim: self.offsets[dim] for dim in self._first[var_name].dims}
627+
offsets = {dim: self.offsets[dim] for dim in self._first[var_name].dims} # pyrefly: ignore[bad-index]
628628

629629
if shard_id is None:
630630
assert self.split_vars
631-
yield from iter_chunk_keys(offsets, vars={var_name})
631+
yield from iter_chunk_keys(offsets, vars={var_name}) # pyrefly: ignore[bad-argument-type]
632632
else:
633633
assert self.split_vars == (var_name is not None)
634634
dim = self.sharded_dim
635-
count = math.ceil(len(self.offsets[dim]) / self.shard_count)
635+
count = math.ceil(len(self.offsets[dim]) / self.shard_count) # pyrefly: ignore[bad-index, unsupported-operation]
636636
dim_slice = slice(shard_id * count, (shard_id + 1) * count)
637-
offsets = {**offsets, dim: offsets[dim][dim_slice]}
637+
offsets = {**offsets, dim: offsets[dim][dim_slice]} # pyrefly: ignore[bad-index, invalid-argument]
638638
vars_ = {var_name} if self.split_vars else None
639-
yield from iter_chunk_keys(offsets, vars=vars_)
639+
yield from iter_chunk_keys(offsets, vars=vars_) # pyrefly: ignore[bad-argument-type]
640640

641641
def _shard_inputs(self) -> list[tuple[int | None, str | None]]:
642642
"""Create inputs for sharded key iterators."""
643643
if not self.split_vars:
644-
return [(i, None) for i in range(self.shard_count)]
644+
return [(i, None) for i in range(self.shard_count)] # pyrefly: ignore[bad-argument-type]
645645

646646
inputs = []
647647
for name, variable in self._first.items():
648648
if self.sharded_dim in variable.dims:
649-
inputs.extend([(i, name) for i in range(self.shard_count)])
649+
inputs.extend([(i, name) for i in range(self.shard_count)]) # pyrefly: ignore[bad-argument-type]
650650
else:
651651
inputs.append((None, name))
652652
return inputs # pytype: disable=bad-return-type # always-use-property-annotation

xarray_beam/_src/dataset.py

Lines changed: 37 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ def _to_human_size(nbytes: int) -> str:
7272
for unit in ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB']:
7373
if nbytes < 1000:
7474
return f'{_at_least_two_digits(nbytes)}{unit}'
75-
nbytes /= 1000
75+
nbytes /= 1000 # pyrefly: ignore[bad-assignment]
7676
nbytes *= 1000
7777
return f'{_at_least_two_digits(nbytes)}EB'
7878

@@ -141,7 +141,7 @@ def normalize_chunks(
141141
"chunks='auto'. Supply an explicit number of bytes instead, e.g., "
142142
"chunks='100MB'."
143143
)
144-
chunks = {k: chunks for k in template.dims}
144+
chunks = {k: chunks for k in template.dims} # pyrefly: ignore[bad-assignment]
145145
elif isinstance(chunks, Mapping):
146146
string_chunks = {v for v in chunks.values() if isinstance(v, str)}
147147
if len(string_chunks) > 1:
@@ -157,9 +157,9 @@ def normalize_chunks(
157157
else:
158158
raise TypeError(f'chunks must be a string or a mapping, got {chunks=}')
159159

160-
if ... in chunks:
161-
default_chunks = chunks[...]
162-
chunks = {k: chunks.get(k, default_chunks) for k in template.dims}
160+
if ... in chunks: # pyrefly: ignore[not-iterable, unsupported-operation]
161+
default_chunks = chunks[...] # pyrefly: ignore[bad-index]
162+
chunks = {k: chunks.get(k, default_chunks) for k in template.dims} # pyrefly: ignore[bad-assignment]
163163

164164
defaults = previous_chunks if previous_chunks else template.sizes
165165
chunks: dict[str, int | str] = {**defaults, **chunks} # pytype: disable=annotation-type-mismatch
@@ -253,6 +253,7 @@ def _normalize_and_validate_chunk(
253253
key = key.replace(vars=set(dataset.keys()))
254254
elif key.vars != set(dataset.keys()):
255255
raise ValueError(
256+
# pyrefly: ignore[bad-specialization]
256257
f'dataset keys {sorted(dataset.keys())} do not match'
257258
f' key.vars={sorted(key.vars)}'
258259
)
@@ -262,7 +263,7 @@ def _normalize_and_validate_chunk(
262263
new_offsets = dict(key.offsets)
263264
for dim in dataset.dims:
264265
if dim not in new_offsets:
265-
new_offsets[dim] = 0
266+
new_offsets[dim] = 0 # pyrefly: ignore[unsupported-operation]
266267
if len(new_offsets) != len(key.offsets):
267268
key = key.replace(offsets=new_offsets)
268269

@@ -353,7 +354,7 @@ def _apply_to_each_chunk(
353354
key.offsets.get(dim, 0) // old_chunks.get(dim, 1) * new_chunks[dim]
354355
)
355356
new_vars = set(new_chunk) if key.vars is not None else None
356-
new_key = core.Key(new_offsets, new_vars)
357+
new_key = core.Key(new_offsets, new_vars) # pyrefly: ignore[bad-argument-type]
357358
return new_key, new_chunk
358359

359360

@@ -516,7 +517,7 @@ def itemsize(self) -> int:
516517
def bytes_per_chunk(self) -> int:
517518
"""Estimate of the number of bytes per dataset chunk."""
518519
variable_sizes = [
519-
v.dtype.itemsize * math.prod(self.chunks[d] for d in v.dims)
520+
v.dtype.itemsize * math.prod(self.chunks[d] for d in v.dims) # pyrefly: ignore[bad-index]
520521
for v in self.template.values()
521522
]
522523
return max(variable_sizes) if self.split_vars else sum(variable_sizes)
@@ -528,7 +529,7 @@ def chunk_count(self) -> int:
528529
total = 0
529530
for variable in self.template.values():
530531
total += math.prod(
531-
math.ceil(self.sizes[d] / self.chunks[d]) for d in variable.dims
532+
math.ceil(self.sizes[d] / self.chunks[d]) for d in variable.dims # pyrefly: ignore[bad-index]
532533
)
533534
return total
534535
else:
@@ -612,13 +613,13 @@ def from_ptransform(
612613
f' got {chunks}'
613614
)
614615

615-
chunks = normalize_chunks(chunks, template)
616+
chunks = normalize_chunks(chunks, template) # pyrefly: ignore[bad-assignment]
616617
ptransform = ptransform | label >> beam.MapTuple(
617618
functools.partial(
618619
_normalize_and_validate_chunk, template, chunks, split_vars
619620
)
620621
)
621-
return cls(template, chunks, split_vars, ptransform)
622+
return cls(template, chunks, split_vars, ptransform) # pyrefly: ignore[bad-argument-type]
622623

623624
@classmethod
624625
def from_xarray(
@@ -650,13 +651,13 @@ def from_xarray(
650651
label = _get_label('from_xarray')
651652
template = zarr.make_template(source)
652653
if previous_chunks is None:
653-
previous_chunks = source.sizes
654-
chunks = normalize_chunks(chunks, template, split_vars, previous_chunks)
655-
ptransform = core.DatasetToChunks(source, chunks, split_vars)
654+
previous_chunks = source.sizes # pyrefly: ignore[bad-assignment]
655+
chunks = normalize_chunks(chunks, template, split_vars, previous_chunks) # pyrefly: ignore[bad-assignment]
656+
ptransform = core.DatasetToChunks(source, chunks, split_vars) # pyrefly: ignore[bad-argument-type]
656657
ptransform.label = label
657658
if pipeline is not None:
658659
ptransform = _LazyPCollection(pipeline, ptransform)
659-
return cls(template, dict(chunks), split_vars, ptransform)
660+
return cls(template, dict(chunks), split_vars, ptransform) # pyrefly: ignore[no-matching-overload]
660661

661662
@classmethod
662663
def from_zarr(
@@ -689,10 +690,10 @@ def from_zarr(
689690
label = _get_label('from_zarr')
690691
source, previous_chunks = zarr.open_zarr(path)
691692
if chunks is None:
692-
chunks = previous_chunks
693+
chunks = previous_chunks # pyrefly: ignore[bad-assignment]
693694
result = cls.from_xarray(
694695
source,
695-
chunks,
696+
chunks, # pyrefly: ignore[bad-argument-type]
696697
split_vars=split_vars,
697698
previous_chunks=previous_chunks,
698699
)
@@ -709,7 +710,7 @@ def _zarr_chunks_per_shard_to_chunks(
709710
"""Convert chunks per shard to chunks."""
710711
chunks_per_shard = dict(zarr_chunks_per_shard)
711712
if ... in chunks_per_shard:
712-
default_cps = chunks_per_shard.pop(...)
713+
default_cps = chunks_per_shard.pop(...) # pyrefly: ignore[bad-argument-type]
713714
else:
714715
default_cps = 1
715716

@@ -808,7 +809,7 @@ def to_zarr(
808809
label = _get_label('to_zarr')
809810

810811
if zarr_shards is not None:
811-
zarr_shards = normalize_chunks(
812+
zarr_shards = normalize_chunks( # pyrefly: ignore[bad-assignment]
812813
zarr_shards,
813814
self.template,
814815
split_vars=self.split_vars,
@@ -821,17 +822,17 @@ def to_zarr(
821822
'cannot supply both zarr_chunks_per_shard and zarr_chunks'
822823
)
823824
if zarr_shards is None:
824-
zarr_shards = self.chunks
825-
zarr_chunks = self._zarr_chunks_per_shard_to_chunks(
826-
zarr_chunks_per_shard, zarr_shards
825+
zarr_shards = self.chunks # pyrefly: ignore[bad-assignment]
826+
zarr_chunks = self._zarr_chunks_per_shard_to_chunks( # pyrefly: ignore[bad-assignment]
827+
zarr_chunks_per_shard, zarr_shards # pyrefly: ignore[bad-argument-type]
827828
)
828829

829830
if zarr_chunks is None:
830831
if zarr_shards is not None:
831832
raise ValueError('cannot supply zarr_shards without zarr_chunks')
832833
zarr_chunks = {}
833834

834-
zarr_chunks = normalize_chunks(
835+
zarr_chunks = normalize_chunks( # pyrefly: ignore[bad-assignment]
835836
zarr_chunks,
836837
self.template,
837838
split_vars=self.split_vars,
@@ -842,23 +843,23 @@ def to_zarr(
842843
# chunk sizes, which means shard sizes must be rounded up to be larger
843844
# than the full dimension size. This will likely be relaxed in the future:
844845
# https://github.com/zarr-developers/zarr-extensions/issues/34
845-
zarr_shards = dict(zarr_shards)
846+
zarr_shards = dict(zarr_shards) # pyrefly: ignore[no-matching-overload]
846847
for k in zarr_shards:
847848
if zarr_shards[k] == self.sizes[k]:
848849
zarr_shards[k] = (
849-
math.ceil(zarr_shards[k] / zarr_chunks[k]) * zarr_chunks[k]
850+
math.ceil(zarr_shards[k] / zarr_chunks[k]) * zarr_chunks[k] # pyrefly: ignore[bad-index, unsupported-operation]
850851
)
851852
self._check_shards_or_chunks(zarr_shards, 'shards')
852853
else:
853-
self._check_shards_or_chunks(zarr_chunks, 'chunks')
854+
self._check_shards_or_chunks(zarr_chunks, 'chunks') # pyrefly: ignore[bad-argument-type]
854855

855856
if zarr_shards is not None and zarr_format is None:
856857
zarr_format = 3 # required for shards
857858

858859
return self.ptransform | label >> zarr.ChunksToZarr(
859860
path,
860861
self.template,
861-
zarr_chunks=zarr_chunks,
862+
zarr_chunks=zarr_chunks, # pyrefly: ignore[bad-argument-type]
862863
zarr_shards=zarr_shards,
863864
zarr_format=zarr_format,
864865
stage_locally=stage_locally,
@@ -936,7 +937,7 @@ def map_blocks(
936937
chunks = _infer_new_chunks(
937938
old_sizes=self.sizes,
938939
old_chunks=self.chunks,
939-
new_sizes=template.sizes,
940+
new_sizes=template.sizes, # pyrefly: ignore[bad-argument-type]
940941
) # pytype: disable=wrong-arg-types
941942

942943
for dim, old_chunks in self.chunks.items():
@@ -998,7 +999,7 @@ def rechunk(
998999
if split_vars is None:
9991000
split_vars = self.split_vars
10001001

1001-
chunks = normalize_chunks(
1002+
chunks = normalize_chunks( # pyrefly: ignore[bad-assignment]
10021003
chunks,
10031004
self.template,
10041005
split_vars=split_vars,
@@ -1007,15 +1008,15 @@ def rechunk(
10071008

10081009
pipeline, ptransform = _split_lazy_pcollection(self._ptransform)
10091010
if isinstance(ptransform, core.DatasetToChunks) and all(
1010-
chunks[k] % self.chunks[k] == 0 for k in chunks
1011+
chunks[k] % self.chunks[k] == 0 for k in chunks # pyrefly: ignore[bad-index, not-iterable]
10111012
):
10121013
# Rechunking can be performed by re-reading the source dataset with new
10131014
# chunks, rather than using a separate rechunking transform.
1014-
ptransform = core.DatasetToChunks(ptransform.dataset, chunks, split_vars)
1015+
ptransform = core.DatasetToChunks(ptransform.dataset, chunks, split_vars) # pyrefly: ignore[bad-argument-type]
10151016
ptransform.label = _concat_labels(ptransform.label, label)
10161017
if pipeline is not None:
10171018
ptransform = _LazyPCollection(pipeline, ptransform)
1018-
return type(self)(self.template, chunks, split_vars, ptransform)
1019+
return type(self)(self.template, chunks, split_vars, ptransform) # pyrefly: ignore[bad-argument-type]
10191020

10201021
# Need to do a full rechunking.
10211022
# If also splitting variables, do that first because smaller itemsize allows
@@ -1024,14 +1025,14 @@ def rechunk(
10241025
rechunk_transform = rechunk.Rechunk(
10251026
prechunked.sizes,
10261027
prechunked.chunks,
1027-
chunks,
1028+
chunks, # pyrefly: ignore[bad-argument-type]
10281029
itemsize=prechunked.itemsize,
10291030
min_mem=min_mem,
10301031
max_mem=max_mem,
10311032
)
10321033
ptransform = prechunked.ptransform | label >> rechunk_transform
10331034
rechunked = type(self)(
1034-
self.template, chunks, prechunked.split_vars, ptransform
1035+
self.template, chunks, prechunked.split_vars, ptransform # pyrefly: ignore[bad-argument-type]
10351036
)
10361037
result = rechunked if split_vars else rechunked.consolidate_variables()
10371038
return result
@@ -1086,13 +1087,13 @@ def mean(
10861087
else:
10871088
dims = dim
10881089
if label is None:
1089-
label = _get_label(f"mean_{'_'.join(dims)}")
1090+
label = _get_label(f"mean_{'_'.join(dims)}") # pyrefly: ignore[no-matching-overload]
10901091
template = zarr.make_template(
10911092
self.template.mean(dim=dims, skipna=skipna, dtype=dtype)
10921093
)
10931094
new_chunks = {k: v for k, v in self.chunks.items() if k not in dims}
10941095
ptransform = self.ptransform | label >> combiners.MultiStageMean(
1095-
dims=dims,
1096+
dims=dims, # pyrefly: ignore[bad-argument-type]
10961097
skipna=skipna,
10971098
dtype=dtype,
10981099
chunks=self.chunks,

0 commit comments

Comments
 (0)