Skip to content

Commit 591e36a

Browse files
authored
Merge pull request #5 from alexfikl/ruff
Enable linting with ruff
2 parents 52e855c + 19f7ba0 commit 591e36a

23 files changed

+203
-99
lines changed

.editorconfig

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# EditorConfig - http://EditorConfig.org
2+
3+
# top-most EditorConfig file
4+
root = true
5+
6+
# Unix-style newlines with a newline ending every file
7+
[*]
8+
end_of_line = lf
9+
insert_final_newline = true
10+
trim_trailing_whitespace = false
11+
12+
# Matches multiple files with brace expansion notation
13+
# Set default charset
14+
[*.{c,py}]
15+
charset = utf-8
16+
17+
# tab indentation
18+
[*.py]
19+
indent_style = tab
20+
indent_size = 4

.github/workflows/ci.yml

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,20 @@ concurrency:
1414
cancel-in-progress: true
1515

1616
jobs:
17+
typos:
18+
name: Spelling (typos)
19+
runs-on: ubuntu-latest
20+
steps:
21+
- uses: actions/checkout@v4
22+
- uses: crate-ci/typos@master
23+
24+
ruff:
25+
name: Linting (ruff)
26+
runs-on: ubuntu-latest
27+
steps:
28+
- uses: actions/checkout@v4
29+
- uses: chartboost/ruff-action@v1
30+
1731
test:
1832
name: Unittest (${{ matrix.os }}-${{ matrix.compiler }}-py${{ matrix.python-version }})
1933
runs-on: ${{ matrix.os }}

docs/conf.py

Lines changed: 22 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,56 +1,58 @@
1-
import sys
21
import os
2+
import sys
33
from unittest.mock import MagicMock as Mock
4+
45
from setuptools_scm import get_version
56

7+
68
# Mocking to make RTD autobuild the documentation. (Doesn’t suffice.)
79
# autodoc_mock_imports = [ 'numpy', 'symengine', '.' ]
810

911
MOCK_MODULES = [
10-
'numpy', 'numpy.testing', 'numpy.random',
11-
'symengine', 'symengine.printing', 'symengine.lib.symengine_wrapper',
12-
'.'
12+
"numpy", "numpy.testing", "numpy.random",
13+
"symengine", "symengine.printing", "symengine.lib.symengine_wrapper",
14+
"."
1315
]
1416
sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES)
1517

1618
sys.path.insert(0,os.path.abspath("../jitcxde_common"))
1719

18-
needs_sphinx = '1.3'
20+
needs_sphinx = "1.3"
1921

2022
extensions = [
21-
'sphinx.ext.autodoc',
22-
'sphinx.ext.autosummary',
23-
'sphinx.ext.mathjax',
24-
'numpydoc',
23+
"sphinx.ext.autodoc",
24+
"sphinx.ext.autosummary",
25+
"sphinx.ext.mathjax",
26+
"numpydoc",
2527
]
2628

27-
source_suffix = '.rst'
29+
source_suffix = ".rst"
2830

29-
master_doc = 'index'
31+
master_doc = "index"
3032

31-
project = u'JiTC*DE Common'
32-
copyright = u'2017, Gerrit Ansmann'
33+
project = "JiTC*DE Common"
34+
copyright = "2017, Gerrit Ansmann"
3335

34-
release = version = get_version(root='..', relative_to=__file__)
36+
release = version = get_version(root="..", relative_to=__file__)
3537

3638
default_role = "any"
3739

3840
add_function_parentheses = True
3941

4042
add_module_names = False
4143

42-
html_theme = 'nature'
43-
pygments_style = 'colorful'
44-
htmlhelp_basename = 'JiTC*DEdoc'
44+
html_theme = "nature"
45+
pygments_style = "colorful"
46+
htmlhelp_basename = "JiTC*DEdoc"
4547

4648
numpydoc_show_class_members = False
47-
autodoc_member_order = 'bysource'
49+
autodoc_member_order = "bysource"
4850

4951
def on_missing_reference(app, env, node, contnode):
50-
if node['reftype'] == 'any':
52+
if node["reftype"] == "any":
5153
return contnode
5254
else:
5355
return None
5456

5557
def setup(app):
56-
app.connect('missing-reference', on_missing_reference)
58+
app.connect("missing-reference", on_missing_reference)

jitcxde_common/__init__.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,10 @@
1-
from sys import version_info
2-
if version_info < (3,3):
3-
raise NotImplementedError("Python versions below 3.3 are not supported anymore (or never were). Please upgrade to a newer Python version.")
1+
from ._jitcxde import DEFAULT_COMPILE_ARGS, DEFAULT_LINK_ARGS, MSVC_COMPILE_ARGS, MSVC_LINK_ARGS, jitcxde # noqa: F401
2+
from .check import checker # noqa: F401
3+
from .symbolic import conditional # noqa: F401
44

5-
from ._jitcxde import jitcxde, DEFAULT_COMPILE_ARGS, DEFAULT_LINK_ARGS, MSVC_COMPILE_ARGS, MSVC_LINK_ARGS
6-
from .symbolic import conditional
7-
from .check import checker
85

96
try:
10-
from .version import version as __version__
7+
from .version import version as __version__ # noqa: F401
118
except ImportError:
129
from warnings import warn
13-
warn('Failed to find (autogenerated) version.py. Do not worry about this unless you really need to know the version.')
10+
warn("Failed to find (autogenerated) version.py. Do not worry about this unless you really need to know the version.", stacklevel=1)

jitcxde_common/_jitcxde.py

Lines changed: 23 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,26 @@
11
#!/usr/bin/python3
2-
# -*- coding: utf-8 -*-
32

4-
from tempfile import TemporaryDirectory
5-
from os import path
6-
from inspect import stack, isgeneratorfunction, isfunction
7-
from setuptools import setup, Extension
8-
from setuptools.command.build_ext import build_ext
3+
import platform
94
import shutil
5+
from inspect import isgeneratorfunction, stack
6+
from os import path
7+
from pickle import PickleError
108
from sys import modules
11-
from warnings import warn
9+
from tempfile import TemporaryDirectory
1210
from traceback import format_exc
13-
from pickle import PickleError
14-
import platform
11+
from warnings import warn
1512

1613
import numpy
1714
from jinja2 import Environment, FileSystemLoader
15+
from setuptools import Extension, setup
16+
from setuptools.command.build_ext import build_ext
1817
from symengine import sympify
1918

2019
from jitcxde_common.check import CheckEnvironment, checker
21-
from jitcxde_common.modules import get_module_path, modulename_from_path, find_and_load_module, module_from_path, add_suffix
20+
from jitcxde_common.code import codelines, write_in_chunks
21+
from jitcxde_common.modules import add_suffix, find_and_load_module, get_module_path, module_from_path, modulename_from_path
2222
from jitcxde_common.strings import count_up
23-
from jitcxde_common.code import write_in_chunks, codelines
23+
2424

2525
#: A list with the default extra compile arguments. Note that without `-Ofast`, `-ffast-math`, or `-funsafe-math-optimizations` (if supported by your compiler), you may experience a considerable speed loss since SymEngine uses the `pow` function for small integer powers (cf. `SymPy Issue 8997`_).
2626
DEFAULT_COMPILE_ARGS = [
@@ -67,12 +67,12 @@ def __init__(self,n=None,verbose=True,module_location=None):
6767

6868
# self.compile_attempt is:
6969
# • None if no compile attempt was made
70-
# • False if a compile attempt was made but not succesful
70+
# • False if a compile attempt was made but not successful
7171
# • True if a successful compile attempt was made
7272

7373
def _check_dynvar_dict(self,dictionary,name,length):
7474
if not set(dictionary.keys()) == {self.dynvar(i) for i in range(length)}:
75-
raise ValueError("If %s is a dictionary, its keys must be y(0), y(1), …, y(n) where n is the number of entries." % name)
75+
raise ValueError(f"If '{name}' is a dictionary, its keys must be y(0), y(1), …, y(n) where n is the number of entries.")
7676

7777
def _generator_func_from_dynvar_dict(self,dictionary,name,length):
7878
"""
@@ -125,8 +125,10 @@ def _handle_input(self,f_sym,n_basic=False):
125125
if n is not None and length != n:
126126
raise ValueError("len(f_sym) and n do not match.")
127127

128-
if n_basic: self.n_basic = length
129-
else: self.n = length
128+
if n_basic:
129+
self.n_basic = length
130+
else:
131+
self.n = length
130132

131133
if isinstance(f_sym,dict):
132134
new_f_sym = self._generator_func_from_dynvar_dict(f_sym,"f_sym",length)
@@ -150,7 +152,7 @@ def _check_dimension_match(self):
150152

151153
def _tmpfile(self,filename=None):
152154
"""
153-
returns the path to a file in the tempory directory associated to this instance or the directory itself (if `filename` is None). Creates the directory if necessary.
155+
returns the path to a file in the temporary directory associated to this instance or the directory itself (if `filename` is None). Creates the directory if necessary.
154156
"""
155157
if self._tmpdir is None:
156158
self._tmpdir = TemporaryDirectory(
@@ -245,9 +247,9 @@ def _attempt_compilation(self,reset=True):
245247
try:
246248
self.compile_C()
247249
except Exception:
248-
warn(format_exc())
250+
warn(format_exc(), stacklevel=3)
249251
line = "\n"+60*"="+"\n"
250-
warn(line + "READ ME FIRST" + line + "Generating compiled integrator failed; resorting to lambdified functions. If you can live with using the Python backend, you can call generate_lambdas to explicitly do this and bypass the compile attempt and error messages. Otherwise, you want to take care of fixing the above errors." + 2*line)
252+
warn(f"{line}READ ME FIRST{line}Generating compiled integrator failed; resorting to lambdified functions. If you can live with using the Python backend, you can call generate_lambdas to explicitly do this and bypass the compile attempt and error messages. Otherwise, you want to take care of fixing the above errors.{2*line}", stacklevel=3)
251253
else:
252254
if reset:
253255
self.reset_integrator()
@@ -312,7 +314,7 @@ def build_extensions(self):
312314
ext_modules = [extension],
313315
script_args = script_args,
314316
verbose = verbose,
315-
cmdclass = {'build_ext':build_ext_with_compiler_detection}
317+
cmdclass = {"build_ext":build_ext_with_compiler_detection}
316318
)
317319

318320
self.jitced = find_and_load_module(self._modulename,self._tmpfile())
@@ -356,7 +358,7 @@ def save_compiled(self, destination="", overwrite=False):
356358
raise RuntimeError("Compilation failed. Cannot save module file.")
357359

358360
if path.isfile(destination) and not overwrite:
359-
raise OSError("Target File already exists and \"overwrite\" is set to False")
361+
raise OSError('Target File already exists and "overwrite" is set to False')
360362
else:
361363
shutil.copy(sourcefile, destination)
362364

@@ -367,7 +369,7 @@ def __del__(self):
367369
try:
368370
self._tmpdir.cleanup()
369371
except (OSError, AttributeError, TypeError, PermissionError) as error:
370-
warn(f"Could not delete temporary directory {self._tmpdir.name} because of the following error:\n{error}")
372+
warn(f"Could not delete temporary directory {self._tmpdir.name} because of the following error:\n{error}", stacklevel=2)
371373
finally:
372374
self._tmpdir = None
373375

jitcxde_common/check.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,17 @@
55

66
from functools import update_wrapper
77

8+
89
# This class exist just to mark functions
9-
class checker(object):
10+
class checker:
1011
def __init__(self,function):
1112
self.function = function
1213
update_wrapper(self,function)
1314

1415
def __call__(self,*args):
1516
self.function(*args)
1617

17-
class CheckEnvironment(object):
18+
class CheckEnvironment:
1819
def _check_assert(self,condition,message):
1920
if not condition:
2021
self.failed_check = True
@@ -42,7 +43,7 @@ def check(self, fail_fast=True):
4243

4344
# execute all methods decorated with checker:
4445
visited = set()
45-
for cls in [self.__class__] + self.__class__.mro():
46+
for cls in [self.__class__, *self.__class__.mro()]:
4647
for name,member in cls.__dict__.items():
4748
if name not in visited and isinstance(member,checker):
4849
member(self)

jitcxde_common/code.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
from itertools import chain
2+
23
from symengine.printing import ccode
4+
35
from jitcxde_common.strings import count_up
46

7+
58
def codelines(expressions):
69
"""
710
Tries to convert expressions to working code
@@ -14,13 +17,12 @@ def codelines(expressions):
1417
raise
1518
else:
1619
raise NotImplementedError(
17-
"Cannot convert the following expression to C Code:\n"
18-
+ str(expression)
19-
)
20+
f"Cannot convert the following expression to C Code:\n{expression}"
21+
) from error
2022
yield codeline + ";\n"
2123

2224
def render_declarator(name, _type, size=0):
23-
return _type + " " + name + ("[%i]"%size if size else "")
25+
return _type + " " + name + (f"[{size}]" if size else "")
2426

2527
def write_in_chunks(lines,mainfile,deffile,name,chunk_size,arguments,omp=True):
2628
"""

jitcxde_common/helpers.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from symengine import sympify
22

3+
34
def depends_on_any(helper, other_helpers):
45
for other_helper in other_helpers:
56
if helper[1].has(other_helper[0]):
@@ -60,5 +61,5 @@ def find_dependent_helpers(helpers,dependency):
6061
return dependent_helpers
6162

6263
def copy_helpers(helpers):
63-
return [helper for helper in helpers]
64+
return list(helpers)
6465

jitcxde_common/modules.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
from sys import version_info
22

3-
if version_info < (3,3):
3+
4+
if version_info < (3,3): # noqa: UP036
45
raise NotImplementedError("Python versions below 3.3 are not supported anymore (or never were). Please upgrade to a newer Python version.")
56
elif (3,3) <= version_info < (3,5):
6-
from jitcxde_common.modules_33 import get_module_path, modulename_from_path, find_and_load_module, module_from_path, add_suffix
7+
from jitcxde_common.modules_33 import add_suffix, find_and_load_module, get_module_path, module_from_path, modulename_from_path
78
elif (3,5) <= version_info:
8-
from jitcxde_common.modules_35 import get_module_path, modulename_from_path, find_and_load_module, module_from_path, add_suffix
9+
from jitcxde_common.modules_35 import add_suffix, find_and_load_module, get_module_path, module_from_path, modulename_from_path # noqa: F401
910

jitcxde_common/modules_33.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
from os import path
2-
from importlib.machinery import ExtensionFileLoader, EXTENSION_SUFFIXES, FileFinder
1+
from importlib.machinery import EXTENSION_SUFFIXES, ExtensionFileLoader, FileFinder
32
from importlib.util import spec_from_file_location
3+
from os import path
4+
45

56
loader_details = (ExtensionFileLoader, EXTENSION_SUFFIXES)
67
suffices = sorted(EXTENSION_SUFFIXES, key=len)

0 commit comments

Comments
 (0)