Skip to content

Commit 3c69e3b

Browse files
Refactor global pylint checks (#788)
* Upgrade pylint version * Fix remaining pylint errors in `randprocs` (excluding `markov`) * Fix pylint errors in `_config.py` * Add a global linting pass ignoring the problematic subpackages * Force parameters, exceptions, yields and return types to be documented in the docstring * Fix pylint messages in `utils` * Disable new messages in per-package linting passes * Remove the sync check between global and local linting passes * Bugfix
1 parent 6c69825 commit 3c69e3b

21 files changed

+209
-134
lines changed

.github/workflows/linting.yml

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -36,13 +36,3 @@ jobs:
3636
run: pip install tox
3737
- name: Run pylint through tox
3838
run: tox -e pylint
39-
40-
pylint-tox-config-check:
41-
runs-on: ubuntu-latest
42-
steps:
43-
- uses: actions/checkout@v2
44-
- uses: actions/setup-python@v2
45-
with:
46-
python-version: 3.8
47-
- name: Check if the list of disabled messages in the local and global linting passes in ./tox.ini are correctly synchronized
48-
run: python .github/workflows/pylint_check.py

.github/workflows/pylint_check.py

Lines changed: 0 additions & 48 deletions
This file was deleted.

linting-requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
# Dependencies for code linting
22

3-
pylint == 2.9.*
3+
pylint~=2.16.2
44
# mypy

pyproject.toml

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -163,18 +163,17 @@ load-plugins = [
163163
"pylint.extensions.docstyle",
164164
"pylint.extensions.overlapping_exceptions",
165165
"pylint.extensions.mccabe",
166+
"pylint.extensions.no_self_use",
166167
]
167168

168169
[tool.pylint.messages_control]
169170
disable = [
170-
# Exceptions suggested by Black:
171-
# https://github.com/psf/black/blob/7f75fe3669ebf0627b1b0476a6d02047e909b959/docs/compatible_configs.md#black-compatible-configurations
172-
"bad-continuation",
173-
"bad-whitespace",
174171
# We allow TODO comments in the following format: `# TODO (#[ISSUE NUMBER]): This needs to be done.`
175172
"fixme",
176173
# We want to use "mathematical notation" to name some of our variables, e.g. `A` for matrices
177174
"invalid-name",
175+
# Assigning lambda expressions to a variable is sometimes useful, e.g. for defining `LambdaLinearOperator`s
176+
"unnecessary-lambda-assignment",
178177
# Temporary ignore, see https://github.com/probabilistic-numerics/probnum/discussions/470#discussioncomment-1998097 for an explanation
179178
"missing-return-doc",
180179
"missing-yield-doc",
@@ -183,13 +182,23 @@ disable = [
183182
[tool.pylint.format]
184183
max-line-length = "88"
185184

185+
[tool.pylint.parameter_documentation]
186+
accept-no-param-doc = false
187+
accept-no-raise-doc = false
188+
accept-no-return-doc = false
189+
accept-no-yields-doc = false
190+
186191
[tool.pylint.design]
187192
max-args = 10
188193
max-complexity = 14
189194
max-locals = 20
190195

191196
[tool.pylint.similarities]
192-
ignore-imports = "yes"
197+
ignore-comments = true
198+
ignore-docstrings = true
199+
ignore-imports = true
200+
ignore-signatures = true
201+
min-similarity-lines = 4
193202

194203
################################################################################
195204
# Formatting Configuration #

src/probnum/_config.py

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
"""ProbNum library configuration"""
2+
13
import contextlib
24
import dataclasses
35
from typing import Any
@@ -35,6 +37,9 @@ class Configuration:
3537

3638
@dataclasses.dataclass
3739
class Option:
40+
"""Representation of a single configuration option as a key-value pair with a
41+
default value and a description string for documentation purposes."""
42+
3843
name: str
3944
default_value: Any
4045
description: str
@@ -49,7 +54,7 @@ def __init__(self) -> None:
4954
# This is the equivalent of `self._options_registry = dict()`.
5055
# After rewriting the `__setattr__` method, we have to fall back on the
5156
# `__setattr__` method of the super class.
52-
object.__setattr__(self, "_options_registry", dict())
57+
object.__setattr__(self, "_options_registry", {})
5358

5459
def __getattr__(self, key: str) -> Any:
5560
if key not in self._options_registry:
@@ -68,7 +73,7 @@ def __repr__(self) -> str:
6873
@contextlib.contextmanager
6974
def __call__(self, **kwargs) -> None:
7075
"""Context manager used to set values of registered config options."""
71-
old_options = dict()
76+
old_options = {}
7277

7378
for key, value in kwargs.items():
7479
if key not in self._options_registry:
@@ -96,6 +101,11 @@ def register(self, key: str, default_value: Any, description: str) -> None:
96101
The default value of the configuration option.
97102
description:
98103
A short description of the configuration option and what it controls.
104+
105+
Raises
106+
------
107+
KeyError
108+
If the configuration option already exists.
99109
"""
100110
if key in self._options_registry:
101111
raise KeyError(
@@ -156,5 +166,9 @@ def register(self, key: str, default_value: Any, description: str) -> None:
156166
]
157167

158168
# ... and register the default configuration options.
159-
for key, default_value, descr in _DEFAULT_CONFIG_OPTIONS:
160-
_GLOBAL_CONFIG_SINGLETON.register(key, default_value, descr)
169+
def _register_defaults():
170+
for key, default_value, descr in _DEFAULT_CONFIG_OPTIONS:
171+
_GLOBAL_CONFIG_SINGLETON.register(key, default_value, descr)
172+
173+
174+
_register_defaults()

src/probnum/conftest.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88

99
@pytest.fixture(autouse=True)
10-
def autoimport_packages(doctest_namespace):
10+
def autoimport_packages(doctest_namespace): # pylint: disable=missing-any-param-doc
1111
"""This fixture 'imports' standard packages automatically in order to avoid
1212
boilerplate code in doctests"""
1313

src/probnum/functions/_function.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -129,9 +129,8 @@ def __sub__(self, other):
129129
@functools.singledispatchmethod
130130
def __mul__(self, other):
131131
if np.ndim(other) == 0:
132-
from ._algebra_fallbacks import ( # pylint: disable=import-outside-toplevel
133-
ScaledFunction,
134-
)
132+
# pylint: disable=import-outside-toplevel,cyclic-import
133+
from ._algebra_fallbacks import ScaledFunction
135134

136135
return ScaledFunction(function=self, scalar=other)
137136

@@ -140,9 +139,8 @@ def __mul__(self, other):
140139
@functools.singledispatchmethod
141140
def __rmul__(self, other):
142141
if np.ndim(other) == 0:
143-
from ._algebra_fallbacks import ( # pylint: disable=import-outside-toplevel
144-
ScaledFunction,
145-
)
142+
# pylint: disable=import-outside-toplevel,cyclic-import
143+
from ._algebra_fallbacks import ScaledFunction
146144

147145
return ScaledFunction(function=self, scalar=other)
148146

src/probnum/linops/_arithmetic_fallbacks.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -137,10 +137,10 @@ def __neg__(self):
137137
return SumLinearOperator(*(-summand for summand in self._summands))
138138

139139
def __repr__(self):
140-
res = "SumLinearOperator [\n"
141-
for s in self._summands:
142-
res += f"\t{s}, \n"
143-
return res + "]"
140+
res = "SumLinearOperator [\n\t"
141+
res += ",\n\t".join(repr(summand) for summand in self._summands)
142+
res += "\n]"
143+
return res
144144

145145
@staticmethod
146146
def _expand_sum_ops(*summands: LinearOperator) -> Tuple[LinearOperator, ...]:
@@ -230,10 +230,10 @@ def _expand_prod_ops(*factors: LinearOperator) -> Tuple[LinearOperator, ...]:
230230
return tuple(expanded_factors)
231231

232232
def __repr__(self):
233-
res = "ProductLinearOperator [\n"
234-
for s in self._factors:
235-
res += f"\t{s}, \n"
236-
return res + "]"
233+
res = "ProductLinearOperator [\n\t"
234+
res += ",\n\t".join(repr(factor) for factor in self._factors)
235+
res += "\n]"
236+
return res
237237

238238
def _solve(self, B: np.ndarray) -> np.ndarray:
239239
return functools.reduce(lambda b, op: op.solve(b), self._factors, B)

src/probnum/linops/_linear_operator.py

Lines changed: 48 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
import scipy.linalg
1111
import scipy.sparse
1212

13-
from probnum import config
13+
from probnum import config # pylint: disable=cyclic-import
1414
from probnum.typing import ArrayLike, DTypeLike, ScalarLike, ShapeLike
1515
import probnum.utils
1616

@@ -384,6 +384,13 @@ def todense(self, cache: bool = True) -> np.ndarray:
384384
This method can be computationally very costly depending on the shape of the
385385
linear operator. Use with caution.
386386
387+
Parameters
388+
----------
389+
cache
390+
If this is set to :data:`True`, then the dense matrix representation will
391+
be cached and subsequent calls will return the cached value (even if
392+
:code:`dense` is set to :data:`False` in these subsequent calls).
393+
387394
Returns
388395
-------
389396
matrix : np.ndarray
@@ -413,7 +420,14 @@ def is_symmetric(self) -> Optional[bool]:
413420
"""Whether the ``LinearOperator`` :math:`L` is symmetric, i.e. :math:`L = L^T`.
414421
415422
If this is ``None``, it is unknown whether the operator is symmetric or not.
416-
Only square operators can be symmetric."""
423+
Only square operators can be symmetric.
424+
425+
Raises
426+
------
427+
ValueError
428+
When setting :attr:`is_symmetric` to :data:`True` on a non-square
429+
:class:`LinearOperator`.
430+
"""
417431
return self._is_symmetric
418432

419433
@is_symmetric.setter
@@ -458,6 +472,12 @@ def is_positive_definite(self) -> Optional[bool]:
458472
459473
If this is ``None``, it is unknown whether the matrix is positive-definite or
460474
not. Only symmetric operators can be positive-definite.
475+
476+
Raises
477+
------
478+
ValueError
479+
When setting :attr:`is_positive_definite` to :data:`True` while
480+
:attr:`is_symmetric` is :data:`False`.
461481
"""
462482
return self._is_positive_definite
463483

@@ -520,7 +540,13 @@ def _eigvals(self) -> np.ndarray:
520540
return np.linalg.eigvals(self.todense(cache=False))
521541

522542
def eigvals(self) -> np.ndarray:
523-
"""Eigenvalue spectrum of the linear operator."""
543+
"""Eigenvalue spectrum of the linear operator.
544+
545+
Raises
546+
------
547+
numpy.linalg.LinAlgError
548+
If :meth:`eigvals` is called on a non-square operator.
549+
"""
524550
if self._eigvals_cache is None:
525551
if not self.is_square:
526552
raise np.linalg.LinAlgError(
@@ -871,9 +897,8 @@ def _lu_factor(self):
871897
####################################################################################
872898

873899
def __neg__(self) -> "LinearOperator":
874-
from ._arithmetic import ( # pylint: disable=import-outside-toplevel
875-
NegatedLinearOperator,
876-
)
900+
# pylint: disable=import-outside-toplevel,cyclic-import
901+
from ._arithmetic import NegatedLinearOperator
877902

878903
return NegatedLinearOperator(self)
879904

@@ -912,6 +937,18 @@ def transpose(self, *axes: Union[int, Tuple[int]]) -> "LinearOperator":
912937
"""Transpose this linear operator.
913938
914939
Can be abbreviated self.T instead of self.transpose().
940+
941+
Parameters
942+
----------
943+
*axes
944+
Permutation of the axes of the :class:`LinearOperator`.
945+
946+
Raises
947+
------
948+
ValueError
949+
If the given axis indices do not constitute a valid permutation of the axes.
950+
numpy.AxisError
951+
If the axis indices are out of bounds.
915952
"""
916953
if len(axes) > 0:
917954
if len(axes) == 1 and isinstance(axes[0], tuple):
@@ -1167,7 +1204,8 @@ def __matmul__(
11671204

11681205
return y
11691206

1170-
from ._arithmetic import matmul # pylint: disable=import-outside-toplevel
1207+
# pylint: disable=import-outside-toplevel,cyclic-import
1208+
from ._arithmetic import matmul
11711209

11721210
return matmul(self, other)
11731211

@@ -1193,7 +1231,8 @@ def __rmatmul__(
11931231

11941232
return y
11951233

1196-
from ._arithmetic import matmul # pylint: disable=import-outside-toplevel
1234+
# pylint: disable=import-outside-toplevel,cyclic-import
1235+
from ._arithmetic import matmul
11971236

11981237
return matmul(other, self)
11991238

@@ -1731,7 +1770,7 @@ def __init__(self, indices, shape, dtype=np.double):
17311770
)
17321771

17331772
@property
1734-
def indices(self):
1773+
def indices(self) -> Tuple[int]:
17351774
"""Indices which will be selected when applying the linear operator to a
17361775
vector."""
17371776
return self._indices

0 commit comments

Comments
 (0)