Skip to content

Commit 43b23ad

Browse files
committed
Fix linting issues.
1 parent a8b8c2b commit 43b23ad

28 files changed

+153
-134
lines changed

docs/cli_usage.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,10 @@ extra protocol. For the above example it would look like this:
208208
In one line:
209209

210210
```json
211-
{"s3": {"key": "my_super_private_key", "secret": "my_super_private_secret"}, "simplecache": {"cache_storage": "/custom/temp/storage/path"}}
211+
{
212+
"s3": { "key": "my_super_private_key", "secret": "my_super_private_secret" },
213+
"simplecache": { "cache_storage": "/custom/temp/storage/path" }
214+
}
212215
```
213216

214217
## CLI Reference

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,7 @@ select = [
116116
ignore = [
117117
"ANN101", # Missing type annotation for `self`
118118
"D107", # Missing docstring in __init__ ; should be in class docstring
119+
"TD003", # Missing issue link following TODO
119120
]
120121

121122
[tool.ruff.lint.per-file-ignores]

src/mdio/__main__.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,18 @@
33
from __future__ import annotations
44

55
import importlib
6-
from collections.abc import Callable
76
from importlib import metadata
87
from pathlib import Path
9-
8+
from typing import TYPE_CHECKING
109
from typing import Any
11-
from typing import Callable
1210

1311
import click
1412

1513

14+
if TYPE_CHECKING:
15+
from collections.abc import Callable
16+
17+
1618
KNOWN_MODULES = [
1719
"segy.py",
1820
"copy.py",
@@ -30,11 +32,12 @@ class MyCLI(click.MultiCommand):
3032
must have a variable named `cli` for the command to be exposed.
3133
3234
Args:
33-
- plugin_folder: Path to the directory containing command modules.
35+
plugin_folder: Path to the directory containing command modules.
36+
*args: Any positional arguments.
37+
**kwargs: Any keyword arguments.
3438
"""
3539

3640
def __init__(self, plugin_folder: Path, *args: Any, **kwargs: Any) -> None: # noqa: ANN401
37-
"""Initializer function."""
3841
super().__init__(*args, **kwargs)
3942
self.plugin_folder = plugin_folder
4043
self.known_modules = KNOWN_MODULES

src/mdio/api/accessor.py

Lines changed: 34 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,8 @@
22

33
from __future__ import annotations
44

5-
from typing import TYPE_CHECKING
6-
75
import logging
6+
from typing import TYPE_CHECKING
87

98
import numpy as np
109
import numpy.typing as npt
@@ -19,14 +18,15 @@
1918
from mdio.core.exceptions import MDIONotFoundError
2019
from mdio.exceptions import ShapeError
2120

21+
2222
if TYPE_CHECKING:
2323
import dask.array as da
2424
from numpy.typing import NDArray
2525

2626
logger = logging.getLogger(__name__)
2727

2828

29-
class MDIOAccessor:
29+
class MDIOAccessor: # noqa: DOC502
3030
"""Accessor class for MDIO files.
3131
3232
The accessor can be used to read and write MDIO files. It allows you to
@@ -138,7 +138,7 @@ class MDIOAccessor:
138138
"dask": open_zarr_array_dask,
139139
}
140140

141-
def __init__(
141+
def __init__( # noqa: PLR0913
142142
self,
143143
mdio_path_or_buffer: str,
144144
mode: str,
@@ -150,7 +150,6 @@ def __init__(
150150
memory_cache_size: int,
151151
disk_cache: bool,
152152
):
153-
"""Accessor initialization function."""
154153
# Set public attributes
155154
self.url = mdio_path_or_buffer
156155
self.mode = mode
@@ -180,11 +179,24 @@ def __init__(
180179

181180
# Call methods to finish initialization
182181
self._validate_store(storage_options)
183-
self._connect()
182+
self._connect() # noqa: DOC502
184183
self._deserialize_grid()
185184
self._set_attributes()
186185
self._open_arrays()
187186

187+
if False:
188+
"""
189+
This code block is inert and is intended only to satisfy the linter.
190+
191+
Pre-commit linting causes some issues.
192+
The __init__ method raises an error from the _connect method.
193+
Since the error isn't raised directly from the __init__ method,
194+
the linter complains and the noqa: DOC502 is ignored.
195+
Disabling the DOC502 globally is not desirable.
196+
"""
197+
err = "noqa: DOC502"
198+
raise MDIONotFoundError(err)
199+
188200
def _validate_store(self, storage_options: dict[str, str] | None) -> None:
189201
"""Method to validate the provided store."""
190202
if storage_options is None:
@@ -317,7 +329,8 @@ def shape(self) -> tuple[int, ...]:
317329
def shape(self, value: tuple[int, ...]) -> None:
318330
"""Validate and set shape of dataset."""
319331
if not isinstance(value, tuple):
320-
raise AttributeError("Array shape needs to be a tuple")
332+
err = "Array shape needs to be a tuple"
333+
raise AttributeError(err)
321334
self._shape = value
322335

323336
@property
@@ -329,7 +342,8 @@ def trace_count(self) -> int:
329342
def trace_count(self, value: int) -> None:
330343
"""Validate and set trace count for seismic MDIO."""
331344
if not isinstance(value, int):
332-
raise AttributeError("Live trace count needs to be an integer")
345+
err = "Live trace count needs to be an integer"
346+
raise AttributeError(err)
333347
self._trace_count = value
334348

335349
@property
@@ -341,7 +355,8 @@ def text_header(self) -> list:
341355
def text_header(self, value: list) -> None:
342356
"""Validate and set seismic text header."""
343357
if not isinstance(value, list):
344-
raise AttributeError("Text header must be a list of str with 40 elements")
358+
err = "Text header must be a list of str with 40 elements"
359+
raise AttributeError(err)
345360
self._text_header = value
346361

347362
@property
@@ -353,7 +368,8 @@ def binary_header(self) -> dict:
353368
def binary_header(self, value: dict) -> None:
354369
"""Validate and set seismic binary header metadata."""
355370
if not isinstance(value, dict):
356-
raise AttributeError("Binary header has to be a dictionary type collection")
371+
err = "Binary header has to be a dictionary type collection"
372+
raise AttributeError(err)
357373
self._binary_header = value
358374

359375
@property
@@ -486,8 +502,9 @@ def coord_to_index(
486502
ndim_expect = self.grid.ndim if dimensions is None else len(dimensions)
487503

488504
if len(queries) != ndim_expect:
505+
err = "Coordinate queries not the same size as n_dimensions"
489506
raise ShapeError(
490-
"Coordinate queries not the same size as n_dimensions",
507+
err,
491508
("# Coord Dims", "# Dimensions"),
492509
(len(queries), ndim_expect),
493510
)
@@ -558,6 +575,8 @@ def copy( # noqa: PLR0913
558575
class MDIOReader(MDIOAccessor):
559576
"""Read-only accessor for MDIO files.
560577
578+
Initialized with `r` permission.
579+
561580
For detailed documentation see MDIOAccessor.
562581
563582
Args:
@@ -596,8 +615,7 @@ def __init__( # noqa: PLR0913
596615
backend: str = "zarr",
597616
memory_cache_size: int = 0,
598617
disk_cache: bool = False,
599-
): # TODO: Disabled all caching by default, sometimes causes performance issues
600-
"""Initialize super class with `r` permission."""
618+
): # TODO(anyone): Disabled all caching by default, sometimes causes performance issues
601619
super().__init__(
602620
mdio_path_or_buffer=mdio_path_or_buffer,
603621
mode="r",
@@ -614,6 +632,8 @@ def __init__( # noqa: PLR0913
614632
class MDIOWriter(MDIOAccessor):
615633
"""Writable accessor for MDIO files.
616634
635+
Initialized with `r+` permission.
636+
617637
For detailed documentation see MDIOAccessor.
618638
619639
Args:
@@ -652,8 +672,7 @@ def __init__( # noqa: PLR0913
652672
backend: str = "zarr",
653673
memory_cache_size: int = 0,
654674
disk_cache: bool = False,
655-
): # TODO: Disabled all caching by default, sometimes causes performance issues
656-
"""Initialize super class with `r+` permission."""
675+
): # TODO(anyone): Disabled all caching by default, sometimes causes performance issues
657676
super().__init__(
658677
mdio_path_or_buffer=mdio_path_or_buffer,
659678
mode="r+",

src/mdio/api/convenience.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ def create_rechunk_plan(
139139
for chunks, suffix in zip(chunks_list, suffix_list): # noqa: B905
140140
norm_chunks = [
141141
min(chunk, size)
142-
for chunk, size in zip(chunks, source.shape) # noqa: B905
142+
for chunk, size in zip(chunks, source.shape) # noqa: B905
143143
]
144144

145145
if suffix == source.access_pattern:

src/mdio/api/io_utils.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import zarr
1010
from zarr.storage import FSStore
1111

12+
1213
if TYPE_CHECKING:
1314
from pathlib import Path
1415

@@ -94,7 +95,7 @@ def process_url(
9495
# Flag for checking write access
9596
# check = True if mode == "w" else False
9697

97-
# TODO: Turning off write checking now because zarr has a bug.
98+
# TODO(anyone): Turning off write checking now because zarr has a bug.
9899
# Get rid of this once bug is fixed.
99100
check = False
100101

src/mdio/converters/exceptions.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ class EnvironmentFormatError(Exception):
55
"""Raised when environment variable is of the wrong format."""
66

77
def __init__(self, name: str, format_: str, msg: str = "") -> None:
8-
"""Initialize error."""
98
self.message = (
109
f"Environment variable: {name} not of expected format: {format_}. "
1110
)
@@ -17,7 +16,6 @@ class GridTraceCountError(Exception):
1716
"""Raised when grid trace counts don't match the SEG-Y trace count."""
1817

1918
def __init__(self, grid_traces: int, segy_traces: int) -> None:
20-
"""Initialize error."""
2119
self.message = (
2220
f"{grid_traces} != {segy_traces}"
2321
f"Scanned grid trace count ({grid_traces}) doesn't "
@@ -33,7 +31,6 @@ class GridTraceSparsityError(Exception):
3331
"""Raised when mdio grid will be sparsely populated from SEG-Y traces."""
3432

3533
def __init__(self, shape: tuple[int, ...], num_traces: int, msg: str = "") -> None:
36-
"""Initialize error."""
3734
self.message = (
3835
f"Grid shape: {shape} but SEG-Y tracecount: {num_traces}. "
3936
"This grid is very sparse and most likely user error with indexing."

src/mdio/converters/mdio.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
from __future__ import annotations
44

55
import os
6-
from os import path
76
from pathlib import Path
87
from tempfile import TemporaryDirectory
98

@@ -28,7 +27,7 @@
2827
NUM_CPUS = int(os.getenv("MDIO__EXPORT__CPU_COUNT", default_cpus))
2928

3029

31-
def mdio_to_segy( # noqa: C901
30+
def mdio_to_segy( # noqa: C901 PLR0913 PLR0912
3231
mdio_path_or_buffer: str | Path,
3332
output_segy_path: str | Path,
3433
endian: str = "big",
@@ -137,7 +136,8 @@ def mdio_to_segy( # noqa: C901
137136

138137
# This handles the case if we are skipping a whole block.
139138
if live_mask.sum() == 0:
140-
raise ValueError("No traces will be written out. Live mask is empty.")
139+
err = "No traces will be written out. Live mask is empty."
140+
raise ValueError(err)
141141

142142
# Find rough dim limits, so we don't unnecessarily hit disk / cloud store.
143143
# Typically, gets triggered when there is a selection mask
@@ -157,7 +157,7 @@ def mdio_to_segy( # noqa: C901
157157
live_mask = live_mask & selection_mask
158158

159159
# tmp file root
160-
out_dir = path.dirname(output_segy_path)
160+
out_dir = Path(output_segy_path).parent
161161
tmp_dir = TemporaryDirectory(dir=out_dir)
162162

163163
with tmp_dir:

src/mdio/core/dimension.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,11 @@
1212
from mdio.core.serialization import Serializer
1313
from mdio.exceptions import ShapeError
1414

15+
1516
if TYPE_CHECKING:
1617
from numpy.typing import NDArray
1718

19+
1820
@dataclass(eq=False, order=False, slots=True)
1921
class Dimension:
2022
"""Dimension class.
@@ -25,6 +27,10 @@ class Dimension:
2527
Args:
2628
coords: Vector of coordinates.
2729
name: Name of the dimension.
30+
31+
Attributes:
32+
coords: Vector of coordinates.
33+
name: Name of the dimension.
2834
"""
2935

3036
coords: list | tuple | NDArray | range
@@ -34,8 +40,9 @@ def __post_init__(self) -> None:
3440
"""Post process and validation."""
3541
self.coords = np.asarray(self.coords)
3642
if self.coords.ndim != 1:
43+
err = "Dimensions can only have vector coordinates"
3744
raise ShapeError(
38-
"Dimensions can only have vector coordinates",
45+
err,
3946
("# Dim", "Expected"),
4047
(self.coords.ndim, 1),
4148
)
@@ -73,8 +80,8 @@ def __hash__(self) -> int:
7380
def __eq__(self, other: Dimension) -> bool:
7481
"""Compares if the dimension has same properties."""
7582
if not isinstance(other, Dimension):
76-
other_type = type(other).__name__
77-
raise TypeError(f"Can't compare Dimension with {other_type}")
83+
err = f"Can't compare Dimension with {type(other).__name__}"
84+
raise TypeError(err)
7885

7986
return hash(self) == hash(other)
8087

src/mdio/core/exceptions.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,6 @@
66
class MDIOAlreadyExistsError(MDIOError):
77
"""Raised when MDIO file already exists."""
88

9-
pass
10-
119

1210
class MDIONotFoundError(MDIOError):
1311
"""Raised when MDIO file doesn't exist."""
14-
15-
pass

0 commit comments

Comments
 (0)