Unverified Commit c60bc739 authored by James Lamb's avatar James Lamb Committed by GitHub
Browse files

[ci] [python-package] add more linting checks (#6049)

parent aafdf741
...@@ -126,7 +126,7 @@ class _MissingType(Enum): ...@@ -126,7 +126,7 @@ class _MissingType(Enum):
class _DummyLogger: class _DummyLogger:
def info(self, msg: str) -> None: def info(self, msg: str) -> None:
print(msg) print(msg) # noqa: T201
def warning(self, msg: str) -> None: def warning(self, msg: str) -> None:
warnings.warn(msg, stacklevel=3) warnings.warn(msg, stacklevel=3)
...@@ -467,11 +467,10 @@ class _ConfigAliases: ...@@ -467,11 +467,10 @@ class _ConfigAliases:
ctypes.c_int64(actual_len), ctypes.c_int64(actual_len),
ctypes.byref(tmp_out_len), ctypes.byref(tmp_out_len),
ptr_string_buffer)) ptr_string_buffer))
aliases = json.loads( return json.loads(
string_buffer.value.decode('utf-8'), string_buffer.value.decode('utf-8'),
object_hook=lambda obj: {k: [k] + v for k, v in obj.items()} object_hook=lambda obj: {k: [k] + v for k, v in obj.items()}
) )
return aliases
@classmethod @classmethod
def get(cls, *args) -> Set[str]: def get(cls, *args) -> Set[str]:
...@@ -3209,8 +3208,7 @@ class Booster: ...@@ -3209,8 +3208,7 @@ class Booster:
def __deepcopy__(self, _) -> "Booster": def __deepcopy__(self, _) -> "Booster":
model_str = self.model_to_string(num_iteration=-1) model_str = self.model_to_string(num_iteration=-1)
booster = Booster(model_str=model_str) return Booster(model_str=model_str)
return booster
def __getstate__(self) -> Dict[str, Any]: def __getstate__(self) -> Dict[str, Any]:
this = self.__dict__.copy() this = self.__dict__.copy()
......
...@@ -693,11 +693,7 @@ def create_tree_digraph( ...@@ -693,11 +693,7 @@ def create_tree_digraph(
model = booster.dump_model() model = booster.dump_model()
tree_infos = model['tree_info'] tree_infos = model['tree_info']
if 'feature_names' in model: feature_names = model.get('feature_names', None)
feature_names = model['feature_names']
else:
feature_names = None
monotone_constraints = model.get('monotone_constraints', None) monotone_constraints = model.get('monotone_constraints', None)
if tree_index < len(tree_infos): if tree_index < len(tree_infos):
...@@ -722,7 +718,7 @@ def create_tree_digraph( ...@@ -722,7 +718,7 @@ def create_tree_digraph(
)[0] )[0]
example_case = example_case[0] example_case = example_case[0]
graph = _to_graphviz( return _to_graphviz(
tree_info=tree_info, tree_info=tree_info,
show_info=show_info, show_info=show_info,
feature_names=feature_names, feature_names=feature_names,
...@@ -734,8 +730,6 @@ def create_tree_digraph( ...@@ -734,8 +730,6 @@ def create_tree_digraph(
**kwargs **kwargs
) )
return graph
def plot_tree( def plot_tree(
booster: Union[Booster, LGBMModel], booster: Union[Booster, LGBMModel],
......
...@@ -111,7 +111,13 @@ select = [ ...@@ -111,7 +111,13 @@ select = [
# pycodestyle # pycodestyle
"E", "E",
# pyflakes # pyflakes
"F" "F",
# flake8-return: unnecessary assignment before return
"RET504",
# flake8-simplify: use dict.get() instead of an if-else block
"SIM401",
# flake8-print
"T",
] ]
# this should be set to the oldest version of python LightGBM supports # this should be set to the oldest version of python LightGBM supports
...@@ -120,13 +126,17 @@ target-version = "py37" ...@@ -120,13 +126,17 @@ target-version = "py37"
[tool.ruff.per-file-ignores] [tool.ruff.per-file-ignores]
"examples/*" = [ "examples/*" = [
# pydocstyle # pydocstyle
"D" "D",
# flake8-print
"T"
] ]
"tests/*" = [ "tests/*" = [
# (flake8-bugbear) Found useless expression # (flake8-bugbear) Found useless expression
"B018", "B018",
# pydocstyle # pydocstyle
"D" "D",
# flake8-print
"T"
] ]
[tool.ruff.pydocstyle] [tool.ruff.pydocstyle]
......
...@@ -25,7 +25,7 @@ def _find_random_open_port() -> int: ...@@ -25,7 +25,7 @@ def _find_random_open_port() -> int:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(('', 0)) s.bind(('', 0))
port = s.getsockname()[1] port = s.getsockname()[1]
return port return port # noqa: RET504
def _generate_n_ports(n: int) -> Generator[int, None, None]: def _generate_n_ports(n: int) -> Generator[int, None, None]:
...@@ -47,8 +47,7 @@ def create_data(task: str, n_samples: int = 1_000) -> np.ndarray: ...@@ -47,8 +47,7 @@ def create_data(task: str, n_samples: int = 1_000) -> np.ndarray:
X, y = make_blobs(n_samples, centers=centers, random_state=42) X, y = make_blobs(n_samples, centers=centers, random_state=42)
elif task == 'regression': elif task == 'regression':
X, y = make_regression(n_samples, n_features=4, n_informative=2, random_state=42) X, y = make_regression(n_samples, n_features=4, n_informative=2, random_state=42)
dataset = np.hstack([y.reshape(-1, 1), X]) return np.hstack([y.reshape(-1, 1), X])
return dataset
class DistributedMockup: class DistributedMockup:
...@@ -149,8 +148,7 @@ class DistributedMockup: ...@@ -149,8 +148,7 @@ class DistributedMockup:
result = subprocess.run(cmd) result = subprocess.run(cmd)
if result.returncode != 0: if result.returncode != 0:
raise RuntimeError('Error in prediction') raise RuntimeError('Error in prediction')
y_pred = np.loadtxt(str(TESTS_DIR / 'predictions.txt')) return np.loadtxt(str(TESTS_DIR / 'predictions.txt'))
return y_pred
def write_train_config(self, i: int) -> None: def write_train_config(self, i: int) -> None:
"""Create a file train{i}.conf with the required configuration to train. """Create a file train{i}.conf with the required configuration to train.
......
...@@ -1720,8 +1720,7 @@ def generate_trainset_for_monotone_constraints_tests(x3_to_category=True): ...@@ -1720,8 +1720,7 @@ def generate_trainset_for_monotone_constraints_tests(x3_to_category=True):
categorical_features = [] categorical_features = []
if x3_to_category: if x3_to_category:
categorical_features = [2] categorical_features = [2]
trainset = lgb.Dataset(x, label=y, categorical_feature=categorical_features, free_raw_data=False) return lgb.Dataset(x, label=y, categorical_feature=categorical_features, free_raw_data=False)
return trainset
@pytest.mark.skipif(getenv('TASK', '') == 'cuda', reason='Monotone constraints are not yet supported by CUDA version') @pytest.mark.skipif(getenv('TASK', '') == 'cuda', reason='Monotone constraints are not yet supported by CUDA version')
......
...@@ -192,4 +192,4 @@ def pickle_and_unpickle_object(obj, serializer): ...@@ -192,4 +192,4 @@ def pickle_and_unpickle_object(obj, serializer):
filepath=tmp_file.name, filepath=tmp_file.name,
serializer=serializer serializer=serializer
) )
return obj_from_disk return obj_from_disk # noqa: RET504
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment