Skip to content

Commit 368bf1d

Browse files
DanielYang59janosh
andauthored
ruff fixes (#196)
* ruff fixes * fix s101 use of assert * globally ignore SLF001, access private class member * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * add todo tag * put docstring and global ignore on top * fix py017, properly capture exception * Fix PT011, exception capture without match * add TODO tag for #195 (comment) * fix NPY201, np trapz * use warn over print to fix T201 * add comments for globally ignored ruff rules * guard type check only import when possible * remove ISC001 from ignore * add todo tag * reduce duration items shown to 20 * import Self from typing extension * remove global ignore of S311 as there're only 2 violation * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * replace random with numpy, which also fixes S311 * fix "PT006", # pytest-parametrize-names-wrong-type * guard type check only import * fix "COM812", # trailing comma missing * remove no type check mark * Revert "fix "COM812", # trailing comma missing" This reverts commit 5ab3390. * fix unit test of io * NEED confirm: change width from 457 to 458 * clean up branch condition * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * use native array size arg * revert accidental elem -> element rename * fix random array generation * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * fix random array generate in asset maker * revert test_io value to 457, reason unknown * skip eslint for now #197 * format pre-commit config * remove eslint skip mark in CI * fix indentation in pyproject.toml * drop quotes in test.yml string * fix typo in filename * fix shaded_ys type * remove overwriting pytest duration * pyproject whitespace --------- Co-authored-by: Janosh Riebesell <[email protected]>
1 parent 5a3c592 commit 368bf1d

36 files changed

+252
-158
lines changed

.pre-commit-config.yaml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
ci:
22
autoupdate_schedule: quarterly
3-
skip: [pyright, eslint]
3+
skip: [pyright]
44

55
default_stages: [commit]
66

@@ -76,6 +76,7 @@ repos:
7676
rev: v9.9.1
7777
hooks:
7878
- id: eslint
79+
stages: [manual] # TODO: skip eslint for now
7980
types: [file]
8081
args: [--fix, --config, site/eslint.config.js]
8182
files: \.(js|ts|svelte)$

examples/dataset_exploration/ricci_carrier_transport/convert_dtype+add_strucs.py renamed to examples/dataset_exploration/ricci_carrier_transport/convert_dtype+add_structs.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
# ruff: noqa: RUF001
2+
"""Unprocessed data in data/carrier_transport.json.gz obtained from https://git.io/JOMwY."""
3+
14
# %%
25
import pandas as pd
36
from matminer.datasets import load_dataset
@@ -6,12 +9,6 @@
69
from pymatviz.enums import Key
710

811

9-
"""
10-
Unprocessed data in data/carrier_transport.json.gz obtained from https://git.io/JOMwY.
11-
"""
12-
# ruff: noqa: RUF001
13-
14-
1512
# %%
1613
df_carrier = load_dataset("ricci_boltztrap_mp_tabular")
1714

examples/make_assets/phonons.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from pymatviz.enums import Key
1212

1313

14+
# TODO: ffonons not working properly (see #195)
1415
try:
1516
import ffonons # noqa: F401
1617
except ImportError:

examples/make_assets/ptable/ptable_matplotlib.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
# %%
2-
import random
3-
42
import numpy as np
53
from matminer.datasets import load_dataset
64
from pymatgen.core.periodic_table import Element
@@ -137,11 +135,10 @@
137135

138136

139137
# %% Evenly-split tile plots laid out as a periodic table
138+
rng = np.random.default_rng()
140139
for n_splits in (2, 3, 4):
141140
data_dict = {
142-
elem.symbol: [
143-
random.randint(10 * n_splits, 20 * (n_splits + 1)) for _ in range(n_splits)
144-
]
141+
elem.symbol: rng.integers(10 * n_splits, 20 * (n_splits + 1), size=n_splits)
145142
for elem in Element
146143
}
147144

pymatviz/bar.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from __future__ import annotations
44

55
from collections.abc import Sequence
6-
from typing import Any, Literal, cast
6+
from typing import TYPE_CHECKING, cast
77

88
import matplotlib.pyplot as plt
99
import numpy as np
@@ -19,6 +19,10 @@
1919
from pymatviz.utils import PLOTLY, Backend, crystal_sys_from_spg_num, si_fmt_int
2020

2121

22+
if TYPE_CHECKING:
23+
from typing import Any, Literal
24+
25+
2226
def spacegroup_bar(
2327
data: Sequence[int | str | Structure] | pd.Series,
2428
*,

pymatviz/cumulative.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,15 @@
22

33
from __future__ import annotations
44

5-
from typing import TYPE_CHECKING, Any
5+
from typing import TYPE_CHECKING
66

77
import matplotlib.pyplot as plt
88
import numpy as np
99

1010

1111
if TYPE_CHECKING:
12+
from typing import Any
13+
1214
from numpy.typing import ArrayLike
1315

1416

pymatviz/enums.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,11 @@
1010

1111

1212
if TYPE_CHECKING:
13-
from typing import Any, Self
13+
from typing import Any
1414

15+
from typing_extensions import Self
16+
17+
# TODO: remove following definition of StrEnum once Python 3.11+
1518
if sys.version_info >= (3, 11):
1619
from enum import StrEnum
1720
else:

pymatviz/histogram.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22

33
from __future__ import annotations
44

5-
from typing import TYPE_CHECKING, Any, Literal
5+
import warnings
6+
from typing import TYPE_CHECKING
67

78
import matplotlib.pyplot as plt
89
import numpy as np
@@ -17,15 +18,18 @@
1718

1819
if TYPE_CHECKING:
1920
from collections.abc import Sequence
21+
from typing import Any, Literal
2022

2123
from pymatviz.utils import ElemValues
2224

2325

2426
def spacegroup_hist(*args: Any, **kwargs: Any) -> plt.Axes | go.Figure:
2527
"""Alias for spacegroup_bar."""
26-
print( # noqa: T201
28+
warnings.warn(
2729
"spacegroup_hist() is deprecated and will be removed in a future version. "
28-
"use pymatviz.bar.spacegroup_bar() instead."
30+
"use pymatviz.bar.spacegroup_bar() instead.",
31+
category=DeprecationWarning,
32+
stacklevel=2,
2933
)
3034
return spacegroup_bar(*args, **kwargs)
3135

pymatviz/io.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,11 @@
55
import copy
66
import os
77
import subprocess
8+
import warnings
89
from pathlib import Path
910
from shutil import which
1011
from time import sleep
11-
from typing import TYPE_CHECKING, Any, Final, Literal
12+
from typing import TYPE_CHECKING
1213

1314
import matplotlib.pyplot as plt
1415
import numpy as np
@@ -26,6 +27,7 @@
2627
if TYPE_CHECKING:
2728
from collections.abc import Callable, Sequence
2829
from pathlib import Path
30+
from typing import Any, Final, Literal
2931

3032
import pandas as pd
3133
from pandas.io.formats.style import Styler
@@ -313,7 +315,10 @@ def normalize_and_crop_pdf(
313315
if on_gs_not_found == "ignore":
314316
return
315317
if on_gs_not_found == "warn":
316-
print("Ghostscript not found, skipping PDF normalization and cropping") # noqa: T201
318+
warnings.warn(
319+
"Ghostscript not found, skipping PDF normalization and cropping",
320+
stacklevel=2,
321+
)
317322
return
318323
raise RuntimeError("Ghostscript not found in PATH")
319324
try:
@@ -337,7 +342,7 @@ def normalize_and_crop_pdf(
337342
)
338343

339344
if stderr:
340-
print(f"pdfCropMargins {stderr=}") # noqa: T201
345+
warnings.warn(f"pdfCropMargins {stderr=}", stacklevel=2)
341346
# something went wrong, remove the cropped PDF
342347
os.remove(cropped_file_path)
343348
else:
@@ -643,6 +648,8 @@ def print_table(
643648
[svgo, "--multipass", "--final-newline", str(file_path)], check=True
644649
)
645650
else:
646-
print("svgo not found in PATH. SVG compression skipped.") # noqa: T201
651+
warnings.warn(
652+
"svgo not found in PATH. SVG compression skipped.", stacklevel=2
653+
)
647654

648655
return fig

pymatviz/phonons.py

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
import sys
66
from dataclasses import dataclass
7-
from typing import TYPE_CHECKING, Any, Literal, get_args, no_type_check
7+
from typing import TYPE_CHECKING, Literal, get_args
88

99
import plotly.express as px
1010
import plotly.graph_objects as go
@@ -18,12 +18,16 @@
1818

1919
if TYPE_CHECKING:
2020
from collections.abc import Sequence
21+
from typing import Any, TypeAlias
2122

2223
import numpy as np
2324
from pymatgen.core import Structure
2425
from typing_extensions import Self
2526

26-
AnyBandStructure = BandStructureSymmLine | PhononBands
27+
AnyBandStructure: TypeAlias = BandStructureSymmLine | PhononBands
28+
YMin: TypeAlias = float | Literal["y_min"]
29+
YMax: TypeAlias = float | Literal["y_max"]
30+
BranchMode: TypeAlias = Literal["union", "intersection"]
2731

2832

2933
@dataclass
@@ -121,21 +125,22 @@ def get_band_xaxis_ticks(
121125
return ticks_x_pos, tick_labels
122126

123127

124-
YMin = float | Literal["y_min"]
125-
YMax = float | Literal["y_max"]
126-
127-
128-
@no_type_check
129128
def _shaded_range(
130-
fig: go.Figure, shaded_ys: dict[tuple[YMin, YMax], dict[str, Any]] | bool | None
129+
fig: go.Figure,
130+
shaded_ys: dict[tuple[YMin | YMax, YMin | YMax], dict[str, Any]] | bool | None,
131131
) -> go.Figure:
132132
if shaded_ys is False:
133133
return fig
134134

135135
shade_defaults = dict(layer="below", row="all", col="all")
136-
y_lim = dict(zip(("y_min", "y_max"), fig.layout.yaxis.range, strict=True))
136+
y_lim: dict[float | Literal["y_min", "y_max"], Any] = dict(
137+
zip(("y_min", "y_max"), fig.layout.yaxis.range, strict=True),
138+
)
137139

138140
shaded_ys = shaded_ys or {(0, "y_min"): dict(fillcolor="gray", opacity=0.07)}
141+
if not isinstance(shaded_ys, dict):
142+
raise TypeError(f"expect shaded_ys as dict, got {type(shaded_ys).__name__}")
143+
139144
for (y0, y1), kwds in shaded_ys.items():
140145
for y_val in (y0, y1):
141146
if isinstance(y_val, str) and y_val not in y_lim:
@@ -147,15 +152,14 @@ def _shaded_range(
147152
return fig
148153

149154

150-
BranchMode = Literal["union", "intersection"]
151-
152-
153155
def phonon_bands(
154156
band_structs: PhononBands | dict[str, PhononBands],
155157
line_kwargs: dict[str, Any] | None = None,
156158
branches: Sequence[str] = (),
157159
branch_mode: BranchMode = "union",
158-
shaded_ys: dict[tuple[YMin, YMax], dict[str, Any]] | bool | None = None,
160+
shaded_ys: dict[tuple[YMin | YMax, YMin | YMax], dict[str, Any]]
161+
| bool
162+
| None = None,
159163
**kwargs: Any,
160164
) -> go.Figure:
161165
"""Plot single or multiple pymatgen band structures using Plotly, focusing on the

pymatviz/powerups/both.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from __future__ import annotations
44

5+
import warnings
56
from typing import TYPE_CHECKING, Any
67

78
import matplotlib.pyplot as plt
@@ -177,7 +178,7 @@ def add_identity_line(
177178
xy_min_min = min(x_min, y_min)
178179
xy_max_min = min(x_max, y_max)
179180

180-
if fig._grid_ref is not None: # noqa: SLF001
181+
if fig._grid_ref is not None:
181182
kwargs.setdefault("row", "all")
182183
kwargs.setdefault("col", "all")
183184

@@ -264,10 +265,11 @@ def add_best_fit_line(
264265
if n_traces > 1 and warn and not is_faceted:
265266
# for a faceted plot, multiple traces are expected so doesn't make sense to
266267
# warn even if user may have wanted to specify trace_idx. we can't know
267-
print( # noqa: T201
268+
warnings.warn(
268269
f"add_best_fit_line Warning: {trace_idx=} but figure has {n_traces}"
269270
" traces, defaulting to trace_idx=0. Check fig.data[0] to make sure"
270-
" this is the expected trace."
271+
" this is the expected trace.",
272+
stacklevel=2,
271273
)
272274
trace_idx = 0
273275

pymatviz/powerups/plotly.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ def add_ecdf_line(
7070
ecdf_trace = px.ecdf(values).data[0]
7171

7272
# if fig has facets, add ECDF to all subplots
73-
fig_add_trace_defaults = {} if fig._grid_ref is None else dict(row="all", col="all") # noqa: SLF001
73+
fig_add_trace_defaults = {} if fig._grid_ref is None else dict(row="all", col="all")
7474
fig.add_trace(ecdf_trace, **fig_add_trace_defaults | kwargs)
7575

7676
# get xlabel falling back on 'x' if not set
@@ -129,7 +129,7 @@ def add_ecdf_line(
129129
yaxis2_layout = getattr(fig.layout, "yaxis2", {})
130130
if yaxis2_layout:
131131
# convert to dict
132-
yaxis2_layout = yaxis2_layout._props # type: ignore[union-attr] # noqa: SLF001
132+
yaxis2_layout = yaxis2_layout._props # type: ignore[union-attr]
133133
fig.layout.yaxis2 = yaxis_defaults | yaxis2_layout
134134

135135
return fig

pymatviz/ptable/_process_data.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
import warnings
66
from collections.abc import Iterable, Sequence
7-
from typing import TYPE_CHECKING, Literal, TypeAlias, get_args
7+
from typing import TYPE_CHECKING, get_args
88

99
import numpy as np
1010
import pandas as pd
@@ -15,7 +15,7 @@
1515

1616
if TYPE_CHECKING:
1717
from collections.abc import Callable
18-
from typing import Any
18+
from typing import Any, Literal, TypeAlias
1919

2020
from numpy.typing import NDArray
2121

pymatviz/sankey.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,14 @@
22

33
from __future__ import annotations
44

5-
from typing import TYPE_CHECKING, Any, Literal
5+
from typing import TYPE_CHECKING
66

77
import plotly.graph_objects as go
88

99

1010
if TYPE_CHECKING:
11+
from typing import Any, Literal
12+
1113
import pandas as pd
1214

1315

0 commit comments

Comments
 (0)