Skip to content

Commit 070b81b

Browse files
authored
Merge pull request #1089 from PowerGridModel/feature/ruff-checks
Linting and Formatting: S, FBT, PT, TRY checks
2 parents 909a138 + dab90a5 commit 070b81b

File tree

23 files changed

+97
-84
lines changed

23 files changed

+97
-84
lines changed

code_generation/code_gen.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
TEMPLATE_DIR = Path(__file__).parent / "templates"
1313
OUTPUT_PATH = Path(__file__).parents[1]
1414

15-
JINJA_ENV = Environment(loader=FileSystemLoader(TEMPLATE_DIR))
15+
JINJA_ENV = Environment(loader=FileSystemLoader(TEMPLATE_DIR), autoescape=True)
1616

1717

1818
def _data_type_nan(data_type: str):

code_generation/templates/power_grid_model_c/power_grid_model/include/power_grid_model/auxiliary/attribute_classes.hpp.jinja

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
#include "../common/common.hpp"
1313
#include "../common/enum.hpp"
1414
#include "../common/three_phase_tensor.hpp"
15-
15+
{% autoescape false %}
1616
namespace power_grid_model {
1717

1818
{% for attribute_class in classes -%}
@@ -42,5 +42,5 @@ using Asym{{ attribute_class.name }} = {{ attribute_class.name }}<asymmetric_t>;
4242
{% endfor %}
4343

4444
} // namespace power_grid_model
45-
45+
{% endautoescape %}
4646
// clang-format on

code_generation/templates/power_grid_model_c/power_grid_model/include/power_grid_model/auxiliary/meta_gen/attribute_classes.hpp.jinja

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717
#include "../{{ name }}.hpp" // NOLINT
1818

19-
19+
{% autoescape false %}
2020
namespace power_grid_model::meta_data {
2121

2222
// template specialization to get list of attributes in the value field
@@ -43,5 +43,5 @@ struct get_attributes_list<{{ attribute_class.name }}> {
4343

4444

4545
} // namespace power_grid_model::meta_data
46-
46+
{% endautoescape %}
4747
// clang-format on

code_generation/templates/power_grid_model_c/power_grid_model/include/power_grid_model/auxiliary/static_asserts/attribute_classes.hpp.jinja

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
#include "../{{ name }}.hpp" // NOLINT
1111

1212
#include <cstddef>
13-
13+
{% autoescape false %}
1414
namespace power_grid_model::test {
1515

1616
{% for attribute_class in classes -%}
@@ -32,5 +32,5 @@ static_assert(offsetof({{ specification }}, {{ attribute.names }}) == offsetof({
3232
{% endfor %}
3333

3434
} // namespace power_grid_model::test
35-
35+
{% endautoescape %}
3636
// clang-format on

code_generation/templates/power_grid_model_c/power_grid_model_c/include/power_grid_model_c/dataset_class_maps.h.jinja

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
#define POWER_GRID_MODEL_C_DATASET_DEFINITIONS_H
1818

1919
#include "basics.h"
20-
20+
{% autoescape false %}
2121
#ifdef __cplusplus
2222
extern "C" {
2323
#endif
@@ -44,4 +44,4 @@ PGM_API extern PGM_MetaAttribute const* const PGM_def_{{ dataset }}_{{ component
4444

4545
#endif
4646
// clang-format on
47-
47+
{% endautoescape %}

code_generation/templates/power_grid_model_c/power_grid_model_c/src/dataset_class_maps.cpp.jinja

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
#include "forward_declarations.hpp"
1111
#include "power_grid_model_c/dataset_definitions.h"
1212
#include "power_grid_model_c/meta_data.h"
13-
13+
{% autoescape false %}
1414
{% for dataset, components in all_map.items() -%}
1515
// dataset {{ dataset }}
1616
PGM_MetaDataset const* const PGM_def_{{ dataset }} = PGM_meta_get_dataset_by_name(nullptr, "{{ dataset }}");
@@ -26,6 +26,6 @@ PGM_MetaAttribute const* const PGM_def_{{ dataset }}_{{ component }}_{{ attribut
2626
{% endfor -%}
2727

2828
//
29-
29+
{% endautoescape %}
3030
// clang-format on
3131

docs/examples/Generic Branch Example.ipynb

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -632,11 +632,10 @@
632632
")\n",
633633
"\n",
634634
"\n",
635-
"pd.set_option(\"display.max_columns\", None)\n",
636-
"pd.set_option(\"display.max_rows\", None)\n",
637-
"pd.set_option(\"display.expand_frame_repr\", False)\n",
638-
"pd.set_option(\"display.max_columns\", None)\n",
639-
"pd.set_option(\"display.max_colwidth\", None)\n",
635+
"pd.options.display.max_columns = None\n",
636+
"pd.options.display.max_rows = None\n",
637+
"pd.options.display.expand_frame_repr = False\n",
638+
"pd.options.display.max_colwidth = None\n",
640639
"\n",
641640
"\n",
642641
"def e3(x):\n",

pyproject.toml

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,8 @@ show-fixes = true
110110
# Assume Python 3.11
111111
target-version = "py311"
112112

113-
extend-exclude = ["setup.py"]
113+
[tool.ruff.lint.pydocstyle]
114+
convention = "google"
114115

115116
[tool.ruff.lint]
116117
select = [
@@ -145,10 +146,17 @@ select = [
145146
"SLF",
146147
"UP",
147148
"RSE",
148-
"RUF"
149+
"RUF",
150+
"S",
151+
"FBT003",
152+
"TRY002",
153+
"PT"
154+
]
155+
156+
ignore = [
157+
"UP038", # deprecated, https://docs.astral.sh/ruff/rules/non-pep604-isinstance/#deprecation
158+
"PT019" # flags false positives
149159
]
150-
# the rule is deprecated, https://docs.astral.sh/ruff/rules/non-pep604-isinstance/#deprecation
151-
ignore = ["UP038"]
152160

153161
[tool.ruff.lint.isort]
154162
# Imports that are imported using keyword "as" and are from the same source - are combined.
@@ -158,11 +166,10 @@ combine-as-imports = true
158166
# Ignore `F811` (redefinition violations) in all examples notebooks since we use redefinition.
159167
"docs/examples/*.ipynb" = ["F811", "E402"]
160168
# Pylint was only run in src directory before moving to Ruff
161-
"tests/*" = ["PLR0915", "PLR0912", "PLR0913"]
169+
"tests/*" = ["PLR0915", "PLR0912", "PLR0913", "S"]
162170
# Ignore private member access: _model_ptr, _all_component_count...
163171
"src/power_grid_model/_core/*.py" = ["SLF001"]
164172
"tests/unit/test_error_handling.py" = ["SLF001"]
165-
"setup.py" = ["PL"]
166173

167174
[tool.mypy]
168175
follow_imports = "silent"

src/power_grid_model/utils.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -282,7 +282,7 @@ def _compatibility_deprecated_export_json_data(
282282
file_pointer.write(old_format_serialized_data)
283283

284284

285-
def import_input_data(json_file: Path) -> SingleDataset:
285+
def import_input_data(json_file: Path) -> SingleDataset: # pragma: no cover
286286
"""
287287
[deprecated] Import input json data.
288288
@@ -299,8 +299,10 @@ def import_input_data(json_file: Path) -> SingleDataset:
299299
warnings.warn(_DEPRECATED_JSON_DESERIALIZATION_MSG, DeprecationWarning)
300300

301301
data = _compatibility_deprecated_import_json_data(json_file=json_file, data_type=DatasetType.input)
302-
assert isinstance(data, dict)
303-
assert all(isinstance(component, np.ndarray) and component.ndim == 1 for component in data.values())
302+
if not isinstance(data, dict):
303+
raise TypeError(f"Expected data to be dict, got {type(data)}")
304+
if not all(isinstance(component, np.ndarray) and component.ndim == 1 for component in data.values()):
305+
raise TypeError("All components must be 1D numpy arrays")
304306
return cast_type(SingleDataset, data)
305307

306308

@@ -398,12 +400,14 @@ def self_test():
398400
with Path(output_file_path).open("r", encoding="utf-8") as output_file:
399401
output_data = json.load(output_file)
400402

401-
assert output_data is not None
402-
assert math.isclose(
403+
if output_data is None: # pragma: no cover
404+
raise ValueError("Output data should not be None")
405+
if not math.isclose(
403406
output_data["data"][ComponentType.node][0]["u"],
404407
input_data["data"][ComponentType.node][0]["u_rated"],
405408
abs_tol=1e-9,
406-
)
409+
): # pragma: no cover
410+
raise ValueError("The difference between the input and output data is too big.")
407411

408412
print("Self test finished.")
409413
except Exception as e:

src/power_grid_model/validation/_rules.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -794,8 +794,8 @@ def no_strict_subset_missing(data: SingleDataset, fields: list[str], component_t
794794
errors = []
795795
if component_type in data:
796796
component_data = data[component_type]
797-
instances_with_nan_data = np.full_like([], False, shape=(len(component_data),), dtype=bool)
798-
instances_with_non_nan_data = np.full_like([], False, shape=(len(component_data),), dtype=bool)
797+
instances_with_nan_data = np.full_like([], fill_value=False, shape=(len(component_data),), dtype=bool)
798+
instances_with_non_nan_data = np.full_like([], fill_value=False, shape=(len(component_data),), dtype=bool)
799799
for field in fields:
800800
nan_value = _nan_type(component_type, field)
801801
asym_axes = tuple(range(component_data.ndim, component_data[field].ndim))
@@ -850,7 +850,7 @@ def not_all_missing(data: SingleDataset, fields: list[str], component_type: Comp
850850
errors = []
851851
if component_type in data:
852852
component_data = data[component_type]
853-
instances_with_all_nan_data = np.full_like([], True, shape=(len(component_data),), dtype=bool)
853+
instances_with_all_nan_data = np.full_like([], fill_value=True, shape=(len(component_data),), dtype=bool)
854854

855855
for field in fields:
856856
nan_value = _nan_type(component_type, field)

0 commit comments

Comments
 (0)