Skip to content

Commit

Permalink
[ci] [python-package] enforce 'pylint' checks (fixes #4308) (#6334)
Browse files Browse the repository at this point in the history
  • Loading branch information
jameslamb committed Feb 24, 2024
1 parent 776c5c3 commit 6f19edd
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 11 deletions.
11 changes: 7 additions & 4 deletions python-package/lightgbm/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1215,7 +1215,7 @@ def predict(
)
if pred_leaf:
preds = preds.astype(np.int32)
is_sparse = isinstance(preds, scipy.sparse.spmatrix) or isinstance(preds, list)
is_sparse = isinstance(preds, (list, scipy.sparse.spmatrix))
if not is_sparse and preds.size != nrow:
if preds.size % nrow == 0:
preds = preds.reshape(nrow, -1)
Expand Down Expand Up @@ -2681,7 +2681,10 @@ def set_field(
'In multiclass classification init_score can also be a list of lists, numpy 2-D array or pandas DataFrame.'
)
else:
dtype = np.int32 if (field_name == 'group' or field_name == 'position') else np.float32
if field_name in {'group', 'position'}:
dtype = np.int32
else:
dtype = np.float32
data = _list_to_1d_numpy(data, dtype=dtype, name=field_name)

ptr_data: Union[_ctypes_float_ptr, _ctypes_int_ptr]
Expand Down Expand Up @@ -3106,7 +3109,7 @@ def get_data(self) -> Optional[_LGBM_TrainDataType]:
if self._need_slice and self.used_indices is not None and self.reference is not None:
self.data = self.reference.data
if self.data is not None:
if isinstance(self.data, np.ndarray) or isinstance(self.data, scipy.sparse.spmatrix):
if isinstance(self.data, (np.ndarray, scipy.sparse.spmatrix)):
self.data = self.data[self.used_indices, :]
elif isinstance(self.data, pd_DataFrame):
self.data = self.data.iloc[self.used_indices].copy()
Expand Down Expand Up @@ -3284,7 +3287,7 @@ def add_features_from(self, other: "Dataset") -> "Dataset":
self.data = None
elif isinstance(self.data, scipy.sparse.spmatrix):
sparse_format = self.data.getformat()
if isinstance(other.data, np.ndarray) or isinstance(other.data, scipy.sparse.spmatrix):
if isinstance(other.data, (np.ndarray, scipy.sparse.spmatrix)):
self.data = scipy.sparse.hstack((self.data, other.data), format=sparse_format)
elif isinstance(other.data, pd_DataFrame):
self.data = scipy.sparse.hstack((self.data, other.data.values), format=sparse_format)
Expand Down
8 changes: 4 additions & 4 deletions python-package/lightgbm/plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -393,8 +393,8 @@ def plot_metric(
for name in dataset_names_iter:
metrics_for_one = eval_results[name]
results = metrics_for_one[metric]
max_result = max(max(results), max_result)
min_result = min(min(results), min_result)
max_result = max(*results, max_result)
min_result = min(*results, min_result)
ax.plot(x_, results, label=name)

ax.legend(loc='best')
Expand Down Expand Up @@ -804,7 +804,7 @@ def plot_tree(
The plot with single tree.
"""
if MATPLOTLIB_INSTALLED:
import matplotlib.image as image
import matplotlib.image
import matplotlib.pyplot as plt
else:
raise ImportError('You must install matplotlib and restart your session to plot tree.')
Expand All @@ -821,7 +821,7 @@ def plot_tree(
s = BytesIO()
s.write(graph.pipe(format='png'))
s.seek(0)
img = image.imread(s)
img = matplotlib.image.imread(s)

ax.imshow(img)
ax.axis('off')
Expand Down
22 changes: 21 additions & 1 deletion python-package/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,21 @@ ignore = [
# (pydocstyle) Missing docstring in magic method
"D105",
# (pycodestyle) Line too long
"E501"
"E501",
# (pylint) Too many branches
"PLR0912",
# (pylint) Too many arguments in function definition
"PLR0913",
# (pylint) Too many statements
"PLR0915",
# (pylint) Consider merging multiple comparisons
"PLR1714",
# (pylint) Magic value used in comparison
"PLR2004",
# (pylint) for loop veriable overwritten by assignment target
"PLW2901",
# (pylint) use 'elif' instead of 'else' then 'if', to reduce indentation
"PLR5501"
]
select = [
# flake8-bugbear
Expand All @@ -138,6 +152,8 @@ select = [
"E",
# pyflakes
"F",
# pylint
"PL",
# flake8-return: unnecessary assignment before return
"RET504",
# flake8-simplify: use dict.get() instead of an if-else block
Expand All @@ -159,6 +175,10 @@ select = [
# flake8-print
"T"
]
"python-package/lightgbm/basic.py" = [
# (pylint) Using the global statement is discouraged
"PLW0603"
]
"tests/*" = [
# (flake8-bugbear) Found useless expression
"B018",
Expand Down
4 changes: 2 additions & 2 deletions tests/distributed/_test_distributed.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def worker_train(self, i: int) -> subprocess.CompletedProcess:
"""Start the training process on the `i`-th worker."""
config_path = TESTS_DIR / f"train{i}.conf"
cmd = [self.executable, f"config={config_path}"]
return subprocess.run(cmd)
return subprocess.run(cmd, check=True)

def _set_ports(self) -> None:
"""Randomly assign a port for training to each worker and save all ports to mlist.txt."""
Expand Down Expand Up @@ -145,7 +145,7 @@ def predict(self, predict_config: Dict[str, Any]) -> np.ndarray:
with open(config_path, "wt") as file:
_write_dict(self.predict_config, file)
cmd = [self.executable, f"config={config_path}"]
result = subprocess.run(cmd)
result = subprocess.run(cmd, check=True)
if result.returncode != 0:
raise RuntimeError("Error in prediction")
return np.loadtxt(str(TESTS_DIR / "predictions.txt"))
Expand Down

0 comments on commit 6f19edd

Please sign in to comment.