Skip to content

Commit

Permalink
chore: use more ruff (#524)
Browse files Browse the repository at this point in the history
Signed-off-by: Henry Schreiner <[email protected]>
  • Loading branch information
henryiii authored Oct 8, 2024
1 parent 3ad1a71 commit 906d9a2
Show file tree
Hide file tree
Showing 21 changed files with 226 additions and 207 deletions.
22 changes: 2 additions & 20 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,31 +16,13 @@ repos:
- id: requirements-txt-fixer
- id: trailing-whitespace

- repo: https://github.com/asottile/setup-cfg-fmt
rev: "v2.5.0"
hooks:
- id: setup-cfg-fmt
args: ["--include-version-classifiers", "--max-py-version=3.12"]

- repo: https://github.com/nbQA-dev/nbQA
rev: 1.8.7
hooks:
- id: nbqa-pyupgrade
additional_dependencies: [pyupgrade]
args: ["--py38-plus"]

- repo: https://github.com/psf/black-pre-commit-mirror
rev: 24.8.0
hooks:
- id: black-jupyter

- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.6.7
rev: v0.6.9
hooks:
# Run the linter.
- id: ruff
args: [ --fix ]
args: [ --fix, --show-fixes ]
# Run the formatter.
- id: ruff-format

Expand Down
13 changes: 5 additions & 8 deletions docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,9 @@
# Add mplhep to path for sphinx-automodapi
sys.path.insert(0, os.path.abspath("../../src"))

import mplhep # noqa: E402
from pathlib import Path

print("sys.path:", sys.path)
print("mplhep version:", mplhep.__version__)
import mplhep

# -- Project information -----------------------------------------------------

Expand Down Expand Up @@ -70,19 +68,18 @@ def linkcode_resolve(domain, info):
mod = importlib.import_module(info["module"])
modpath = [p for p in sys.path if mod.__file__.startswith(p)]
if len(modpath) < 1:
raise RuntimeError("Cannot deduce module path")
msg = "Cannot deduce module path"
raise RuntimeError(msg)
modpath = modpath[0]
obj = reduce(getattr, [mod] + info["fullname"].split("."))
obj = reduce(getattr, [mod, *info["fullname"].split(".")])
try:
path = inspect.getsourcefile(obj)
relpath = path[len(modpath) + 1 :]
_, lineno = inspect.getsourcelines(obj)
except TypeError:
# skip property or other type that inspect doesn't like
return None
return "http://github.com/scikit-hep/mplhep/blob/{}/{}#L{}".format(
githash, relpath, lineno
)
return f"http://github.com/scikit-hep/mplhep/blob/{githash}/{relpath}#L{lineno}"


intersphinx_mapping = {
Expand Down
2 changes: 1 addition & 1 deletion examples/Examples.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np\n",
"\n",
"import mplhep as hep"
]
Expand Down
58 changes: 47 additions & 11 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,7 @@ dependencies = [

[project.optional-dependencies]
dev = [
"black",
"bumpversion",
"flake8",
"jupyter",
"pre-commit",
"twine",
Expand Down Expand Up @@ -67,14 +65,16 @@ version.source = "vcs"
build.hooks.vcs.version-file = "src/mplhep/_version.py"


[tool.nbqa.mutate]
pyupgrade = 1

[tool.nbqa.addopts]
pyupgrade = ["--py38-plus"]
[tool.uv]
environments = [
"python_version >= '3.10'",
]
dev-dependencies = [
"mplhep[test]",
]


[tools.mypy]
[tool.mypy]
files = ["src"]
python_version = 3.8
warn_unused_configs = true
Expand All @@ -85,7 +85,7 @@ allow_redefinition = true
# disallow_untyped_calls = true
# disallow_untyped_defs = true
# disallow_incomplete_defs = true
check_untyped_defs = true
check_untyped_defs = false
# disallow_untyped_decorators = true
# no_implicit_optional = true
# warn_redundant_casts = true
Expand All @@ -106,5 +106,41 @@ testpaths = ["tests"]
python_files = "test*.py"


[tool.isort]
profile = "black"
[tool.ruff.lint]
extend-select = [
"B", # flake8-bugbear
"I", # isort
"ARG", # flake8-unused-arguments
"C4", # flake8-comprehensions
"EM", # flake8-errmsg
"ICN", # flake8-import-conventions
"G", # flake8-logging-format
"PGH", # pygrep-hooks
"PIE", # flake8-pie
"PL", # pylint
"PT", # flake8-pytest-style
"RET", # flake8-return
"RUF", # Ruff-specific
"SIM", # flake8-simplify
"T20", # flake8-print
"UP", # pyupgrade
"YTT", # flake8-2020
"EXE", # flake8-executable
"NPY", # NumPy specific rules
"PD", # pandas-vet
"FURB", # refurb
"PYI", # flake8-pyi
]
ignore = [
"PLR09", # Too many <...>
"PLR2004", # Magic value used in comparison
"ISC001", # Conflicts with formatter
"NPY002", # np.random.Generator
"G004", # Logging with f-string
"PD011", # .values vs .to_numpy can get confused
"PT013", # Import from pytest
]

[tool.ruff.lint.per-file-ignores]
"tests/**" = ["T20"]
"docs/conf.py" = ["T20"]
2 changes: 1 addition & 1 deletion src/mplhep/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
rescale_to_axessize,
sort_legend,
ylow,
yscale_legend,
yscale_anchored_text,
yscale_legend,
)
from .styles import set_style

Expand Down
8 changes: 2 additions & 6 deletions src/mplhep/_deprecate.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,9 @@ def __init__(self, name, reason="", warn_once: bool = True, warning=FutureWarnin

def __call__(self, func):
def decorated_func(*args, **kwargs):
if self._name in kwargs.keys() and not (
self._warn_once and self._already_warned
):
if self._name in kwargs and not (self._warn_once and self._already_warned):
warnings.warn(
'kwarg "{}" in function ``{}`` is deprecated and may be removed in future versions: {}'.format(
self._name, func.__name__, self._reason
),
f'kwarg "{self._name}" in function ``{func.__name__}`` is deprecated and may be removed in future versions: {self._reason}',
category=self._warning,
stacklevel=2,
)
Expand Down
2 changes: 0 additions & 2 deletions src/mplhep/_version.pyi
Original file line number Diff line number Diff line change
@@ -1,4 +1,2 @@
from __future__ import annotations

version: str
version_tuple: tuple[int, int, int] | tuple[int, int, int, str, str]
4 changes: 2 additions & 2 deletions src/mplhep/alice.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def text(text="", **kwargs):
for key, value in dict(mplhep.rcParams.text._get_kwargs()).items():
if (
value is not None
and key not in kwargs.keys()
and key not in kwargs
and key in inspect.getfullargspec(label_base.exp_text).kwonlyargs
):
kwargs.setdefault(key, value)
Expand All @@ -31,7 +31,7 @@ def label(label=None, **kwargs):
for key, value in dict(mplhep.rcParams.label._get_kwargs()).items():
if (
value is not None
and key not in kwargs.keys()
and key not in kwargs
and key in inspect.getfullargspec(label_base.exp_label).kwonlyargs
):
kwargs.setdefault(key, value)
Expand Down
4 changes: 2 additions & 2 deletions src/mplhep/atlas.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def text(text="", **kwargs):
for key, value in dict(mplhep.rcParams.text._get_kwargs()).items():
if (
value is not None
and key not in kwargs.keys()
and key not in kwargs
and key in inspect.getfullargspec(label_base.exp_text).kwonlyargs
):
kwargs.setdefault(key, value)
Expand All @@ -35,7 +35,7 @@ def label(label=None, **kwargs):
for key, value in dict(mplhep.rcParams.label._get_kwargs()).items():
if (
value is not None
and key not in kwargs.keys()
and key not in kwargs
and key in inspect.getfullargspec(label_base.exp_label).kwonlyargs
):
kwargs.setdefault(key, value)
Expand Down
4 changes: 2 additions & 2 deletions src/mplhep/cms.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def text(text="", **kwargs):
for key, value in dict(mplhep.rcParams.text._get_kwargs()).items():
if (
value is not None
and key not in kwargs.keys()
and key not in kwargs
and key in inspect.getfullargspec(label_base.exp_text).kwonlyargs
):
kwargs.setdefault(key, value)
Expand All @@ -35,7 +35,7 @@ def label(label=None, **kwargs):
for key, value in dict(mplhep.rcParams.label._get_kwargs()).items():
if (
value is not None
and key not in kwargs.keys()
and key not in kwargs
and key in inspect.getfullargspec(label_base.exp_label).kwonlyargs
):
kwargs.setdefault(key, value)
Expand Down
56 changes: 19 additions & 37 deletions src/mplhep/label.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,25 +11,17 @@

class ExpText(mtext.Text):
def __repr__(self):
return "exptext: Custom Text({}, {}, {})".format(
self._x, self._y, repr(self._text)
)
return f"exptext: Custom Text({self._x}, {self._y}, {self._text!r})"


class ExpSuffix(mtext.Text):
def __repr__(self):
return "expsuffix: Custom Text({}, {}, {})".format(
self._x,
self._y,
repr(self._text),
)
return f"expsuffix: Custom Text({self._x}, {self._y}, {self._text!r})"


class SuppText(mtext.Text):
def __repr__(self):
return "supptext: Custom Text({}, {}, {})".format(
self._x, self._y, repr(self._text)
)
return f"supptext: Custom Text({self._x}, {self._y}, {self._text!r})"


def exp_text(
Expand Down Expand Up @@ -105,13 +97,14 @@ def exp_text(
}

if loc not in [0, 1, 2, 3, 4]:
raise ValueError(
msg = (
"loc must be in {0, 1, 2}:\n"
"0 : Above axes, left aligned\n"
"1 : Top left corner\n"
"2 : Top left corner, multiline\n"
"3 : Split EXP above axes, rest of label in top left corner\n"
)
raise ValueError(msg)

def pixel_to_axis(extent, ax=None):
# Transform pixel bbox extends to axis fractions
Expand All @@ -134,10 +127,7 @@ def dist(tup):
abs(y1 - y) / dimy,
)

if loc in [0, 3]:
_exp_loc = 0
else:
_exp_loc = 1
_exp_loc = 0 if loc in [0, 3] else 1
_formater = ax.get_yaxis().get_major_formatter()
if isinstance(_formater, mpl.ticker.ScalarFormatter) and _exp_loc == 0:
_sci_box = pixel_to_axis(
Expand Down Expand Up @@ -209,14 +199,7 @@ def dist(tup):
units="inches",
fig=ax.figure,
)
elif loc == 2:
_t = mtransforms.offset_copy(
expsuffix._transform,
y=-expsuffix.get_window_extent().height / _dpi,
units="inches",
fig=ax.figure,
)
elif loc == 3:
elif loc in (2, 3):
_t = mtransforms.offset_copy(
expsuffix._transform,
y=-expsuffix.get_window_extent().height / _dpi,
Expand Down Expand Up @@ -368,18 +351,17 @@ def exp_label(
# Right label
if rlabel is not None:
_lumi = rlabel
elif lumi is not None:
_lumi = r"{lumi}{year} ({com} TeV)".format(
lumi=lumi_format.format(lumi) + r" $\mathrm{fb^{-1}}$",
year=", " + str(year) if year is not None else "",
com=str(com) if com is not None else "13",
)
else:
if lumi is not None:
_lumi = r"{lumi}{year} ({com} TeV)".format(
lumi=lumi_format.format(lumi) + r" $\mathrm{fb^{-1}}$",
year=", " + str(year) if year is not None else "",
com=str(com) if com is not None else "13",
)
else:
_lumi = "{year} ({com} TeV)".format(
year=str(year) if year is not None else "",
com=str(com) if com is not None else "13",
)
_lumi = "{year} ({com} TeV)".format(
year=str(year) if year is not None else "",
com=str(com) if com is not None else "13",
)

if loc < 4:
lumitext(text=_lumi, ax=ax, fontname=fontname, fontsize=fontsize)
Expand Down Expand Up @@ -524,7 +506,7 @@ def savelabels(
if ax is None:
ax = plt.gca()

label_base = [ch for ch in ax.get_children() if isinstance(ch, ExpSuffix)][0]
label_base = next(ch for ch in ax.get_children() if isinstance(ch, ExpSuffix))
_sim = "Simulation" if "Simulation" in label_base.get_text() else ""

for label_text, suffix in labels:
Expand All @@ -534,7 +516,7 @@ def savelabels(
save_name = suffix
else:
if len(suffix) > 0:
suffix = "_" + suffix
suffix = "_" + suffix # noqa: PLW2901
if "." in fname:
save_name = f"{fname.split('.')[0]}{suffix}.{fname.split('.')[1]}"
else:
Expand Down
4 changes: 2 additions & 2 deletions src/mplhep/lhcb.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def text(text="", **kwargs):
for key, value in dict(mplhep.rcParams.text._get_kwargs()).items():
if (
value is not None
and key not in kwargs.keys()
and key not in kwargs
and key in inspect.getfullargspec(label_base.exp_text).kwonlyargs
):
kwargs.setdefault(key, value)
Expand All @@ -53,7 +53,7 @@ def label(label=None, **kwargs):
for key, value in dict(mplhep.rcParams.label._get_kwargs()).items():
if (
value is not None
and key not in kwargs.keys()
and key not in kwargs
and key in inspect.getfullargspec(label_base.exp_label).kwonlyargs
):
kwargs.setdefault(key, value)
Expand Down
Loading

0 comments on commit 906d9a2

Please sign in to comment.