Skip to content

Commit 23edb17

Browse files
apply ruff rules (#45)
Closes #26. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent ce0bc39 commit 23edb17

File tree

13 files changed

+101
-65
lines changed

13 files changed

+101
-65
lines changed

.pre-commit-config.yaml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ repos:
1616
- repo: https://github.com/astral-sh/ruff-pre-commit
1717
rev: v0.2.0
1818
hooks:
19+
- id: ruff
20+
args: [ --fix ]
1921
- id: ruff-format
2022
# numpydoc
2123
- repo: https://github.com/Carreau/velin

dargs/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
from .dargs import Argument, Variant, ArgumentEncoder
1+
from .dargs import Argument, ArgumentEncoder, Variant
22

33
__all__ = ["Argument", "Variant", "ArgumentEncoder"]

dargs/dargs.py

Lines changed: 24 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
r"""
2-
Some (ocaml) pseudo-code here to show the intended type structure::
1+
r"""Some (ocaml) pseudo-code here to show the intended type structure.
32
43
type args = {key: str; value: data; optional: bool; doc: str} list
54
and data =
@@ -40,7 +39,11 @@
4039
HookArgKType = Callable[["Argument", dict, List[str]], None]
4140
HookArgVType = Callable[["Argument", Any, List[str]], None]
4241
HookVrntType = Callable[["Variant", dict, List[str]], None]
43-
_DUMMYHOOK = lambda a, x, p: None # for doing nothing in traversing
42+
43+
44+
def _DUMMYHOOK(a, x, p):
45+
# for doing nothing in traversing
46+
pass
4447

4548

4649
class _Flags(Enum):
@@ -68,19 +71,19 @@ def __str__(self) -> str:
6871

6972

7073
class ArgumentKeyError(ArgumentError):
71-
"""Error class for missing or invalid argument keys"""
74+
"""Error class for missing or invalid argument keys."""
7275

7376
pass
7477

7578

7679
class ArgumentTypeError(ArgumentError):
77-
"""Error class for invalid argument data types"""
80+
"""Error class for invalid argument data types."""
7881

7982
pass
8083

8184

8285
class ArgumentValueError(ArgumentError):
83-
"""Error class for missing or invalid argument values"""
86+
"""Error class for missing or invalid argument values."""
8487

8588
pass
8689

@@ -169,8 +172,12 @@ def __init__(
169172
def __eq__(self, other: "Argument") -> bool:
170173
# do not compare doc and default
171174
# since they do not enter to the type checking
172-
fkey = lambda f: f.name
173-
vkey = lambda v: v.flag_name
175+
def fkey(f):
176+
return f.name
177+
178+
def vkey(v):
179+
return v.flag_name
180+
174181
return (
175182
self.name == other.name
176183
and set(self.dtype) == set(other.dtype)
@@ -204,7 +211,7 @@ def __getitem__(self, key: str) -> "Argument":
204211
return self[skey][rkey]
205212

206213
@property
207-
def I(self):
214+
def I(self): # noqa:E743
208215
# return a dummy argument that only has self as a sub field
209216
# can be used in indexing
210217
return Argument("_", dict, [self])
@@ -227,7 +234,7 @@ def _reorg_dtype(self):
227234
if (
228235
self.optional
229236
and self.default is not _Flags.NONE
230-
and all([not isinstance_annotation(self.default, tt) for tt in self.dtype])
237+
and all(not isinstance_annotation(self.default, tt) for tt in self.dtype)
231238
):
232239
self.dtype.add(type(self.default))
233240
# and make it compatible with `isinstance`
@@ -473,7 +480,7 @@ def normalize(
473480
do_alias: bool = True,
474481
trim_pattern: Optional[str] = None,
475482
):
476-
"""Modify `argdict` so that it meets the Argument structure
483+
"""Modify `argdict` so that it meets the Argument structure.
477484
478485
Normalization can add default values to optional args,
479486
substitute alias by its standard names, and discard unnecessary
@@ -526,7 +533,7 @@ def normalize_value(
526533
do_alias: bool = True,
527534
trim_pattern: Optional[str] = None,
528535
):
529-
"""Modify the value so that it meets the Argument structure
536+
"""Modify the value so that it meets the Argument structure.
530537
531538
Same as `normalize({self.name: value})[self.name]`.
532539
@@ -611,7 +618,7 @@ def gen_doc_head(self, path: Optional[List[str]] = None, **kwargs) -> str:
611618
if self.optional:
612619
typesig += ", optional"
613620
if self.default == "":
614-
typesig += f", default: (empty string)"
621+
typesig += ", default: (empty string)"
615622
elif self.default is not _Flags.NONE:
616623
typesig += f", default: ``{self.default}``"
617624
if self.alias:
@@ -733,7 +740,7 @@ def set_default(self, default_tag: Union[bool, str]):
733740
self.default_tag = default_tag
734741

735742
def extend_choices(self, choices: Optional[Iterable["Argument"]]):
736-
"""Add a list of choice Arguments to the current Variant"""
743+
"""Add a list of choice Arguments to the current Variant."""
737744
# choices is a list of arguments
738745
# whose name is treated as the switch tag
739746
# we convert it into a dict for better reference
@@ -760,7 +767,7 @@ def add_choice(
760767
*args,
761768
**kwargs,
762769
) -> "Argument":
763-
"""Add a choice Argument to the current Variant"""
770+
"""Add a choice Argument to the current Variant."""
764771
if isinstance(tag, Argument):
765772
newarg = tag
766773
else:
@@ -835,7 +842,7 @@ def gen_doc(
835842
if kwargs.get("make_link"):
836843
if not kwargs.get("make_anchor"):
837844
raise ValueError("`make_link` only works with `make_anchor` set")
838-
fnstr, target = make_ref_pair(path + [self.flag_name], fnstr, "flag")
845+
fnstr, target = make_ref_pair([*path, self.flag_name], fnstr, "flag")
839846
body_list.append(target + "\n")
840847
for choice in self.choice_dict.values():
841848
body_list.append("")
@@ -986,7 +993,7 @@ def isinstance_annotation(value, dtype) -> bool:
986993

987994

988995
class ArgumentEncoder(json.JSONEncoder):
989-
"""Extended JSON Encoder to encode Argument object:
996+
"""Extended JSON Encoder to encode Argument object.
990997
991998
Examples
992999
--------

dargs/sphinx.py

Lines changed: 23 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
where `_test_argument` returns an :class:`Argument <dargs.Argument>`. A :class:`list` of :class:`Argument <dargs.Argument>` is also accepted.
2121
"""
2222
import sys
23-
from typing import List
23+
from typing import ClassVar, List
2424

2525
from docutils.parsers.rst import Directive
2626
from docutils.parsers.rst.directives import unchanged
@@ -34,13 +34,13 @@
3434

3535

3636
class DargsDirective(Directive):
37-
"""dargs directive"""
37+
"""dargs directive."""
3838

39-
has_content = True
40-
option_spec = dict(
41-
module=unchanged,
42-
func=unchanged,
43-
)
39+
has_content: ClassVar[bool] = True
40+
option_spec: ClassVar[dict] = {
41+
"module": unchanged,
42+
"func": unchanged,
43+
}
4444

4545
def run(self):
4646
if "module" in self.options and "func" in self.options:
@@ -58,11 +58,8 @@ def run(self):
5858

5959
if not hasattr(mod, attr_name):
6060
raise self.error(
61-
(
62-
'Module "%s" has no attribute "%s"\n'
63-
"Incorrect argparse :module: or :func: values?"
64-
)
65-
% (module_name, attr_name)
61+
f'Module "{module_name}" has no attribute "{attr_name}"\n'
62+
"Incorrect argparse :module: or :func: values?"
6663
)
6764
func = getattr(mod, attr_name)
6865
arguments = func()
@@ -78,7 +75,7 @@ def run(self):
7875
make_anchor=True, make_link=True, use_sphinx_domain=True
7976
)
8077
rsts.extend(rst.split("\n"))
81-
self.state_machine.insert_input(rsts, "%s:%s" % (module_name, attr_name))
78+
self.state_machine.insert_input(rsts, f"{module_name}:{attr_name}")
8279
return []
8380

8481

@@ -88,17 +85,17 @@ class DargsObject(ObjectDescription):
8885
This directive creates a signature node for an argument.
8986
"""
9087

91-
option_spec = dict(
92-
path=unchanged,
93-
)
88+
option_spec: ClassVar[dict] = {
89+
"path": unchanged,
90+
}
9491

9592
def handle_signature(self, sig, signode):
9693
signode += addnodes.desc_name(sig, sig)
9794
return sig
9895

9996
def add_target_and_index(self, name, sig, signode):
10097
path = self.options["path"]
101-
targetid = "%s:%s" % (self.objtype, path)
98+
targetid = f"{self.objtype}:{path}"
10299
if targetid not in self.state.document.ids:
103100
signode["names"].append(targetid)
104101
signode["ids"].append(targetid)
@@ -108,16 +105,15 @@ def add_target_and_index(self, name, sig, signode):
108105
inv = self.env.domaindata["dargs"]["arguments"]
109106
if targetid in inv:
110107
self.state.document.reporter.warning(
111-
'Duplicated argument "%s" described in "%s".'
112-
% (targetid, self.env.doc2path(inv[targetid][0])),
108+
f'Duplicated argument "{targetid}" described in "{self.env.doc2path(inv[targetid][0])}".',
113109
line=self.lineno,
114110
)
115111
inv[targetid] = (self.env.docname, self.objtype)
116112

117113
self.indexnode["entries"].append(
118114
(
119115
"pair",
120-
"%s ; %s (%s) " % (name, path, self.objtype.title()),
116+
f"{name}; {path} ({self.objtype.title()})",
121117
targetid,
122118
"main",
123119
None,
@@ -133,25 +129,25 @@ class DargsDomain(Domain):
133129
- dargs::argument role
134130
"""
135131

136-
name = "dargs"
137-
label = "dargs"
138-
object_types = {
132+
name: ClassVar[str] = "dargs"
133+
label: ClassVar[str] = "dargs"
134+
object_types: ClassVar[dict] = {
139135
"argument": ObjType("argument", "argument"),
140136
}
141-
directives = {
137+
directives: ClassVar[dict] = {
142138
"argument": DargsObject,
143139
}
144-
roles = {
140+
roles: ClassVar[dict] = {
145141
"argument": XRefRole(),
146142
}
147143

148-
initial_data = {
144+
initial_data: ClassVar[dict] = {
149145
"arguments": {}, # fullname -> docname, objtype
150146
}
151147

152148
def resolve_xref(self, env, fromdocname, builder, typ, target, node, contnode):
153149
"""Resolve cross-references."""
154-
targetid = "%s:%s" % (typ, target)
150+
targetid = f"{typ}:{target}"
155151
obj = self.data["arguments"].get(targetid)
156152
if obj is None:
157153
return None

docs/conf.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
#
32
# Configuration file for the Sphinx documentation builder.
43
#

pyproject.toml

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,34 @@ include = ["dargs*"]
3232

3333
[tool.setuptools_scm]
3434
write_to = "dargs/_version.py"
35+
36+
[tool.ruff.lint]
37+
select = [
38+
"E", # errors
39+
"F", # pyflakes
40+
"D", # pydocstyle
41+
"UP", # pyupgrade
42+
"C4", # flake8-comprehensions
43+
"RUF", # ruff
44+
"I", # isort
45+
]
46+
47+
ignore = [
48+
"E501", # line too long
49+
"F841", # local variable is assigned to but never used
50+
"E741", # ambiguous variable name
51+
"E402", # module level import not at top of file
52+
"D100", # TODO: missing docstring in public module
53+
"D101", # TODO: missing docstring in public class
54+
"D102", # TODO: missing docstring in public method
55+
"D103", # TODO: missing docstring in public function
56+
"D104", # TODO: missing docstring in public package
57+
"D105", # TODO: missing docstring in magic method
58+
"D205", # 1 blank line required between summary line and description
59+
"D401", # TODO: first line should be in imperative mood
60+
"D404", # TODO: first word of the docstring should not be This
61+
]
62+
ignore-init-module-imports = true
63+
64+
[tool.ruff.lint.pydocstyle]
65+
convention = "numpy"

tests/__init__.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
import os
2+
import sys
3+
4+
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

tests/context.py

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +0,0 @@
1-
import sys, os
2-
3-
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
4-
import dargs

tests/dpmdargs.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
from .context import dargs
2-
from dargs import dargs, Argument, Variant
1+
from dargs import Argument, Variant, dargs
32

43
ACTIVATION_FN_DICT = {
54
"relu": None,
@@ -140,7 +139,8 @@ def descrpt_se_a_tpe_args():
140139
doc_type_nlayer = "number of hidden layers of type embedding net"
141140
doc_numb_aparam = "dimension of atomic parameter. if set to a value > 0, the atomic parameters are embedded."
142141

143-
return descrpt_se_a_args() + [
142+
return [
143+
*descrpt_se_a_args(),
144144
Argument("type_nchanl", int, optional=True, default=4, doc=doc_type_nchanl),
145145
Argument("type_nlayer", int, optional=True, default=2, doc=doc_type_nlayer),
146146
Argument("numb_aparam", int, optional=True, default=0, doc=doc_numb_aparam),
@@ -202,7 +202,7 @@ def descrpt_se_ar_args():
202202

203203

204204
def descrpt_hybrid_args():
205-
doc_list = f"A list of descriptor definitions"
205+
doc_list = "A list of descriptor definitions"
206206

207207
return [
208208
Argument(
@@ -243,7 +243,7 @@ def descrpt_variant_type_args():
243243
link_se_a_3be = make_link("se_a_3be", "model/descriptor[se_a_3be]")
244244
link_se_a_tpe = make_link("se_a_tpe", "model/descriptor[se_a_tpe]")
245245
link_hybrid = make_link("hybrid", "model/descriptor[hybrid]")
246-
doc_descrpt_type = f"The type of the descritpor. See explanation below. \n\n\
246+
doc_descrpt_type = "The type of the descritpor. See explanation below. \n\n\
247247
- `loc_frame`: Defines a local frame at each atom, and the compute the descriptor as local coordinates under this frame.\n\n\
248248
- `se_a`: Used by the smooth edition of Deep Potential. The full relative coordinates are used to construct the descriptor.\n\n\
249249
- `se_r`: Used by the smooth edition of Deep Potential. Only the distance between atoms is used to construct the descriptor.\n\n\
@@ -391,7 +391,7 @@ def modifier_dipole_charge():
391391
doc_model_name = "The name of the frozen dipole model file."
392392
doc_model_charge_map = f"The charge of the WFCC. The list length should be the same as the {make_link('sel_type', 'model/fitting_net[dipole]/sel_type')}. "
393393
doc_sys_charge_map = f"The charge of real atoms. The list length should be the same as the {make_link('type_map', 'model/type_map')}"
394-
doc_ewald_h = f"The grid spacing of the FFT grid. Unit is A"
394+
doc_ewald_h = "The grid spacing of the FFT grid. Unit is A"
395395
doc_ewald_beta = f"The splitting parameter of Ewald sum. Unit is A^{-1}"
396396

397397
return [

tests/test_checker.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
from typing import List
2-
from .context import dargs
31
import unittest
2+
from typing import List
3+
44
from dargs import Argument, Variant
55
from dargs.dargs import ArgumentKeyError, ArgumentTypeError, ArgumentValueError
66

0 commit comments

Comments
 (0)