diff --git a/CODING_GUIDELINES.md b/CODING_GUIDELINES.md index 9376644064..cdcad0f4b8 100644 --- a/CODING_GUIDELINES.md +++ b/CODING_GUIDELINES.md @@ -21,8 +21,8 @@ We follow the [Google Python Style Guide][google-style-guide] with a few minor c We deviate from the [Google Python Style Guide][google-style-guide] only in the following points: -- We use [`flake8`][flake8] with some plugins instead of [`pylint`][pylint]. -- We use [`black`][black] and [`isort`][isort] for source code and imports formatting, which may work differently than indicated by the guidelines in section [_3. Python Style Rules_](https://google.github.io/styleguide/pyguide.html#3-python-style-rules). For example, maximum line length is set to 100 instead of 79 (although docstring lines should still be limited to 79). +- We use [`ruff-linter`][ruff-linter] instead of [`pylint`][pylint]. +- We use [`ruff-formatter`][ruff-formatter] for source code and imports formatting, which may work differently than indicated by the guidelines in section [_3. Python Style Rules_](https://google.github.io/styleguide/pyguide.html#3-python-style-rules). For example, maximum line length is set to 100 instead of 79 (although docstring lines should still be limited to 79). - According to subsection [_2.19 Power Features_](https://google.github.io/styleguide/pyguide.html#219-power-features), direct use of _power features_ (e.g. custom metaclasses, import hacks, reflection) should be avoided, but standard library classes that internally use these power features are accepted. Following the same spirit, we allow the use of power features in infrastructure code with similar functionality and scope as the Python standard library. - According to subsection [_3.19.12 Imports For Typing_](https://google.github.io/styleguide/pyguide.html#31912-imports-for-typing), symbols from `typing` and `collections.abc` modules used in type annotations _"can be imported directly to keep common annotations concise and match standard typing practices"_. Following the same spirit, we allow symbols to be imported directly from third-party or internal modules when they only contain a collection of frequently used typying definitions. @@ -107,7 +107,7 @@ In general, you should structure new Python modules in the following way: 1. _shebang_ line: `#! /usr/bin/env python3` (only for **executable scripts**!). 2. License header (see `LICENSE_HEADER.txt`). 3. Module docstring. -4. Imports, alphabetically ordered within each block (fixed automatically by `isort`): +4. Imports, alphabetically ordered within each block (fixed automatically by `ruff-formatter`): 1. Block of imports from the standard library. 2. Block of imports from general third party libraries using standard shortcuts when customary (e.g. `numpy as np`). 3. Block of imports from specific modules of the project. @@ -126,10 +126,17 @@ Consider configuration files as another type of source code and apply the same c ### Ignoring QA errors -You may occasionally need to disable checks from _quality assurance_ (QA) tools (e.g. linters, type checkers, etc.) on specific lines as some tool might not be able to fully understand why a certain piece of code is needed. This is usually done with special comments, e.g. `# type: ignore`. However, you should **only** ignore QA errors when you fully understand their source and rewriting your code to pass QA checks would make it less readable. Additionally, you should add a brief comment for future reference, e.g.: +You may occasionally need to disable checks from _quality assurance_ (QA) tools (e.g. linters, type checkers, etc.) on specific lines as some tool might not be able to fully understand why a certain piece of code is needed. This is usually done with special comments, e.g. `# noqa: F401`, `# type: ignore`. However, you should **only** ignore QA errors when you fully understand their source and rewriting your code to pass QA checks would make it less readable. Additionally, you should add a short descriptive code if possible (check [ruff rules][ruff-rules] and [mypy error codes][mypy-error-codes] for reference): ```python -f = lambda: 'empty' # noqa: E731 # assign lambda expression for testing +f = lambda: 'empty' # noqa: E731 [lambda-assignment] +``` + +and, if needed, a brief comment for future reference: + +```python +... +return undeclared_symbol # noqa: F821 [undefined-name] on purpose to trigger black-magic ``` ## Testing @@ -213,13 +220,15 @@ https://testandcode.com/116 -[black]: https://black.readthedocs.io/en/stable/ [doctest]: https://docs.python.org/3/library/doctest.html -[flake8]: https://flake8.pycqa.org/ [google-style-guide]: https://google.github.io/styleguide/pyguide.html -[isort]: https://pycqa.github.io/isort/ +[mypy]: https://mypy.readthedocs.io/ +[mypy-error-codes]: https://mypy.readthedocs.io/en/stable/error_code_list.html [pre-commit]: https://pre-commit.com/ [pylint]: https://pylint.pycqa.org/ +[ruff-formatter]: https://docs.astral.sh/ruff/formatter/ +[ruff-linter]: https://docs.astral.sh/ruff/linter/ +[ruff-rules]: https://docs.astral.sh/ruff/rules/ [sphinx]: https://www.sphinx-doc.org [sphinx-autodoc]: https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html [sphinx-napoleon]: https://sphinxcontrib-napoleon.readthedocs.io/en/latest/index.html# diff --git a/src/gt4py/cartesian/__gtscript__.py b/src/gt4py/cartesian/__gtscript__.py index 32ed7d1a6b..902f81b9b3 100644 --- a/src/gt4py/cartesian/__gtscript__.py +++ b/src/gt4py/cartesian/__gtscript__.py @@ -20,7 +20,7 @@ import sys -from gt4py.cartesian.gtscript import * +from gt4py.cartesian.gtscript import * # noqa: F403 [undefined-local-with-import-star] sys.modules["__gtscript__"] = sys.modules["gt4py.cartesian.__gtscript__"] diff --git a/src/gt4py/cartesian/__init__.py b/src/gt4py/cartesian/__init__.py index af4b66eac1..7270eedc28 100644 --- a/src/gt4py/cartesian/__init__.py +++ b/src/gt4py/cartesian/__init__.py @@ -30,3 +30,20 @@ type_hints, ) from .stencil_object import StencilObject + + +__all__ = [ + "typing", + "caching", + "cli", + "config", + "definitions", + "frontend", + "gt_cache_manager", + "gtscript", + "loader", + "stencil_builder", + "stencil_object", + "type_hints", + "StencilObject", +] diff --git a/src/gt4py/cartesian/backend/base.py b/src/gt4py/cartesian/backend/base.py index 259e94dcd8..61488f1135 100644 --- a/src/gt4py/cartesian/backend/base.py +++ b/src/gt4py/cartesian/backend/base.py @@ -271,7 +271,9 @@ def check_options(self, options: gt_definitions.BuildOptions) -> None: unknown_options = set(options.backend_opts.keys()) - set(self.options.keys()) if unknown_options: warnings.warn( - f"Unknown options '{unknown_options}' for backend '{self.name}'", RuntimeWarning + f"Unknown options '{unknown_options}' for backend '{self.name}'", + RuntimeWarning, + stacklevel=2, ) def make_module( diff --git a/src/gt4py/cartesian/backend/dace_backend.py b/src/gt4py/cartesian/backend/dace_backend.py index 215ed8af96..7ec542e98c 100644 --- a/src/gt4py/cartesian/backend/dace_backend.py +++ b/src/gt4py/cartesian/backend/dace_backend.py @@ -516,7 +516,7 @@ def _postprocess_dace_code(code_objects, is_gpu, builder): break for i, line in enumerate(lines): if "#include " in line: - cuda_code = [co.clean_code for co in code_objects if co.title == "CUDA"][0] + cuda_code = next(co.clean_code for co in code_objects if co.title == "CUDA") lines = lines[0:i] + cuda_code.split("\n") + lines[i + 1 :] break diff --git a/src/gt4py/cartesian/backend/pyext_builder.py b/src/gt4py/cartesian/backend/pyext_builder.py index 1ffa5a412d..9d04cf3413 100644 --- a/src/gt4py/cartesian/backend/pyext_builder.py +++ b/src/gt4py/cartesian/backend/pyext_builder.py @@ -194,7 +194,7 @@ def build_pybind_ext( libraries: Optional[List[str]] = None, extra_compile_args: Optional[Union[List[str], Dict[str, List[str]]]] = None, extra_link_args: Optional[List[str]] = None, - build_ext_class: Type = None, + build_ext_class: Optional[Type] = None, verbose: bool = False, clean: bool = False, ) -> Tuple[str, str]: ... @@ -211,7 +211,7 @@ def build_pybind_ext( libraries: Optional[List[str]] = None, extra_compile_args: Optional[Union[List[str], Dict[str, List[str]]]] = None, extra_link_args: Optional[List[str]] = None, - build_ext_class: Type = None, + build_ext_class: Optional[Type] = None, verbose: bool = False, clean: bool = False, ) -> Tuple[str, str]: @@ -242,7 +242,6 @@ def build_pybind_ext( ext_modules=[py_extension], script_args=[ "build_ext", - # "--parallel={}".format(gt_config.build_settings["parallel_jobs"]), "--build-temp={}".format(build_path), "--build-lib={}".format(build_path), "--force", @@ -336,7 +335,7 @@ def build_pybind_cuda_ext( def _clean_build_flags(config_vars: Dict[str, str]) -> None: for key, value in config_vars.items(): - if type(value) == str: + if isinstance(value, str): value = " " + value + " " for s in value.split(" "): if ( diff --git a/src/gt4py/cartesian/frontend/defir_to_gtir.py b/src/gt4py/cartesian/frontend/defir_to_gtir.py index eb53e49ac5..2471063789 100644 --- a/src/gt4py/cartesian/frontend/defir_to_gtir.py +++ b/src/gt4py/cartesian/frontend/defir_to_gtir.py @@ -137,7 +137,7 @@ def visit_StencilDefinition( def _nested_list_dim(self, a: List) -> List[int]: if not isinstance(a, list): return [] - return [len(a)] + self._nested_list_dim(a[0]) + return [len(a), *self._nested_list_dim(a[0])] def visit_Assign( self, node: Assign, *, fields_decls: Dict[str, FieldDecl], **kwargs @@ -181,7 +181,7 @@ def apply(cls, root, *, expected_dim: Tuple[int, ...], fields_decls: Dict[str, F # if the expression is just a scalar broadcast to the expected dimensions if not isinstance(result, list): result = functools.reduce( - lambda val, len: [val for _ in range(len)], reversed(expected_dim), result + lambda val, len_: [val for _ in range(len_)], reversed(expected_dim), result ) return result diff --git a/src/gt4py/cartesian/frontend/gtscript_frontend.py b/src/gt4py/cartesian/frontend/gtscript_frontend.py index d08fd8d7ea..df87f4b121 100644 --- a/src/gt4py/cartesian/frontend/gtscript_frontend.py +++ b/src/gt4py/cartesian/frontend/gtscript_frontend.py @@ -211,15 +211,15 @@ def visit_BinOp(self, node: ast.BinOp) -> Union[gtscript.AxisIndex, nodes.AxisBo right = self.visit(node.right) if isinstance(node.op, ast.Add): - bin_op = lambda x, y: x + y # noqa: E731 - u_op = lambda x: x # noqa: E731 + bin_op = lambda x, y: x + y # noqa: E731 [lambda-assignment] + u_op = lambda x: x # noqa: E731 [lambda-assignment] elif isinstance(node.op, ast.Sub): - bin_op = lambda x, y: x - y # noqa: E731 - u_op = lambda x: -x # noqa: E731 + bin_op = lambda x, y: x - y # noqa: E731 [lambda-assignment] + u_op = lambda x: -x # noqa: E731 [lambda-assignment] elif isinstance(node.op, ast.Mult): if left.level != right.level or not isinstance(left.level, nodes.LevelMarker): raise self.interval_error - bin_op = lambda x, y: x * y # noqa: E731 + bin_op = lambda x, y: x * y # noqa: E731 [lambda-assignment] u_op = None else: raise GTScriptSyntaxError("Unexpected binary operator found in interval expression") @@ -249,7 +249,7 @@ def visit_BinOp(self, node: ast.BinOp) -> Union[gtscript.AxisIndex, nodes.AxisBo def visit_UnaryOp(self, node: ast.UnaryOp) -> nodes.AxisBound: if isinstance(node.op, ast.USub): - op = lambda x: -x # noqa: E731 + op = lambda x: -x # noqa: E731 [lambda-assignment] else: raise self.interval_error @@ -417,9 +417,7 @@ def visit_Assign(self, node: ast.Assign): else: return self.generic_visit(node) - def visit_Call( # Cyclomatic complexity too high - self, node: ast.Call, *, target_node=None - ): + def visit_Call(self, node: ast.Call, *, target_node=None): # Cyclomatic complexity too high call_name = gt_meta.get_qualified_name_from_node(node.func) if call_name in self.call_stack: @@ -461,10 +459,10 @@ def visit_Call( # Cyclomatic complexity too high if name not in call_args: assert arg_infos[name] != nodes.Empty call_args[name] = ast.Constant(value=arg_infos[name]) - except Exception: + except Exception as ex: raise GTScriptSyntaxError( message="Invalid call signature", loc=nodes.Location.from_ast_node(node) - ) + ) from ex # Rename local names in subroutine to avoid conflicts with caller context names try: @@ -601,7 +599,7 @@ def visit_If(self, node: ast.If): and node.test.func.id == "__INLINED" and len(node.test.args) == 1 ): - warnings.warn( + warnings.warn( # noqa: B028 [no-explicit-stacklevel] f"stencil {self.stencil_name}, line {node.lineno}, column {node.col_offset}: compile-time if condition via __INLINED deprecated", category=DeprecationWarning, ) @@ -1059,10 +1057,10 @@ def _eval_new_spatial_index( for index_node in index_nodes: try: value = gt_meta.ast_eval(index_node, axis_context) - except Exception: + except Exception as ex: raise GTScriptSyntaxError( message="Could not evaluate axis shift expression.", loc=index_node - ) + ) from ex if not isinstance(value, (gtscript.ShiftedAxis, gtscript.Axis)): raise GTScriptSyntaxError( message=f"Axis shift expression evaluated to unrecognized type {type(value)}.", diff --git a/src/gt4py/cartesian/frontend/node_util.py b/src/gt4py/cartesian/frontend/node_util.py index 6436bf2983..238e541053 100644 --- a/src/gt4py/cartesian/frontend/node_util.py +++ b/src/gt4py/cartesian/frontend/node_util.py @@ -69,7 +69,7 @@ def generic_visit(self, node: Node, **kwargs): else: pass - for key, value in items: + for _, value in items: self._visit(value, **kwargs) @@ -122,7 +122,7 @@ def iter_nodes_of_type(root_node: Node, node_type: Type) -> Generator[Node, None """Yield an iterator over the nodes of node_type inside root_node in DFS order.""" def recurse(node: Node) -> Generator[Node, None, None]: - for key, value in iter_attributes(node): + for _, value in iter_attributes(node): if isinstance(node, collections.abc.Iterable): if isinstance(node, collections.abc.Mapping): children = node.values() diff --git a/src/gt4py/cartesian/frontend/nodes.py b/src/gt4py/cartesian/frontend/nodes.py index 3f3207e9fe..c88775dea9 100644 --- a/src/gt4py/cartesian/frontend/nodes.py +++ b/src/gt4py/cartesian/frontend/nodes.py @@ -322,15 +322,6 @@ class ScalarLiteral(Literal): loc = attribute(of=Location, optional=True) -# @attribclass -# class TupleLiteral(Node): -# items = attribute(of=TupleOf[Expr]) -# -# @property -# def length(self): -# return len(self.items) - - @attribclass class BuiltinLiteral(Literal): value = attribute(of=Builtin) @@ -593,12 +584,6 @@ class Statement(Node): pass -# @attribclass -# class ExprStmt(Statement): -# expr = attribute(of=Expr) -# loc = attribute(of=Location, optional=True) - - class Decl(Statement): pass @@ -722,9 +707,6 @@ def is_single_index(self) -> bool: return self.start.level == self.end.level and self.start.offset == self.end.offset - 1 def disjoint_from(self, other: "AxisInterval") -> bool: - # This made-up constant must be larger than any LevelMarker.offset used - DOMAIN_SIZE: int = 1000 - def get_offset(bound: AxisBound) -> int: return ( 0 + bound.offset if bound.level == LevelMarker.START else sys.maxsize + bound.offset diff --git a/src/gt4py/cartesian/gtc/dace/expansion/tasklet_codegen.py b/src/gt4py/cartesian/gtc/dace/expansion/tasklet_codegen.py index e2ce48ec74..530d80d6b1 100644 --- a/src/gt4py/cartesian/gtc/dace/expansion/tasklet_codegen.py +++ b/src/gt4py/cartesian/gtc/dace/expansion/tasklet_codegen.py @@ -225,7 +225,7 @@ def _visit_conditional( indent = " " * 4 body_code = [line for block in self.visit(body, **kwargs) for line in block.split("\n")] body_code = [indent + b for b in body_code] - return "\n".join([mask_str] + body_code) + return "\n".join([mask_str, *body_code]) def visit_MaskStmt(self, node: dcir.MaskStmt, **kwargs): return self._visit_conditional(cond=node.mask, body=node.body, keyword="if", **kwargs) diff --git a/src/gt4py/cartesian/gtc/daceir.py b/src/gt4py/cartesian/gtc/daceir.py index 0366317360..fd254d46fa 100644 --- a/src/gt4py/cartesian/gtc/daceir.py +++ b/src/gt4py/cartesian/gtc/daceir.py @@ -43,7 +43,7 @@ class Stmt(common.Stmt): class Axis(eve.StrEnum): - I = "I" # noqa: E741 ambiguous variable name 'I' + I = "I" # noqa: E741 [ambiguous-variable-name] J = "J" K = "K" diff --git a/src/gt4py/cartesian/gtc/definitions.py b/src/gt4py/cartesian/gtc/definitions.py index 4b41aabee8..1b06d70737 100644 --- a/src/gt4py/cartesian/gtc/definitions.py +++ b/src/gt4py/cartesian/gtc/definitions.py @@ -23,7 +23,7 @@ class CartesianSpace: @enum.unique class Axis(enum.Enum): - I = 0 # noqa: E741 # Do not use variables named 'I', 'O', or 'l' + I = 0 # noqa: E741 [ambiguous-variable-name] J = 1 K = 2 diff --git a/src/gt4py/cartesian/gtc/gtcpp/oir_to_gtcpp.py b/src/gt4py/cartesian/gtc/gtcpp/oir_to_gtcpp.py index 58cddffd5f..06db14940b 100644 --- a/src/gt4py/cartesian/gtc/gtcpp/oir_to_gtcpp.py +++ b/src/gt4py/cartesian/gtc/gtcpp/oir_to_gtcpp.py @@ -17,7 +17,7 @@ from dataclasses import dataclass, field from typing import Any, Callable, Dict, List, Set, Union, cast -from devtools import debug # noqa: F401 +from devtools import debug # noqa: F401 [unused-import] from typing_extensions import Protocol from gt4py import eve diff --git a/src/gt4py/cartesian/gtc/numpy/npir.py b/src/gt4py/cartesian/gtc/numpy/npir.py index eec59e8831..42ceb161cc 100644 --- a/src/gt4py/cartesian/gtc/numpy/npir.py +++ b/src/gt4py/cartesian/gtc/numpy/npir.py @@ -22,7 +22,7 @@ # --- Misc --- class AxisName(eve.StrEnum): - I = "I" # noqa: E741 (ambiguous variable name) + I = "I" # noqa: E741 [ambiguous-variable-name] J = "J" K = "K" diff --git a/src/gt4py/cartesian/gtc/passes/gtir_definitive_assignment_analysis.py b/src/gt4py/cartesian/gtc/passes/gtir_definitive_assignment_analysis.py index 017723f8c8..fa5c3dbb7c 100644 --- a/src/gt4py/cartesian/gtc/passes/gtir_definitive_assignment_analysis.py +++ b/src/gt4py/cartesian/gtc/passes/gtir_definitive_assignment_analysis.py @@ -74,6 +74,6 @@ def check(gtir_stencil_expr: gtir.Stencil) -> gtir.Stencil: """Execute definitive assignment analysis and warn on errors.""" invalid_accesses = analyze(gtir_stencil_expr) for invalid_access in invalid_accesses: - warnings.warn(f"`{invalid_access.name}` may be uninitialized.") + warnings.warn(f"`{invalid_access.name}` may be uninitialized.", stacklevel=2) return gtir_stencil_expr diff --git a/src/gt4py/cartesian/gtc/passes/oir_optimizations/horizontal_execution_merging.py b/src/gt4py/cartesian/gtc/passes/oir_optimizations/horizontal_execution_merging.py index 9bb5cccc18..df923c6470 100644 --- a/src/gt4py/cartesian/gtc/passes/oir_optimizations/horizontal_execution_merging.py +++ b/src/gt4py/cartesian/gtc/passes/oir_optimizations/horizontal_execution_merging.py @@ -256,7 +256,7 @@ def first_has_horizontal_restriction() -> bool: or first_has_variable_access() or first_has_horizontal_restriction() ): - return [first] + self._merge(others, symtable, new_symbol_name, protected_fields) + return [first, *self._merge(others, symtable, new_symbol_name, protected_fields)] first_scalars = {decl.name for decl in first.declarations} writes = first_accesses.write_fields() diff --git a/src/gt4py/cartesian/gtc/passes/oir_optimizations/vertical_loop_merging.py b/src/gt4py/cartesian/gtc/passes/oir_optimizations/vertical_loop_merging.py index c684359eb7..daea8a2c02 100644 --- a/src/gt4py/cartesian/gtc/passes/oir_optimizations/vertical_loop_merging.py +++ b/src/gt4py/cartesian/gtc/passes/oir_optimizations/vertical_loop_merging.py @@ -38,7 +38,9 @@ def _mergeable(a: oir.VerticalLoop, b: oir.VerticalLoop) -> bool: def _merge(a: oir.VerticalLoop, b: oir.VerticalLoop) -> oir.VerticalLoop: sections = a.sections + b.sections if a.caches or b.caches: - warnings.warn("AdjacentLoopMerging pass removed previously declared caches") + warnings.warn( + "AdjacentLoopMerging pass removed previously declared caches", stacklevel=2 + ) return oir.VerticalLoop( loop_order=a.loop_order, sections=sections, diff --git a/src/gt4py/cartesian/gtc/ufuncs.py b/src/gt4py/cartesian/gtc/ufuncs.py index e3bc5a450d..f577e4bd02 100644 --- a/src/gt4py/cartesian/gtc/ufuncs.py +++ b/src/gt4py/cartesian/gtc/ufuncs.py @@ -40,7 +40,7 @@ not_equal: np.ufunc = np.not_equal logical_and: np.ufunc = np.logical_and logical_or: np.ufunc = np.logical_or -abs: np.ufunc = np.abs # noqa: A001 # shadowing abs builtin +abs: np.ufunc = np.abs # noqa: A001 [builtin-variable-shadowing] minimum: np.ufunc = np.minimum maximum: np.ufunc = np.maximum remainder: np.ufunc = np.remainder diff --git a/src/gt4py/cartesian/gtscript.py b/src/gt4py/cartesian/gtscript.py index 418fefc292..dbf6443caf 100644 --- a/src/gt4py/cartesian/gtscript.py +++ b/src/gt4py/cartesian/gtscript.py @@ -94,7 +94,7 @@ IGNORE_WHEN_INLINING = {*MATH_BUILTINS, "compile_assert"} -__all__ = list(builtins) + ["function", "stencil", "lazy_stencil"] +__all__ = [*list(builtins), "function", "stencil", "lazy_stencil"] __externals__ = "Placeholder" __gtscript__ = "Placeholder" @@ -581,7 +581,7 @@ def __sub__(self, shift): return ShiftedAxis(self.name, -shift) -I = Axis("I") +I = Axis("I") # noqa: E741 [ambiguous name] """I axes (parallel).""" J = Axis("J") @@ -634,8 +634,8 @@ def __init__(self, dtype, axes, data_dims=tuple()): data_dims = dtype.shape if dtype not in _VALID_DATA_TYPES: raise ValueError("Invalid data type descriptor") - except: - raise ValueError("Invalid data type descriptor") + except ValueError as ex: + raise ValueError("Invalid data type descriptor") from ex self.dtype = np.dtype(dtype) self.axes = axes if isinstance(axes, collections.abc.Collection) else [axes] if data_dims: @@ -674,14 +674,14 @@ def __getitem__(self, field_spec): data_dims = () if isinstance(field_spec, str) or not isinstance(field_spec, collections.abc.Collection): - # Field[dtype] + # Field[dtype] # noqa: ERA001 [commented-out-code] dtype = field_spec elif _FieldDescriptorMaker._is_axes_spec(field_spec[0]): - # Field[axes, dtype] + # Field[axes, dtype] # noqa: ERA001 [commented-out-code] assert len(field_spec) == 2 axes, dtype = field_spec elif len(field_spec) == 2 and not _FieldDescriptorMaker._is_axes_spec(field_spec[1]): - # Field[high_dimensional_dtype] + # Field[high_dimensional_dtype] # noqa: ERA001 [commented-out-code] dtype = field_spec else: raise ValueError("Invalid field type descriptor") @@ -765,17 +765,17 @@ def compile_assert(expr): # GTScript builtins: math functions -def abs(x): +def abs(x): # noqa: A001 [builtin-variable-shadowing] """Return the absolute value of the argument""" pass -def min(x, y): +def min(x, y): # noqa: A001 [builtin-variable-shadowing] """Return the smallest of two or more arguments.""" pass -def max(x, y): +def max(x, y): # noqa: A001 [builtin-variable-shadowing] """Return the largest of two or more arguments.""" pass diff --git a/src/gt4py/cartesian/stencil_object.py b/src/gt4py/cartesian/stencil_object.py index c1fe858d62..01f19070bc 100644 --- a/src/gt4py/cartesian/stencil_object.py +++ b/src/gt4py/cartesian/stencil_object.py @@ -376,8 +376,8 @@ def _validate_args( # Function is too complex try: domain = Shape(domain) - except Exception: - raise ValueError("Invalid 'domain' value ({})".format(domain)) + except Exception as ex: + raise ValueError("Invalid 'domain' value ({})".format(domain)) from ex if not domain > Shape.zeros(domain_ndim): raise ValueError(f"Compute domain contains zero sizes '{domain}')") @@ -420,7 +420,8 @@ def _validate_args( # Function is too complex warnings.warn( f"The layout of the field '{name}' is not recommended for this backend." f"This may lead to performance degradation. Please consider using the" - f"provided allocators in `gt4py.storage`." + f"provided allocators in `gt4py.storage`.", + stacklevel=2, ) field_dtype = self.field_info[name].dtype diff --git a/src/gt4py/cartesian/utils/attrib.py b/src/gt4py/cartesian/utils/attrib.py index 46bbf3dcfd..ad586823ea 100644 --- a/src/gt4py/cartesian/utils/attrib.py +++ b/src/gt4py/cartesian/utils/attrib.py @@ -83,7 +83,6 @@ def _make_type_validator(t): if isinstance(t, type): return attr.validators.instance_of(t) else: - # isinstance(t, _TypeDescriptor) return t.validator @@ -97,12 +96,12 @@ def _is_sequence_of_validator(instance, attribute, value): try: assert isinstance(value, tuple(container_types)) assert isinstance([item_validator(instance, attribute, v) for v in value], list) - except Exception: + except Exception as ex: raise ValueError( "Expr ({value}) does not match the '{name}' specification".format( value=value, name=attribute.name ) - ) + ) from ex return _is_sequence_of_validator @@ -126,12 +125,12 @@ def _is_dict_of_validator(instance, attribute, value): assert isinstance( [value_validator(instance, attribute, v) for v in value.values()], list ) - except Exception: + except Exception as ex: raise ValueError( "Expr ({value}) does not match the '{name}' specification".format( value=value, name=attribute.name ) - ) + ) from ex return _is_dict_of_validator @@ -151,12 +150,12 @@ def _is_tuple_of_validator(instance, attribute, value): ], list, ) - except Exception: + except Exception as ex: raise ValueError( "Expr ({value}) does not match the '{name}' specification".format( value=value, name=attribute.name ) - ) + ) from ex return _is_tuple_of_validator @@ -224,7 +223,7 @@ def attribute(of, optional=False, **kwargs): attr_type_hint = of.type_hint elif isinstance(of, type): - # assert of in (bool, float, str, int, enum.Enum) + # assert of in (bool, float, str, int, enum.Enum) # noqa: ERA001 [commented-out-code] attr_validator = attr.validators.instance_of(of) attr_type_hint = of @@ -234,7 +233,6 @@ def attribute(of, optional=False, **kwargs): if optional: attr_validator = attr.validators.optional(attr_validator) kwargs.setdefault("default", None) - # kwargs["kw_only"] = True return attr.ib(validator=attr_validator, type=attr_type_hint, **kwargs) diff --git a/src/gt4py/cartesian/utils/base.py b/src/gt4py/cartesian/utils/base.py index dca8a1f420..fa4ba7bce9 100644 --- a/src/gt4py/cartesian/utils/base.py +++ b/src/gt4py/cartesian/utils/base.py @@ -197,7 +197,7 @@ def shashed_id(*args, length=10, hash_algorithm=None): return shash(*args, hash_algorithm=hash_algorithm)[:length] -def classmethod_to_function(class_method, instance=None, owner=type(None), remove_cls_arg=False): +def classmethod_to_function(class_method, instance=None, owner=None, remove_cls_arg=False): if remove_cls_arg: return functools.partial(class_method.__get__(instance, owner), None) else: diff --git a/src/gt4py/cartesian/utils/meta.py b/src/gt4py/cartesian/utils/meta.py index 769b097f54..a4d9bbc084 100644 --- a/src/gt4py/cartesian/utils/meta.py +++ b/src/gt4py/cartesian/utils/meta.py @@ -20,7 +20,7 @@ import operator import platform import textwrap -from typing import Callable, Dict, List, Tuple, Type +from typing import Callable, Dict, Final, List, Tuple, Type from packaging import version @@ -208,7 +208,7 @@ def get_qualified_name_from_node(name_or_attribute, *, as_list=False): else: assert isinstance(node, ast.Attribute) components = get_qualified_name_from_node(node.value, as_list=True) - components = components + [node.attr] + components = [*components, node.attr] return components if as_list else ".".join(components) @@ -260,7 +260,7 @@ def generic_visit(self, node, **kwargs): class ASTEvaluator(ASTPass): - AST_OP_TO_OP: Dict[Type, Callable] = { + AST_OP_TO_OP: Final[Dict[Type, Callable]] = { # Arithmetic operations ast.UAdd: operator.pos, ast.USub: operator.neg, @@ -429,7 +429,7 @@ def _get_name_components(self, node: ast.AST): valid = self.prefixes is None or node.id in self.prefixes elif isinstance(node, ast.Attribute): components, valid = self._get_name_components(node.value) - components = components + [node.attr] + components = [*components, node.attr] valid = valid or ".".join(components) in self.prefixes else: components = [None] diff --git a/src/gt4py/eve/datamodels/__init__.py b/src/gt4py/eve/datamodels/__init__.py index c57ab7c8c2..d329eda67e 100644 --- a/src/gt4py/eve/datamodels/__init__.py +++ b/src/gt4py/eve/datamodels/__init__.py @@ -114,4 +114,4 @@ """ from . import core as core, validators as validators # imported but unused -from .core import * # noqa: # star unused import +from .core import * # noqa: F403 [undefined-local-with-import-star] diff --git a/src/gt4py/eve/datamodels/core.py b/src/gt4py/eve/datamodels/core.py index ba13bdf166..d98023cb5a 100644 --- a/src/gt4py/eve/datamodels/core.py +++ b/src/gt4py/eve/datamodels/core.py @@ -267,7 +267,7 @@ def datamodel( cls: Literal[None] = None, /, *, - repr: bool = _REPR_DEFAULT, # noqa: A002 # shadowing 'repr' python builtin + repr: bool = _REPR_DEFAULT, # noqa: A002 [builtin-argument-shadowing] eq: bool = _EQ_DEFAULT, order: bool = _ORDER_DEFAULT, unsafe_hash: bool = _UNSAFE_HASH_DEFAULT, @@ -286,7 +286,7 @@ def datamodel( # redefinion of unused symbol cls: Type[_T], /, *, - repr: bool = _REPR_DEFAULT, # noqa: A002 # shadowing 'repr' python builtin + repr: bool = _REPR_DEFAULT, # noqa: A002 [builtin-argument-shadowing] eq: bool = _EQ_DEFAULT, order: bool = _ORDER_DEFAULT, unsafe_hash: bool = _UNSAFE_HASH_DEFAULT, @@ -305,7 +305,7 @@ def datamodel( # redefinion of unused symbol cls: Optional[Type[_T]] = None, /, *, - repr: bool = _REPR_DEFAULT, # noqa: A002 # shadowing 'repr' python builtin + repr: bool = _REPR_DEFAULT, # noqa: A002 [builtin-argument-shadowing] eq: bool = _EQ_DEFAULT, order: bool = _ORDER_DEFAULT, unsafe_hash: bool = _UNSAFE_HASH_DEFAULT, @@ -394,7 +394,7 @@ def __call__( cls: Optional[Type[_T]] = None, /, *, - repr: bool = _REPR_DEFAULT, # noqa: A002 # shadowing 'repr' python builtin + repr: bool = _REPR_DEFAULT, # noqa: A002 [builtin-argument-shadowing] eq: bool = _EQ_DEFAULT, order: bool = _ORDER_DEFAULT, unsafe_hash: bool = _UNSAFE_HASH_DEFAULT, @@ -446,7 +446,7 @@ def __init_subclass__( cls, /, *, - repr: ( # noqa: A002 # shadowing 'repr' python builtin + repr: ( # noqa: A002 [builtin-argument-shadowing] bool | None | Literal["inherited"] ) = "inherited", eq: bool | None | Literal["inherited"] = "inherited", @@ -507,8 +507,8 @@ def field( default: Any = NOTHING, default_factory: Optional[Callable[[], Any]] = None, init: bool = True, - repr: bool = True, # noqa: A002 # shadowing 'repr' python builtin - hash: Optional[bool] = None, # noqa: A002 # shadowing 'hash' python builtin + repr: bool = True, # noqa: A002 [builtin-argument-shadowing] + hash: Optional[bool] = None, # noqa: A002 [builtin-argument-shadowing] compare: bool = True, metadata: Optional[Mapping[Any, Any]] = None, kw_only: bool = _KW_ONLY_DEFAULT, @@ -543,7 +543,7 @@ def field( have their own key, to use as a namespace in the metadata. kw_only: If ``True`` (default is ``False``), make this field keyword-only in the generated ``__init__`` (if ``init`` is ``False``, this parameter is ignored). - converter: Callable that is automatically called to convert attribute’s value. + converter: Callable that is automatically called to convert attribute's value. It is given the passed-in value, and the returned value will be used as the new value of the attribute before being passed to the validator, if any. If ``"coerce"`` is passed, a naive coercer converter will be generated. @@ -660,7 +660,7 @@ def get_fields(model: Union[DataModel, Type[DataModel]]) -> utils.FrozenNamespac >>> fields(Model) # doctest:+ELLIPSIS FrozenNamespace(...name=Attribute(name='name', default=NOTHING, ... - """ # doctest conventions confuse RST validator + """ if not is_datamodel(model): raise TypeError(f"Invalid datamodel instance or class: '{model}'.") if not isinstance(model, type): @@ -695,7 +695,7 @@ def asdict( ... y: int >>> c = C(x=1, y=2) >>> assert asdict(c) == {"x": 1, "y": 2} - """ # sphinx.napoleon conventions confuse RST validator + """ if not is_datamodel(instance) or isinstance(instance, type): raise TypeError(f"Invalid datamodel instance: '{instance}'.") return attrs.asdict(instance, value_serializer=value_serializer) @@ -805,12 +805,12 @@ def concretize( overwrite_definition: If ``True``, a previous definition of the class in the target module will be overwritten. - """ # doctest conventions confuse RST validator + """ concrete_cls: Type[DataModelT] = _make_concrete_with_cache( - datamodel_cls, + datamodel_cls, # type: ignore[arg-type] *type_args, class_name=class_name, - module=module, # type: ignore[arg-type] + module=module, ) assert isinstance(concrete_cls, type) and is_datamodel(concrete_cls) @@ -825,7 +825,8 @@ def concretize( RuntimeWarning( f"Existing '{class_name}' symbol in module '{module}' contains a reference" "to a different object." - ) + ), + stacklevel=2, ) return concrete_cls @@ -1021,10 +1022,10 @@ def _type_converter(value: Any) -> _T: _KNOWN_MUTABLE_TYPES: Final = (list, dict, set) -def _make_datamodel( # too complex but still readable and documented +def _make_datamodel( cls: Type[_T], *, - repr: bool, # noqa: A002 # shadowing 'repr' python builtin + repr: bool, # noqa: A002 [builtin-argument-shadowing] eq: bool, order: bool, unsafe_hash: bool, @@ -1072,7 +1073,7 @@ def _make_datamodel( # too complex but still readable and documented # Create type validator if validation is enabled if type_validation_factory is None or _UNCHECKED_TYPE_TAG in type_extras: - type_validator = lambda a, b, c: None # noqa: E731 + type_validator = lambda a, b, c: None # noqa: E731 [lambda-assignment] else: type_validator = type_validation_factory(type_hint, qualified_field_name) @@ -1183,8 +1184,8 @@ def _make_datamodel( # too complex but still readable and documented cls.__attrs_pre_init__ = cls.__pre_init__ # type: ignore[attr-defined] # adding new attribute if "__attrs_post_init__" in cls.__dict__ and not hasattr( - cls.__attrs_post_init__, - _DATAMODEL_TAG, # type: ignore[attr-defined] # mypy doesn't know about __attr_post_init__ + cls.__attrs_post_init__, # type: ignore[attr-defined] # mypy doesn't know about __attr_post_init__ + _DATAMODEL_TAG, ): raise TypeError(f"'{cls.__name__}' class contains forbidden custom '__attrs_post_init__'.") cls.__attrs_post_init__ = _make_post_init(has_post_init="__post_init__" in cls.__dict__) # type: ignore[attr-defined] # adding new attribute diff --git a/src/gt4py/eve/extended_typing.py b/src/gt4py/eve/extended_typing.py index 4fa56cc264..acb2103602 100644 --- a/src/gt4py/eve/extended_typing.py +++ b/src/gt4py/eve/extended_typing.py @@ -33,12 +33,12 @@ import sys as _sys import types as _types import typing as _typing -from typing import * # noqa: F403 +from typing import * # noqa: F403 [undefined-local-with-import-star] from typing import overload # Only needed to avoid false flake8 errors import numpy.typing as npt import typing_extensions as _typing_extensions -from typing_extensions import * # type: ignore[assignment,no-redef] # noqa: F403 +from typing_extensions import * # type: ignore[assignment,no-redef] # noqa: F403 [undefined-local-with-import-star] if _sys.version_info >= (3, 9): @@ -180,11 +180,9 @@ def __get__( ) -> NonDataDescriptor[_C, _V]: ... @overload - def __get__( # redefinion of unused member - self, _instance: _C, _owner_type: Optional[Type[_C]] = None - ) -> _V: ... + def __get__(self, _instance: _C, _owner_type: Optional[Type[_C]] = None) -> _V: ... - def __get__( # redefinion of unused member + def __get__( self, _instance: Optional[_C], _owner_type: Optional[Type[_C]] = None ) -> _V | NonDataDescriptor[_C, _V]: ... @@ -351,7 +349,7 @@ def extended_runtime_checkable( ) -> _ProtoT: ... -def extended_runtime_checkable( # too complex but unavoidable +def extended_runtime_checkable( maybe_cls: Optional[_ProtoT] = None, *, instance_check_shortcut: bool = True, @@ -697,7 +695,7 @@ class CallableKwargsInfo: data: Dict[str, Any] -def infer_type( # function is complex but well organized in independent cases +def infer_type( value: Any, *, annotate_callable_kwargs: bool = False, diff --git a/src/gt4py/eve/trees.py b/src/gt4py/eve/trees.py index dabb48105b..fb9390efc0 100644 --- a/src/gt4py/eve/trees.py +++ b/src/gt4py/eve/trees.py @@ -42,7 +42,7 @@ import cytoolz as toolz except ModuleNotFoundError: # Fall back to pure Python toolz - import toolz # noqa: F401 # imported but unused + import toolz # noqa: F401 [unused-import] TreeKey = Union[int, str] @@ -52,7 +52,7 @@ TreeLike = Any else: - class TreeLike(abc.ABC): # noqa: B024 + class TreeLike(abc.ABC): # noqa: B024 [abstract-base-class-without-abstract-method] ... diff --git a/src/gt4py/eve/type_definitions.py b/src/gt4py/eve/type_definitions.py index d2cf87c644..c0a8507fdd 100644 --- a/src/gt4py/eve/type_definitions.py +++ b/src/gt4py/eve/type_definitions.py @@ -19,7 +19,7 @@ import abc import re import sys -from enum import Enum as Enum, IntEnum as IntEnum # imported but unused +from enum import Enum as Enum, IntEnum as IntEnum from boltons.typeutils import classproperty as classproperty from frozendict import frozendict as _frozendict @@ -42,7 +42,7 @@ _Tc = TypeVar("_Tc", covariant=True) -class FrozenList(Tuple[_Tc, ...], metaclass=abc.ABCMeta): # no abstract methods +class FrozenList(Tuple[_Tc, ...], metaclass=abc.ABCMeta): """Tuple subtype which works as an alias of ``Tuple[_Tc, ...]``.""" __slots__ = () diff --git a/src/gt4py/eve/type_validation.py b/src/gt4py/eve/type_validation.py index f67741c658..43e059dc40 100644 --- a/src/gt4py/eve/type_validation.py +++ b/src/gt4py/eve/type_validation.py @@ -112,7 +112,7 @@ def __call__( ) -> FixedTypeValidator: ... @overload - def __call__( # redefinion of unused member + def __call__( self, type_annotation: TypeAnnotation, name: Optional[str] = None, @@ -124,7 +124,7 @@ def __call__( # redefinion of unused member ) -> Optional[FixedTypeValidator]: ... @abc.abstractmethod - def __call__( # redefinion of unused member + def __call__( self, type_annotation: TypeAnnotation, name: Optional[str] = None, @@ -169,7 +169,7 @@ def __call__( ) -> FixedTypeValidator: ... @overload - def __call__( # redefinion of unused member + def __call__( self, type_annotation: TypeAnnotation, name: Optional[str] = None, @@ -180,7 +180,7 @@ def __call__( # redefinion of unused member **kwargs: Any, ) -> Optional[FixedTypeValidator]: ... - def __call__( # redefinion of unused member / complex but well organized in cases + def __call__( self, type_annotation: TypeAnnotation, name: Optional[str] = None, diff --git a/src/gt4py/eve/utils.py b/src/gt4py/eve/utils.py index 5a89e83b74..aab530db43 100644 --- a/src/gt4py/eve/utils.py +++ b/src/gt4py/eve/utils.py @@ -695,7 +695,7 @@ def reset_sequence(self, start: int = 1, *, warn_unsafe: Optional[bool] = None) if warn_unsafe is None: warn_unsafe = self.warn_unsafe if warn_unsafe and start < next(self._counter): - warnings.warn("Unsafe reset of UIDGenerator ({self})") + warnings.warn("Unsafe reset of UIDGenerator ({self})", stacklevel=2) self._counter = itertools.count(start) return self @@ -783,9 +783,7 @@ def map(self, func: Callable) -> XIterable[Any]: # A003: shadowing a python bui raise ValueError(f"Invalid function or callable: '{func}'.") return XIterable(map(func, self.iterator)) - def filter( # A003: shadowing a python builtin - self, func: Callable[..., bool] - ) -> XIterable[T]: + def filter(self, func: Callable[..., bool]) -> XIterable[T]: # A003: shadowing a python builtin """Filter elements with callables. Equivalent to ``filter(func, self)``. diff --git a/src/gt4py/next/__init__.py b/src/gt4py/next/__init__.py index 1398af5f03..bcc8196da2 100644 --- a/src/gt4py/next/__init__.py +++ b/src/gt4py/next/__init__.py @@ -31,7 +31,7 @@ ) from .ffront import fbuiltins from .ffront.decorator import field_operator, program, scan_operator -from .ffront.fbuiltins import * # noqa: F403 # fbuiltins defines __all__ and we explicitly want to reexport everything here +from .ffront.fbuiltins import * # noqa: F403 [undefined-local-with-import-star] explicitly reexport all from fbuiltins.__all__ from .ffront.fbuiltins import FieldOffset from .iterator.embedded import ( NeighborTableOffsetProvider, diff --git a/src/gt4py/next/common.py b/src/gt4py/next/common.py index c8e9e6c18e..cf539fc8fa 100644 --- a/src/gt4py/next/common.py +++ b/src/gt4py/next/common.py @@ -167,10 +167,9 @@ def __repr__(self) -> str: def __getitem__(self, index: int) -> int: ... @overload - def __getitem__(self, index: slice) -> UnitRange: # redefine unused - ... + def __getitem__(self, index: slice) -> UnitRange: ... - def __getitem__(self, index: int | slice) -> int | UnitRange: # redefine unused + def __getitem__(self, index: int | slice) -> int | UnitRange: assert UnitRange.is_finite(self) if isinstance(index, slice): start, stop, step = index.indices(len(self)) @@ -425,17 +424,12 @@ def is_finite(cls, obj: Domain) -> TypeGuard[FiniteDomain]: def __getitem__(self, index: int) -> tuple[Dimension, _Rng]: ... @overload - def __getitem__(self, index: slice) -> Self: # redefine unused - ... + def __getitem__(self, index: slice) -> Self: ... @overload - def __getitem__( # redefine unused - self, index: Dimension - ) -> tuple[Dimension, _Rng]: ... + def __getitem__(self, index: Dimension) -> tuple[Dimension, _Rng]: ... - def __getitem__( # redefine unused - self, index: int | slice | Dimension - ) -> NamedRange | Domain: # redefine unused + def __getitem__(self, index: int | slice | Dimension) -> NamedRange | Domain: if isinstance(index, int): return self.dims[index], self.ranges[index] elif isinstance(index, slice): @@ -446,8 +440,8 @@ def __getitem__( # redefine unused try: index_pos = self.dims.index(index) return self.dims[index_pos], self.ranges[index_pos] - except ValueError: - raise KeyError(f"No Dimension of type '{index}' is present in the Domain.") + except ValueError as ex: + raise KeyError(f"No Dimension of type '{index}' is present in the Domain.") from ex else: raise KeyError("Invalid index type, must be either int, slice, or Dimension.") diff --git a/src/gt4py/next/constructors.py b/src/gt4py/next/constructors.py index 47f2bc3264..12968fc4f3 100644 --- a/src/gt4py/next/constructors.py +++ b/src/gt4py/next/constructors.py @@ -29,7 +29,7 @@ @eve.utils.with_fluid_partial def empty( domain: common.DomainLike, - dtype: core_defs.DTypeLike = core_defs.Float64DType(()), + dtype: core_defs.DTypeLike = core_defs.Float64DType(()), # noqa: B008 [function-call-in-default-argument] *, aligned_index: Optional[Sequence[common.NamedIndex]] = None, allocator: Optional[next_allocators.FieldBufferAllocationUtil] = None, @@ -96,7 +96,7 @@ def empty( @eve.utils.with_fluid_partial def zeros( domain: common.DomainLike, - dtype: core_defs.DTypeLike = core_defs.Float64DType(()), + dtype: core_defs.DTypeLike = core_defs.Float64DType(()), # noqa: B008 [function-call-in-default-argument] *, aligned_index: Optional[Sequence[common.NamedIndex]] = None, allocator: Optional[next_allocators.FieldBufferAllocatorProtocol] = None, @@ -128,7 +128,7 @@ def zeros( @eve.utils.with_fluid_partial def ones( domain: common.DomainLike, - dtype: core_defs.DTypeLike = core_defs.Float64DType(()), + dtype: core_defs.DTypeLike = core_defs.Float64DType(()), # noqa: B008 [function-call-in-default-argument] *, aligned_index: Optional[Sequence[common.NamedIndex]] = None, allocator: Optional[next_allocators.FieldBufferAllocatorProtocol] = None, @@ -205,7 +205,7 @@ def as_field( aligned_index: Optional[Sequence[common.NamedIndex]] = None, allocator: Optional[next_allocators.FieldBufferAllocatorProtocol] = None, device: Optional[core_defs.Device] = None, - # copy=False, TODO + # TODO: copy=False ) -> nd_array_field.NdArrayField: """Create a Field from an array-like object using the given (or device-default) allocator. @@ -307,7 +307,7 @@ def as_connectivity( allocator: Optional[next_allocators.FieldBufferAllocatorProtocol] = None, device: Optional[core_defs.Device] = None, skip_value: Optional[core_defs.IntegralScalar] = None, - # copy=False, TODO + # TODO: copy=False ) -> common.ConnectivityField: """ Construct a connectivity field from the given domain, codomain, and data. diff --git a/src/gt4py/next/embedded/common.py b/src/gt4py/next/embedded/common.py index 0832af14a1..0ba39d377a 100644 --- a/src/gt4py/next/embedded/common.py +++ b/src/gt4py/next/embedded/common.py @@ -51,10 +51,10 @@ def _relative_sub_domain( try: sliced = _slice_range(rng, idx) named_ranges.append((dim, sliced)) - except IndexError: + except IndexError as ex: raise embedded_exceptions.IndexOutOfBounds( domain=domain, indices=index, index=idx, dim=dim - ) + ) from ex else: # not in new domain assert common.is_int_index(idx) @@ -164,11 +164,11 @@ def _named_slice_to_named_range( assert hasattr(idx, "start") and hasattr(idx, "stop") if common.is_named_slice(idx): idx_start_0, idx_start_1, idx_stop_0, idx_stop_1 = ( - idx.start[0], - idx.start[1], - idx.stop[0], - idx.stop[1], - ) # type: ignore[attr-defined] + idx.start[0], # type: ignore[attr-defined] + idx.start[1], # type: ignore[attr-defined] + idx.stop[0], # type: ignore[attr-defined] + idx.stop[1], # type: ignore[attr-defined] + ) if idx_start_0 != idx_stop_0: raise IndexError( f"Dimensions slicing mismatch between '{idx_start_0.value}' and '{idx_stop_0.value}'." diff --git a/src/gt4py/next/embedded/nd_array_field.py b/src/gt4py/next/embedded/nd_array_field.py index 8b22118469..1760cb17e8 100644 --- a/src/gt4py/next/embedded/nd_array_field.py +++ b/src/gt4py/next/embedded/nd_array_field.py @@ -486,12 +486,12 @@ def _hypercube( # -- Specialized implementations for builtin operations on array fields -- NdArrayField.register_builtin_func( - fbuiltins.abs, - NdArrayField.__abs__, # type: ignore[attr-defined] + fbuiltins.abs, # type: ignore[attr-defined] + NdArrayField.__abs__, ) NdArrayField.register_builtin_func( - fbuiltins.power, - NdArrayField.__pow__, # type: ignore[attr-defined] + fbuiltins.power, # type: ignore[attr-defined] + NdArrayField.__pow__, ) # TODO gamma @@ -505,16 +505,16 @@ def _hypercube( NdArrayField.register_builtin_func(getattr(fbuiltins, name), _make_builtin(name, name)) NdArrayField.register_builtin_func( - fbuiltins.minimum, - _make_builtin("minimum", "minimum"), # type: ignore[attr-defined] + fbuiltins.minimum, # type: ignore[attr-defined] + _make_builtin("minimum", "minimum"), ) NdArrayField.register_builtin_func( - fbuiltins.maximum, - _make_builtin("maximum", "maximum"), # type: ignore[attr-defined] + fbuiltins.maximum, # type: ignore[attr-defined] + _make_builtin("maximum", "maximum"), ) NdArrayField.register_builtin_func( - fbuiltins.fmod, - _make_builtin("fmod", "fmod"), # type: ignore[attr-defined] + fbuiltins.fmod, # type: ignore[attr-defined] + _make_builtin("fmod", "fmod"), ) NdArrayField.register_builtin_func(fbuiltins.where, _make_builtin("where", "where")) diff --git a/src/gt4py/next/embedded/operators.py b/src/gt4py/next/embedded/operators.py index d48e6c0b4e..0982024090 100644 --- a/src/gt4py/next/embedded/operators.py +++ b/src/gt4py/next/embedded/operators.py @@ -42,9 +42,11 @@ class ScanOperator(EmbeddedOperator[_R, _P]): init: core_defs.Scalar | tuple[core_defs.Scalar | tuple, ...] axis: common.Dimension - def __call__( - self, *args: common.Field | core_defs.Scalar, **kwargs: common.Field | core_defs.Scalar - ) -> common.Field: # type: ignore[override] # we cannot properly type annotate relative to self.fun + def __call__( # type: ignore[override] + self, + *args: common.Field | core_defs.Scalar, + **kwargs: common.Field | core_defs.Scalar, # type: ignore[override] + ) -> common.Field: scan_range = embedded_context.closure_column_range.get() assert self.axis == scan_range[0] scan_axis = scan_range[0] diff --git a/src/gt4py/next/errors/__init__.py b/src/gt4py/next/errors/__init__.py index c965332929..475a43bbf5 100644 --- a/src/gt4py/next/errors/__init__.py +++ b/src/gt4py/next/errors/__init__.py @@ -14,9 +14,7 @@ """Contains the exception classes and other utilities for error handling.""" -from . import ( # noqa: module needs to be loaded for pretty printing of uncaught exceptions. - excepthook, -) +from . import excepthook # noqa: F401 [unused-import] from .exceptions import ( DSLError, InvalidParameterAnnotationError, diff --git a/src/gt4py/next/ffront/decorator.py b/src/gt4py/next/ffront/decorator.py index a152439a65..60e96a6cc2 100644 --- a/src/gt4py/next/ffront/decorator.py +++ b/src/gt4py/next/ffront/decorator.py @@ -248,8 +248,8 @@ def with_bound_args(self, **kwargs) -> ProgramWithBoundArgs: >>> import gt4py.next as gtx >>> @gtx.program # doctest: +SKIP - ... def program(condition: bool, out: gtx.Field[[IDim], float]): # noqa: F821 - ... sample_field_operator(condition, out=out) # noqa: F821 + ... def program(condition: bool, out: gtx.Field[[IDim], float]): # noqa: F821 [undefined-name] + ... sample_field_operator(condition, out=out) # noqa: F821 [undefined-name] Create a new program from `program` with the `condition` parameter set to `True`: @@ -258,8 +258,8 @@ def with_bound_args(self, **kwargs) -> ProgramWithBoundArgs: The resulting program is equivalent to >>> @gtx.program # doctest: +SKIP - ... def program(condition: bool, out: gtx.Field[[IDim], float]): # noqa: F821 - ... sample_field_operator(condition=True, out=out) # noqa: F821 + ... def program(condition: bool, out: gtx.Field[[IDim], float]): # noqa: F821 [undefined-name] + ... sample_field_operator(condition=True, out=out) # noqa: F821 [undefined-name] and can be executed without passing `condition`. @@ -298,7 +298,8 @@ def __call__(self, *args, offset_provider: dict[str, Dimension], **kwargs) -> No warnings.warn( UserWarning( f"Field View Program '{self.itir.id}': Using Python execution, consider selecting a perfomance backend." - ) + ), + stacklevel=2, ) with next_embedded.context.new_context(offset_provider=offset_provider) as ctx: ctx.run(self.definition, *rewritten_args, **kwargs) @@ -513,18 +514,18 @@ def program( Generate an implementation of a program from a Python function object. Examples: - >>> @program # noqa: F821 # doctest: +SKIP - ... def program(in_field: Field[[TDim], float64], out_field: Field[[TDim], float64]): # noqa: F821 + >>> @program # noqa: F821 [undefined-name] # doctest: +SKIP + ... def program(in_field: Field[[TDim], float64], out_field: Field[[TDim], float64]): # noqa: F821 [undefined-name] ... field_op(in_field, out=out_field) - >>> program(in_field, out=out_field) # noqa: F821 # doctest: +SKIP + >>> program(in_field, out=out_field) # noqa: F821 [undefined-name] # doctest: +SKIP >>> # the backend can optionally be passed if already decided >>> # not passing it will result in embedded execution by default >>> # the above is equivalent to - >>> @program(backend="roundtrip") # noqa: F821 # doctest: +SKIP - ... def program(in_field: Field[[TDim], float64], out_field: Field[[TDim], float64]): # noqa: F821 + >>> @program(backend="roundtrip") # noqa: F821 [undefined-name] # doctest: +SKIP + ... def program(in_field: Field[[TDim], float64], out_field: Field[[TDim], float64]): # noqa: F821 [undefined-name] ... field_op(in_field, out=out_field) - >>> program(in_field, out=out_field) # noqa: F821 # doctest: +SKIP + >>> program(in_field, out=out_field) # noqa: F821 [undefined-name] # doctest: +SKIP """ def program_inner(definition: types.FunctionType) -> Program: @@ -688,7 +689,7 @@ def as_program( untyped_past_node = past.Program( id=f"__field_operator_{self.foast_node.id}", type=ts.DeferredType(constraint=ts_ffront.ProgramType), - params=params_decl + [out_sym], + params=[*params_decl, out_sym], body=[ past.Call( func=past.Name(id=self.foast_node.id, location=loc), @@ -774,14 +775,14 @@ def field_operator(definition=None, *, backend=eve.NOTHING, grid_type=None): Examples: >>> @field_operator # doctest: +SKIP - ... def field_op(in_field: Field[[TDim], float64]) -> Field[[TDim], float64]: # noqa: F821 + ... def field_op(in_field: Field[[TDim], float64]) -> Field[[TDim], float64]: # noqa: F821 [undefined-name] ... ... - >>> field_op(in_field, out=out_field) # noqa: F821 # doctest: +SKIP + >>> field_op(in_field, out=out_field) # noqa: F821 [undefined-name] # doctest: +SKIP >>> # the backend can optionally be passed if already decided >>> # not passing it will result in embedded execution by default >>> @field_operator(backend="roundtrip") # doctest: +SKIP - ... def field_op(in_field: Field[[TDim], float64]) -> Field[[TDim], float64]: # noqa: F821 + ... def field_op(in_field: Field[[TDim], float64]) -> Field[[TDim], float64]: # noqa: F821 [undefined-name] ... ... """ diff --git a/src/gt4py/next/ffront/dialect_parser.py b/src/gt4py/next/ffront/dialect_parser.py index 07490db27c..9bafdf02ea 100644 --- a/src/gt4py/next/ffront/dialect_parser.py +++ b/src/gt4py/next/ffront/dialect_parser.py @@ -50,7 +50,7 @@ def parse_source_definition(source_definition: SourceDefinition) -> ast.AST: else None ), ) - raise errors.DSLError(loc, err.msg).with_traceback(err.__traceback__) + raise errors.DSLError(loc, err.msg).with_traceback(err.__traceback__) from err @dataclass(frozen=True, kw_only=True) diff --git a/src/gt4py/next/ffront/fbuiltins.py b/src/gt4py/next/ffront/fbuiltins.py index 743a3be3cf..03b0cdc1a1 100644 --- a/src/gt4py/next/ffront/fbuiltins.py +++ b/src/gt4py/next/ffront/fbuiltins.py @@ -24,8 +24,8 @@ import gt4py.next as gtx from gt4py._core import definitions as core_defs from gt4py.next import common, embedded -from gt4py.next.common import Dimension, Field # noqa: F401 # direct import for TYPE_BUILTINS -from gt4py.next.ffront.experimental import as_offset # noqa: F401 +from gt4py.next.common import Dimension, Field # noqa: F401 [unused-import] for TYPE_BUILTINS +from gt4py.next.ffront.experimental import as_offset # noqa: F401 [unused-import] from gt4py.next.iterator import runtime from gt4py.next.type_system import type_specifications as ts @@ -40,7 +40,8 @@ int64, float32, float64, -] + PYTHON_TYPE_BUILTINS + *PYTHON_TYPE_BUILTINS, +] TYPE_BUILTIN_NAMES = [t.__name__ for t in TYPE_BUILTINS] # Be aware: Type aliases are not fully supported in the frontend yet, e.g. `IndexType(1)` will not @@ -244,8 +245,8 @@ def astype( def _make_unary_math_builtin(name): def impl(value: common.Field | core_defs.ScalarT, /) -> common.Field | core_defs.ScalarT: # TODO(havogt): enable once we have a failing test (see `test_math_builtin_execution.py`) - # assert core_defs.is_scalar_type(value) # default implementation for scalars, Fields are handled via dispatch # commented code - # return getattr(math, name)(value)# commented code + # assert core_defs.is_scalar_type(value) # default implementation for scalars, Fields are handled via dispatch # noqa: ERA001 [commented-out-code] + # return getattr(math, name)(value)# noqa: ERA001 [commented-out-code] raise NotImplementedError() impl.__name__ = name @@ -295,7 +296,8 @@ def impl( "where", "astype", "as_offset", -] + MATH_BUILTIN_NAMES + *MATH_BUILTIN_NAMES, +] BUILTIN_NAMES = TYPE_BUILTIN_NAMES + FUN_BUILTIN_NAMES diff --git a/src/gt4py/next/ffront/field_operator_ast.py b/src/gt4py/next/ffront/field_operator_ast.py index dde6211076..88564900ac 100644 --- a/src/gt4py/next/ffront/field_operator_ast.py +++ b/src/gt4py/next/ffront/field_operator_ast.py @@ -51,7 +51,7 @@ def __str__(self): # class Symbol(eve.GenericNode, LocatedNode, Generic[SymbolT]): # class Symbol(LocatedNode, Generic[SymbolT]): - id: Coerced[SymbolName] # shadowing a python builtin + id: Coerced[SymbolName] type: Union[SymbolT, ts.DeferredType] # A003 namespace: dialect_ast_enums.Namespace = dialect_ast_enums.Namespace( dialect_ast_enums.Namespace.LOCAL @@ -79,7 +79,7 @@ class Expr(LocatedNode): class Name(Expr): - id: Coerced[SymbolRef] # shadowing a python builtin + id: Coerced[SymbolRef] class Constant(Expr): @@ -157,7 +157,7 @@ class Stmt(LocatedNode): ... class Starred(Expr): - id: Union[FieldSymbol, TupleSymbol, ScalarSymbol] # shadowing a python builtin + id: Union[FieldSymbol, TupleSymbol, ScalarSymbol] class Assign(Stmt): @@ -198,7 +198,7 @@ def _collect_common_symbols(cls: type[IfStmt], instance: IfStmt) -> None: class FunctionDefinition(LocatedNode, SymbolTableTrait): - id: Coerced[SymbolName] # shadowing a python builtin + id: Coerced[SymbolName] params: list[DataSymbol] body: BlockStmt closure_vars: list[Symbol] @@ -206,7 +206,7 @@ class FunctionDefinition(LocatedNode, SymbolTableTrait): class FieldOperator(LocatedNode, SymbolTableTrait): - id: Coerced[SymbolName] # shadowing a python builtin + id: Coerced[SymbolName] definition: FunctionDefinition type: Union[ts_ffront.FieldOperatorType, ts.DeferredType] = ts.DeferredType( constraint=ts_ffront.FieldOperatorType @@ -214,7 +214,7 @@ class FieldOperator(LocatedNode, SymbolTableTrait): class ScanOperator(LocatedNode, SymbolTableTrait): - id: Coerced[SymbolName] # shadowing a python builtin + id: Coerced[SymbolName] axis: Constant forward: Constant init: Constant diff --git a/src/gt4py/next/ffront/foast_passes/type_deduction.py b/src/gt4py/next/ffront/foast_passes/type_deduction.py index b4a6beae75..9bc004e7b8 100644 --- a/src/gt4py/next/ffront/foast_passes/type_deduction.py +++ b/src/gt4py/next/ffront/foast_passes/type_deduction.py @@ -319,7 +319,7 @@ def visit_ScanOperator(self, node: foast.ScanOperator, **kwargs) -> foast.ScanOp ) new_definition = self.visit(node.definition, **kwargs) new_def_type = new_definition.type - carry_type = list(new_def_type.pos_or_kw_args.values())[0] + carry_type = next(iter(new_def_type.pos_or_kw_args.values())) if new_init.type != new_def_type.returns: raise errors.DSLError( node.location, @@ -327,7 +327,7 @@ def visit_ScanOperator(self, node: foast.ScanOperator, **kwargs) -> foast.ScanOp f"expected '{new_def_type.returns}', got '{new_init.type}'.", ) elif new_init.type != carry_type: - carry_arg_name = list(new_def_type.pos_or_kw_args.keys())[0] + carry_arg_name = next(iter(new_def_type.pos_or_kw_args.keys())) raise errors.DSLError( node.location, f"Argument 'init' to scan operator '{node.id}' must have same type as '{carry_arg_name}' argument: " diff --git a/src/gt4py/next/ffront/foast_passes/utils.py b/src/gt4py/next/ffront/foast_passes/utils.py index 86d623ff4e..f87e2b3795 100644 --- a/src/gt4py/next/ffront/foast_passes/utils.py +++ b/src/gt4py/next/ffront/foast_passes/utils.py @@ -52,9 +52,9 @@ def compute_assign_indices( starred_upper = idx + 1 break if starred_lower is not None and starred_upper is not None: - return ( - list(range(0, starred_lower)) - + [(starred_lower, starred_upper)] - + list(range(starred_upper, num_elts)) - ) + return [ + *list(range(0, starred_lower)), + (starred_lower, starred_upper), + *list(range(starred_upper, num_elts)), + ] return list(range(0, num_elts)) # no starred target diff --git a/src/gt4py/next/ffront/foast_pretty_printer.py b/src/gt4py/next/ffront/foast_pretty_printer.py index 9275cdda95..9cd9304cdd 100644 --- a/src/gt4py/next/ffront/foast_pretty_printer.py +++ b/src/gt4py/next/ffront/foast_pretty_printer.py @@ -71,8 +71,6 @@ (foast.Compare, "greater_equal"): 7, (foast.Compare, "not_eq"): 7, (foast.Compare, "eq"): 7, - # Boolean NOT - (foast.UnaryOp, "not_"): 6, # Boolean AND (foast.BinOp, "and_"): 5, # Boolean OR diff --git a/src/gt4py/next/ffront/foast_to_itir.py b/src/gt4py/next/ffront/foast_to_itir.py index 627b67f004..6771e9ccc5 100644 --- a/src/gt4py/next/ffront/foast_to_itir.py +++ b/src/gt4py/next/ffront/foast_to_itir.py @@ -114,7 +114,7 @@ def visit_ScanOperator(self, node: foast.ScanOperator, **kwargs) -> itir.Functio # (this is the only place in the lowering were a variable is captured in a lifted lambda) lowering_utils.to_tuples_of_iterator( im.promote_to_const_iterator(func_definition.params[0].id), - [*node.type.definition.pos_or_kw_args.values()][0], + [*node.type.definition.pos_or_kw_args.values()][0], # noqa: RUF015 [unnecessary-iterable-allocation-for-first-element] ), )( # the function itself returns a tuple of iterators, deref element-wise diff --git a/src/gt4py/next/ffront/lowering_utils.py b/src/gt4py/next/ffront/lowering_utils.py index 61b957d5f7..1a1210d1bc 100644 --- a/src/gt4py/next/ffront/lowering_utils.py +++ b/src/gt4py/next/ffront/lowering_utils.py @@ -75,9 +75,9 @@ def to_iterator_of_tuples(expr: itir.Expr | str, arg_type: ts.TypeSpec): for type_ in type_info.primitive_constituents(arg_type) ] assert all( - isinstance(type_, ts.FieldType) and type_.dims == type_constituents[0].dims + isinstance(type_, ts.FieldType) and type_.dims == type_constituents[0].dims # type: ignore[attr-defined] # ensure by assert above for type_ in type_constituents - ) # type: ignore[attr-defined] # ensure by assert above + ) def fun(_, path): param_name = "__iot_el" diff --git a/src/gt4py/next/ffront/source_utils.py b/src/gt4py/next/ffront/source_utils.py index 57f4af8d7c..ba41d1281f 100644 --- a/src/gt4py/next/ffront/source_utils.py +++ b/src/gt4py/next/ffront/source_utils.py @@ -28,7 +28,7 @@ def get_closure_vars_from_function(function: Callable) -> dict[str, Any]: - (nonlocals, globals, builtins, unbound) = inspect.getclosurevars(function) # noqa: A001 + (nonlocals, globals, builtins, unbound) = inspect.getclosurevars(function) # noqa: A001 [builtin-variable-shadowing] return {**builtins, **globals, **nonlocals} # nonlocals override globals diff --git a/src/gt4py/next/ffront/type_info.py b/src/gt4py/next/ffront/type_info.py index 2072c4164a..3681cec189 100644 --- a/src/gt4py/next/ffront/type_info.py +++ b/src/gt4py/next/ffront/type_info.py @@ -180,9 +180,9 @@ def _as_field(dtype: ts.TypeSpec, path: tuple[int, ...]) -> ts.FieldType: assert isinstance(dtype, ts.ScalarType) try: el_type = reduce( - lambda type_, idx: type_.types[idx], + lambda type_, idx: type_.types[idx], # type: ignore[attr-defined] path, - arg, # type: ignore[attr-defined] + arg, ) return ts.FieldType(dims=type_info.extract_dims(el_type), dtype=dtype) except (IndexError, AttributeError): diff --git a/src/gt4py/next/iterator/builtins.py b/src/gt4py/next/iterator/builtins.py index 58dd5b8b41..7bbcd67337 100644 --- a/src/gt4py/next/iterator/builtins.py +++ b/src/gt4py/next/iterator/builtins.py @@ -184,7 +184,7 @@ def tuple_get(*args): @builtin_dispatch -def abs(*args): # noqa: A001 +def abs(*args): # noqa: A001 [builtin-variable-shadowing] raise BackendNotSelectedError() @@ -329,7 +329,7 @@ def power(*args): @builtin_dispatch -def int(*args): # noqa: A001 +def int(*args): # noqa: A001 [builtin-variable-shadowing] raise BackendNotSelectedError() @@ -344,7 +344,7 @@ def int64(*args): @builtin_dispatch -def float(*args): # noqa: A001 +def float(*args): # noqa: A001 [builtin-variable-shadowing] raise BackendNotSelectedError() @@ -359,7 +359,7 @@ def float64(*args): @builtin_dispatch -def bool(*args): # noqa: A001 +def bool(*args): # noqa: A001 [builtin-variable-shadowing] raise BackendNotSelectedError() diff --git a/src/gt4py/next/iterator/embedded.py b/src/gt4py/next/iterator/embedded.py index 409773de26..f9f1ba47e0 100644 --- a/src/gt4py/next/iterator/embedded.py +++ b/src/gt4py/next/iterator/embedded.py @@ -227,7 +227,7 @@ def __array__(self, dtype: Optional[npt.DTypeLike] = None) -> np.ndarray: return self.data.astype(dtype, copy=False) def _validate_kstart(self, args): - if wrong_kstarts := ( # noqa: F841 # wrong_kstarts looks unused + if wrong_kstarts := ( # noqa: F841 [unused-variable] set(arg.kstart for arg in args if isinstance(arg, Column)) - {self.kstart} ): raise ValueError( @@ -1013,7 +1013,7 @@ def _shift_field_indices( def np_as_located_field( *axes: common.Dimension, origin: Optional[dict[common.Dimension, int]] = None ) -> Callable[[np.ndarray], common.Field]: - warnings.warn("`np_as_located_field()` is deprecated, use `gtx.as_field()`", DeprecationWarning) + warnings.warn("`np_as_located_field()` is deprecated, use `gtx.as_field()`", DeprecationWarning) # noqa: B028 [no-explicit-stacklevel] origin = origin or {} diff --git a/src/gt4py/next/iterator/pretty_parser.py b/src/gt4py/next/iterator/pretty_parser.py index 2b1c8169fb..9dd96b076e 100644 --- a/src/gt4py/next/iterator/pretty_parser.py +++ b/src/gt4py/next/iterator/pretty_parser.py @@ -42,7 +42,7 @@ | "if" prec1 "then" prec1 "else" prec1 -> ifthenelse ?prec2: prec3 - | prec2 "∨" prec3 -> bool_or + | prec2 "∨" prec3 -> bool_or ?prec3: prec4 | prec3 "∧" prec4 -> bool_and @@ -85,7 +85,7 @@ %import common (CNAME, SIGNED_FLOAT, SIGNED_INT, WS) %ignore WS -""" +""" # noqa: RUF001 [ambiguous-unicode-character-string] @lark_visitors.v_args(inline=True) diff --git a/src/gt4py/next/iterator/pretty_printer.py b/src/gt4py/next/iterator/pretty_printer.py index 23f6620f60..710d5c6be9 100644 --- a/src/gt4py/next/iterator/pretty_printer.py +++ b/src/gt4py/next/iterator/pretty_printer.py @@ -31,13 +31,13 @@ BINARY_OPS: Final = { "plus": "+", "minus": "-", - "multiplies": "×", + "multiplies": "×", # noqa: RUF001 [ambiguous-unicode-character-string] "divides": "/", "eq": "==", "less": "<", "greater": ">", "and_": "∧", - "or_": "∨", + "or_": "∨", # noqa: RUF001 [ambiguous-unicode-character-string] } # replacements for builtin unary operations @@ -98,7 +98,7 @@ def impl(a: list[str], b: list[str]) -> list[str]: @staticmethod def _vmerge(*blocks: list[str]) -> list[str]: - return sum(blocks, []) + return [s for b in blocks for s in b] def _prec_parens(self, block: list[str], prec: int, op_prec: int) -> list[str]: if prec > op_prec: @@ -195,11 +195,11 @@ def visit_FunCall(self, node: ir.FunCall, *, prec: int) -> list[str]: res = self._hmerge(dim, [": ["], start, [", "], end, [")"]) return self._prec_parens(res, prec, PRECEDENCE["__call__"]) if fun_name == "cartesian_domain" and len(node.args) >= 1: - # cartesian_domain(x, y, ...) → c{ x × y × ... } + # cartesian_domain(x, y, ...) → c{ x × y × ... } # noqa: RUF003 [ambiguous-unicode-character-comment] args = self.visit(node.args, prec=PRECEDENCE["__call__"]) return self._hmerge(["c⟨ "], *self._hinterleave(args, ", "), [" ⟩"]) if fun_name == "unstructured_domain" and len(node.args) >= 1: - # unstructured_domain(x, y, ...) → u{ x × y × ... } + # unstructured_domain(x, y, ...) → u{ x × y × ... } # noqa: RUF003 [ambiguous-unicode-character-comment] args = self.visit(node.args, prec=PRECEDENCE["__call__"]) return self._hmerge(["u⟨ "], *self._hinterleave(args, ", "), [" ⟩"]) if fun_name == "if_" and len(node.args) == 3: diff --git a/src/gt4py/next/iterator/tracing.py b/src/gt4py/next/iterator/tracing.py index 1c9887cd22..82e6f20388 100644 --- a/src/gt4py/next/iterator/tracing.py +++ b/src/gt4py/next/iterator/tracing.py @@ -15,7 +15,7 @@ import dataclasses import inspect import typing -from typing import List +from typing import ClassVar, List from gt4py._core import definitions as core_defs from gt4py.eve import Node @@ -208,8 +208,8 @@ def __bool__(self): class TracerContext: - fundefs: List[FunctionDefinition] = [] - closures: List[StencilClosure] = [] + fundefs: ClassVar[List[FunctionDefinition]] = [] + closures: ClassVar[List[StencilClosure]] = [] @classmethod def add_fundef(cls, fun): diff --git a/src/gt4py/next/iterator/transforms/collapse_tuple.py b/src/gt4py/next/iterator/transforms/collapse_tuple.py index 84e4c5562d..2bc33e85e1 100644 --- a/src/gt4py/next/iterator/transforms/collapse_tuple.py +++ b/src/gt4py/next/iterator/transforms/collapse_tuple.py @@ -11,6 +11,8 @@ # distribution for a copy of the license or check . # # SPDX-License-Identifier: GPL-3.0-or-later +from __future__ import annotations + import dataclasses import enum import functools @@ -110,12 +112,12 @@ class Flag(enum.Flag): INLINE_TRIVIAL_LET = enum.auto() @classmethod - def all(self): # shadowing a python builtin + def all(self) -> CollapseTuple.Flag: return functools.reduce(operator.or_, self.__members__.values()) ignore_tuple_size: bool use_global_type_inference: bool - flags: Flag = Flag.all() + flags: Flag = Flag.all() # noqa: RUF009 [function-call-in-dataclass-default-argument] PRESERVED_ANNEX_ATTRS = ("type",) diff --git a/src/gt4py/next/iterator/transforms/global_tmps.py b/src/gt4py/next/iterator/transforms/global_tmps.py index d42ba82574..4feeca43e3 100644 --- a/src/gt4py/next/iterator/transforms/global_tmps.py +++ b/src/gt4py/next/iterator/transforms/global_tmps.py @@ -319,8 +319,9 @@ def always_extract_heuristics(_): stencil=stencil, output=im.ref(tmp_sym.id), inputs=[ - closure_param_arg_mapping[param.id] for param in lift_expr.args - ], # type: ignore[attr-defined] + closure_param_arg_mapping[param.id] # type: ignore[attr-defined] + for param in lift_expr.args + ], location=current_closure.location, ) ) diff --git a/src/gt4py/next/iterator/transforms/inline_lambdas.py b/src/gt4py/next/iterator/transforms/inline_lambdas.py index f6beec3571..0557f23872 100644 --- a/src/gt4py/next/iterator/transforms/inline_lambdas.py +++ b/src/gt4py/next/iterator/transforms/inline_lambdas.py @@ -41,8 +41,7 @@ def inline_lambda( # see todo above ref_counts = CountSymbolRefs.apply(node.fun.expr, [p.id for p in node.fun.params]) for i, param in enumerate(node.fun.params): - # TODO(tehrengruber): allow inlining more complicated zero-op expressions like - # ignore_shift(...)(it_sym) + # TODO(tehrengruber): allow inlining more complicated zero-op expressions like ignore_shift(...)(it_sym) if ref_counts[param.id] > 1 and not isinstance( node.args[i], (ir.SymRef, ir.Literal, ir.OffsetLiteral) ): @@ -80,10 +79,8 @@ def inline_lambda( # see todo above clashes = refs & syms expr = node.fun.expr if clashes: - # TODO(tehrengruber): find a better way of generating new symbols - # in `name_map` that don't collide with each other. E.g. this - # must still work: - # (lambda arg, arg_: (lambda arg_: ...)(arg))(a, b) + # TODO(tehrengruber): find a better way of generating new symbols in `name_map` that don't collide with each other. E.g. this must still work: + # (lambda arg, arg_: (lambda arg_: ...)(arg))(a, b) # noqa: ERA001 [commented-out-code] name_map: dict[ir.SymRef, str] = {} def new_name(name): diff --git a/src/gt4py/next/iterator/transforms/inline_lifts.py b/src/gt4py/next/iterator/transforms/inline_lifts.py index d6146d9fc8..73991a869c 100644 --- a/src/gt4py/next/iterator/transforms/inline_lifts.py +++ b/src/gt4py/next/iterator/transforms/inline_lifts.py @@ -14,8 +14,7 @@ import dataclasses import enum -from collections.abc import Callable -from typing import Optional +from typing import Callable, Optional import gt4py.eve as eve from gt4py.eve import NodeTranslator, traits @@ -141,7 +140,7 @@ class Flag(enum.IntEnum): #: when we see that it is not required. INLINE_LIFTED_ARGS = 16 - predicate: Callable[[ir.Expr, bool], bool] = lambda _1, _2: True + predicate: Callable[[ir.Expr, bool], bool] = lambda _1, _2: True # noqa: E731 [lambda-assignment] flags: int = ( Flag.PROPAGATE_SHIFT diff --git a/src/gt4py/next/iterator/transforms/simple_inline_heuristic.py b/src/gt4py/next/iterator/transforms/simple_inline_heuristic.py index 2737ec2b24..089235b5d7 100644 --- a/src/gt4py/next/iterator/transforms/simple_inline_heuristic.py +++ b/src/gt4py/next/iterator/transforms/simple_inline_heuristic.py @@ -29,20 +29,20 @@ def is_eligible_for_inlining(node: ir.FunCall, is_scan_pass_context: bool) -> bo `↑(scan(λ(acc, args...) → acc + ·↑(f)(args...)))(...)` Follows the simple rules: - - Don’t inline scans (as there is no efficient way to inline them, also required by some + - Do not inline scans (as there is no efficient way to inline them, also required by some backends, e.g. gtfn) - - Don’t inline the first lifted function call within a scan (otherwise, all stencils would get + - Do not inline the first lifted function call within a scan (otherwise, all stencils would get inlined into the scans, leading to reduced parallelism/scan-only computation) """ assert _is_lift(node) assert isinstance(node.fun, ir.FunCall) # for mypy (stencil,) = node.fun.args - # Don’t inline scans, i.e. exclude `↑(scan(...))(...)` + # Don't inline scans, i.e. exclude `↑(scan(...))(...)` if isinstance(stencil, ir.FunCall) and stencil.fun == ir.SymRef(id="scan"): return False - # Don’t inline the first lifted function call within a scan, e.g. if the node given here + # Don't inline the first lifted function call within a scan, e.g. if the node given here # is `↑(f)(args...)` and appears in a scan pass `scan(λ(acc, args...) → acc + ·↑(f)(args...))` # it should not be inlined. return not is_scan_pass_context diff --git a/src/gt4py/next/iterator/transforms/unroll_reduce.py b/src/gt4py/next/iterator/transforms/unroll_reduce.py index 3c878b2b00..1e0977e68e 100644 --- a/src/gt4py/next/iterator/transforms/unroll_reduce.py +++ b/src/gt4py/next/iterator/transforms/unroll_reduce.py @@ -153,7 +153,7 @@ def _visit_reduce(self, node: itir.FunCall, **kwargs) -> itir.Expr: fun, init = node.fun.args elems = [_make_list_get(offset, arg) for arg in node.args] - step_fun: itir.Expr = itir.FunCall(fun=fun, args=[acc] + elems) + step_fun: itir.Expr = itir.FunCall(fun=fun, args=[acc, *elems]) if has_skip_values: check_arg = next(_get_neighbors_args(node.args)) offset_tag, it = check_arg.args diff --git a/src/gt4py/next/iterator/type_inference.py b/src/gt4py/next/iterator/type_inference.py index a189538ca1..6c4a87e6c0 100644 --- a/src/gt4py/next/iterator/type_inference.py +++ b/src/gt4py/next/iterator/type_inference.py @@ -387,7 +387,7 @@ def _default_constraints(): DOMAIN_DTYPE = Primitive(name="domain") OFFSET_TAG_DTYPE = Primitive(name="offset_tag") -# Some helpers to define the builtins’ types +# Some helpers to define the builtins' types T0 = TypeVar.fresh() T1 = TypeVar.fresh() T2 = TypeVar.fresh() @@ -558,16 +558,16 @@ def _infer_shift_location_types(shift_args, offset_provider, constraints): current_loc_out = current_loc_in for arg in shift_args: if not isinstance(arg, ir.OffsetLiteral): - # probably some dynamically computed offset, thus we assume it’s a number not an axis and just ignore it (see comment below) + # probably some dynamically computed offset, thus we assume it's a number not an axis and just ignore it (see comment below) continue offset = arg.value if isinstance(offset, int): - continue # ignore ‘application’ of (partial) shifts + continue # ignore 'application' of (partial) shifts else: assert isinstance(offset, str) axis = offset_provider[offset] if isinstance(axis, gtx.Dimension): - continue # Cartesian shifts don’t change the location type + continue # Cartesian shifts don't change the location type elif isinstance(axis, Connectivity): assert ( axis.origin_axis.kind @@ -955,14 +955,14 @@ def _save_types_to_annex(node: ir.Node, types: dict[int, Type]) -> None: for child_node in node.pre_walk_values().if_isinstance(*TYPED_IR_NODES): try: child_node.annex.type = types[id(child_node)] - except KeyError: + except KeyError as ex: if not ( isinstance(child_node, ir.SymRef) and child_node.id in ir.GRAMMAR_BUILTINS | ir.TYPEBUILTINS ): raise AssertionError( f"Expected a type to be inferred for node '{child_node}', but none was found." - ) + ) from ex def infer_all( diff --git a/src/gt4py/next/otf/binding/nanobind.py b/src/gt4py/next/otf/binding/nanobind.py index 42988ad8db..05e072b0d6 100644 --- a/src/gt4py/next/otf/binding/nanobind.py +++ b/src/gt4py/next/otf/binding/nanobind.py @@ -40,8 +40,8 @@ class BufferSID(Expr): source_buffer: str dimensions: Sequence[DimensionType] scalar_type: ts.ScalarType - # strides_kind: int # TODO(havogt): implement strides_kind once we have the "frozen stencil" mechanism - # unit_stride_dim: int # TODO(havogt): we can fix the dimension with unity stride once we have the "frozen stencil" mechanism + # TODO(havogt): implement `strides_kind: int` once we have the "frozen stencil" mechanism + # TODO(havogt): we can fix the dimension with `unit_stride_dim: int` once we have the "frozen stencil" mechanism class CompositeSID(Expr): diff --git a/src/gt4py/next/otf/compilation/importer.py b/src/gt4py/next/otf/compilation/importer.py index 6301ba33b0..70655390ba 100644 --- a/src/gt4py/next/otf/compilation/importer.py +++ b/src/gt4py/next/otf/compilation/importer.py @@ -29,7 +29,7 @@ def import_from_path(module_file: pathlib.Path) -> ModuleType: try: module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) - except ImportError: - raise ModuleNotFoundError(error_msg) + except ImportError as ex: + raise ModuleNotFoundError(error_msg) from ex return module diff --git a/src/gt4py/next/program_processors/codegens/gtfn/codegen.py b/src/gt4py/next/program_processors/codegens/gtfn/codegen.py index 23165854de..6a020f1102 100644 --- a/src/gt4py/next/program_processors/codegens/gtfn/codegen.py +++ b/src/gt4py/next/program_processors/codegens/gtfn/codegen.py @@ -12,7 +12,7 @@ # # SPDX-License-Identifier: GPL-3.0-or-later -from typing import Any, Collection, Union +from typing import Any, Collection, Final, Union from gt4py.eve import codegen from gt4py.eve.codegen import FormatTemplate as as_fmt, MakoTemplate as as_mako @@ -22,12 +22,12 @@ class GTFNCodegen(codegen.TemplatedGenerator): - _grid_type_str = { + _grid_type_str: Final = { common.GridType.CARTESIAN: "cartesian", common.GridType.UNSTRUCTURED: "unstructured", } - _builtins_mapping = { + _builtins_mapping: Final = { "abs": "std::abs", "sin": "std::sin", "cos": "std::cos", diff --git a/src/gt4py/next/program_processors/codegens/gtfn/gtfn_ir_to_gtfn_im_ir.py b/src/gt4py/next/program_processors/codegens/gtfn/gtfn_ir_to_gtfn_im_ir.py index 361cc3c9d6..49cf16bf4c 100644 --- a/src/gt4py/next/program_processors/codegens/gtfn/gtfn_ir_to_gtfn_im_ir.py +++ b/src/gt4py/next/program_processors/codegens/gtfn/gtfn_ir_to_gtfn_im_ir.py @@ -126,7 +126,7 @@ def _make_dense_acess( fun=gtfn_ir_common.SymRef(id="deref"), args=[ gtfn_ir.FunCall( - fun=gtfn_ir_common.SymRef(id="shift"), args=shift_call.args + [nbh_iter] + fun=gtfn_ir_common.SymRef(id="shift"), args=[*shift_call.args, nbh_iter] ) ], ) @@ -228,7 +228,7 @@ def _expand_symref( ] rhs = gtfn_ir.FunCall( fun=fun, - args=[gtfn_ir_common.SymRef(id=red_idx)] + plugged_in_args, + args=[gtfn_ir_common.SymRef(id=red_idx), *plugged_in_args], ) self.imp_list_ir.append(AssignStmt(lhs=gtfn_ir_common.SymRef(id=red_idx), rhs=rhs)) @@ -339,7 +339,7 @@ def visit_FunctionDefinition( return ImperativeFunctionDefinition( id=node.id, params=node.params, - fun=self.imp_list_ir + [ReturnStmt(ret=ret)], + fun=[*self.imp_list_ir, ReturnStmt(ret=ret)], ) def visit_ScanPassDefinition( diff --git a/src/gt4py/next/program_processors/codegens/gtfn/gtfn_module.py b/src/gt4py/next/program_processors/codegens/gtfn/gtfn_module.py index 4c3af5129b..50d71cb94a 100644 --- a/src/gt4py/next/program_processors/codegens/gtfn/gtfn_module.py +++ b/src/gt4py/next/program_processors/codegens/gtfn/gtfn_module.py @@ -193,7 +193,8 @@ def _preprocess_program( if runtime_lift_mode and runtime_lift_mode != self.lift_mode: warnings.warn( f"GTFN Backend was configured for LiftMode `{self.lift_mode!s}`, but " - f"overriden to be {runtime_lift_mode!s} at runtime." + f"overriden to be {runtime_lift_mode!s} at runtime.", + stacklevel=2, ) if not self.enable_itir_transforms: diff --git a/src/gt4py/next/program_processors/codegens/gtfn/itir_to_gtfn_ir.py b/src/gt4py/next/program_processors/codegens/gtfn/itir_to_gtfn_ir.py index 98eff62d60..7fa43e78c9 100644 --- a/src/gt4py/next/program_processors/codegens/gtfn/itir_to_gtfn_ir.py +++ b/src/gt4py/next/program_processors/codegens/gtfn/itir_to_gtfn_ir.py @@ -472,7 +472,7 @@ def visit_StencilClosure( return ScanExecution( backend=backend, scans=[scan], - args=[self._visit_output_argument(node.output)] + self.visit(node.inputs), + args=[self._visit_output_argument(node.output), *self.visit(node.inputs)], axis=SymRef(id=column_axis.value), ) return StencilExecution( diff --git a/src/gt4py/next/program_processors/runners/dace_iterator/__init__.py b/src/gt4py/next/program_processors/runners/dace_iterator/__init__.py index 75b4b3eda8..9fe19ee2de 100644 --- a/src/gt4py/next/program_processors/runners/dace_iterator/__init__.py +++ b/src/gt4py/next/program_processors/runners/dace_iterator/__init__.py @@ -118,7 +118,8 @@ def _ensure_is_on_device( if device == dace.dtypes.DeviceType.GPU: if not isinstance(connectivity_arg, cp.ndarray): warnings.warn( - "Copying connectivity to device. For performance make sure connectivity is provided on device." + "Copying connectivity to device. For performance make sure connectivity is provided on device.", + stacklevel=2, ) return cp.asarray(connectivity_arg) return connectivity_arg @@ -300,11 +301,10 @@ def build_sdfg_from_itir( if not nested_sdfg.debuginfo: _, frameinfo = ( warnings.warn( - f"{nested_sdfg.label} does not have debuginfo. Consider adding them in the corresponding nested sdfg." - ), - getframeinfo( - currentframe() # type: ignore + f"{nested_sdfg.label} does not have debuginfo. Consider adding them in the corresponding nested sdfg.", + stacklevel=2, ), + getframeinfo(currentframe()), # type: ignore[arg-type] ) nested_sdfg.debuginfo = dace.dtypes.DebugInfo( start_line=frameinfo.lineno, diff --git a/src/gt4py/next/program_processors/runners/dace_iterator/itir_to_sdfg.py b/src/gt4py/next/program_processors/runners/dace_iterator/itir_to_sdfg.py index ed71522da1..726966e0c9 100644 --- a/src/gt4py/next/program_processors/runners/dace_iterator/itir_to_sdfg.py +++ b/src/gt4py/next/program_processors/runners/dace_iterator/itir_to_sdfg.py @@ -266,7 +266,9 @@ def add_storage_for_temporaries( of the array. """ if not (isinstance(begin, SymbolExpr) and begin.value == "0"): - warnings.warn(f"Domain start offset for temporary {tmp_name} is ignored.") + warnings.warn( + f"Domain start offset for temporary {tmp_name} is ignored.", stacklevel=2 + ) tmp_symbols[str(shape_sym)] = end.value return tmp_symbols diff --git a/src/gt4py/next/program_processors/runners/dace_iterator/utility.py b/src/gt4py/next/program_processors/runners/dace_iterator/utility.py index 567b8b9356..d5ba62c775 100644 --- a/src/gt4py/next/program_processors/runners/dace_iterator/utility.py +++ b/src/gt4py/next/program_processors/runners/dace_iterator/utility.py @@ -54,8 +54,8 @@ def as_dace_type(type_: ts.ScalarType): def as_scalar_type(typestr: str) -> ts.ScalarType: try: kind = getattr(ts.ScalarKind, typestr.upper()) - except AttributeError: - raise ValueError(f"Data type {typestr} not supported.") + except AttributeError as ex: + raise ValueError(f"Data type {typestr} not supported.") from ex return ts.ScalarType(kind) @@ -181,7 +181,8 @@ def add_mapped_nested_sdfg( def unique_name(prefix): unique_id = getattr(unique_name, "_unique_id", 0) # static variable - setattr(unique_name, "_unique_id", unique_id + 1) # noqa: B010 # static variable + setattr(unique_name, "_unique_id", unique_id + 1) # noqa: B010 [set-attr-with-constant] + return f"{prefix}_{unique_id}" diff --git a/src/gt4py/next/program_processors/runners/gtfn.py b/src/gt4py/next/program_processors/runners/gtfn.py index e490e83ddb..13e3308a0f 100644 --- a/src/gt4py/next/program_processors/runners/gtfn.py +++ b/src/gt4py/next/program_processors/runners/gtfn.py @@ -70,7 +70,8 @@ def _ensure_is_on_device( if not isinstance(connectivity_arg, cp.ndarray): warnings.warn( - "Copying connectivity to device. For performance make sure connectivity is provided on device." + "Copying connectivity to device. For performance make sure connectivity is provided on device.", + stacklevel=2, ) return cp.asarray(connectivity_arg) return connectivity_arg diff --git a/src/gt4py/next/type_inference.py b/src/gt4py/next/type_inference.py index 10ae524451..76ba8a61f2 100644 --- a/src/gt4py/next/type_inference.py +++ b/src/gt4py/next/type_inference.py @@ -197,7 +197,7 @@ def _update_node(self, node: Type, field: str, replacement: Type) -> None: # Pop the node out of the parents dict as its hash could change after modification popped = self._parents.pop(node, None) - # Update the node’s field + # Update the node's field setattr(node, field, replacement) # Register `node` to be the new parent of `replacement` diff --git a/src/gt4py/storage/__init__.py b/src/gt4py/storage/__init__.py index d23d880c58..bc1aa1530b 100644 --- a/src/gt4py/storage/__init__.py +++ b/src/gt4py/storage/__init__.py @@ -12,8 +12,6 @@ # # SPDX-License-Identifier: GPL-3.0-or-later -# flake8: noqa: F401 - """GridTools storages utilities.""" from . import cartesian diff --git a/src/gt4py/storage/allocators.py b/src/gt4py/storage/allocators.py index 0482ec1e65..1c9525c7b1 100644 --- a/src/gt4py/storage/allocators.py +++ b/src/gt4py/storage/allocators.py @@ -49,7 +49,7 @@ _NDBuffer: TypeAlias = Union[ - # xtyping.Buffer, # TODO: add once we update typing_extensions + # TODO: add `xtyping.Buffer` once we update typing_extensions xtyping.ArrayInterface, xtyping.CUDAArrayInterface, xtyping.DLPackBuffer, diff --git a/src/gt4py/storage/cartesian/layout.py b/src/gt4py/storage/cartesian/layout.py index 65b1967448..4ec689c66b 100644 --- a/src/gt4py/storage/cartesian/layout.py +++ b/src/gt4py/storage/cartesian/layout.py @@ -79,9 +79,9 @@ def layout_maker(dimensions: Tuple[str, ...]) -> Tuple[int, ...]: mask = [dim in dimensions for dim in "IJK"] mask += [True] * (len(dimensions) - sum(mask)) ranks = [] - for m, l in zip(mask, base_layout): + for m, bl in zip(mask, base_layout): if m: - ranks.append(l) + ranks.append(bl) if len(mask) > 3: if base_layout[2] == 2: ranks.extend(3 + c for c in range(len(mask) - 3)) diff --git a/tests/cartesian_tests/integration_tests/feature_tests/test_stencil_object.py b/tests/cartesian_tests/integration_tests/feature_tests/test_stencil_object.py index e8fd9a8643..a1539e5fba 100644 --- a/tests/cartesian_tests/integration_tests/feature_tests/test_stencil_object.py +++ b/tests/cartesian_tests/integration_tests/feature_tests/test_stencil_object.py @@ -33,7 +33,7 @@ def test_stencil_object_cache(backend: str): @typing.no_type_check def stencil(in_field: Field[float], out_field: Field[float], *, offset: float): with computation(PARALLEL), interval(...): - out_field = ( # noqa: F841 # local variable 'out_field' is assigned to but never used + out_field = ( # noqa: F841 [unused-variable] in_field + offset ) diff --git a/tests/cartesian_tests/integration_tests/multi_feature_tests/test_suites.py b/tests/cartesian_tests/integration_tests/multi_feature_tests/test_suites.py index 10019343ab..eb94342495 100644 --- a/tests/cartesian_tests/integration_tests/multi_feature_tests/test_suites.py +++ b/tests/cartesian_tests/integration_tests/multi_feature_tests/test_suites.py @@ -63,7 +63,7 @@ class TestCopy(gt_testing.StencilTestSuite): def definition(field_a, field_b): with computation(PARALLEL), interval(...): - field_b = field_a # noqa: F841 # Local name is assigned to but never used + field_b = field_a # noqa: F841 [unused-variable] def validation(field_a, field_b, domain=None, origin=None): field_b[...] = field_a @@ -111,7 +111,7 @@ def definition(field_a): field_a = SCALE_FACTOR * field_a[0, 0, 0] def validation(field_a, domain, origin, **kwargs): - field_a[...] = SCALE_FACTOR * field_a # noqa: F821 # Undefined name + field_a[...] = SCALE_FACTOR * field_a # noqa: F821 [undefined-name] # ---- Parametric scale stencil ----- @@ -166,15 +166,14 @@ def definition(field_a, field_b, field_c, field_out, *, weight, alpha_factor): else: factor = 1.0 field_out = ( - factor - * field_a[0, 0, 0] # noqa: F841 # Local name is assigned to but never used + factor * field_a[0, 0, 0] # noqa: F841 [unused-variable] - (1 - factor) * (field_b[0, 0, 0] - weight * field_c[0, 0, 0]) ) def validation( field_a, field_b, field_c, field_out, *, weight, alpha_factor, domain, origin, **kwargs ): - if USE_ALPHA: # noqa: F821 # Undefined name + if USE_ALPHA: # noqa: F821 [undefined-name] factor = alpha_factor else: factor = 1.0 @@ -198,10 +197,10 @@ class TestHeatEquation_FTCS_3D(gt_testing.StencilTestSuite): def definition(u, v, u_new, v_new, *, ru, rv): with computation(PARALLEL), interval(...): - u_new = u[0, 0, 0] + ru * ( # noqa: F841 # Local name is assigned to but never used + u_new = u[0, 0, 0] + ru * ( # noqa: F841 [unused-variable] u[1, 0, 0] - 2 * u[0, 0, 0] + u[-1, 0, 0] ) - v_new = v[0, 0, 0] + rv * ( # noqa: F841 # Local name is assigned to but never used + v_new = v[0, 0, 0] + rv * ( # noqa: F841 [unused-variable] v[0, 1, 0] - 2 * v[0, 0, 0] + v[0, -1, 0] ) @@ -228,7 +227,7 @@ def definition(u, diffusion, *, weight): flux_i = laplacian[1, 0, 0] - laplacian[0, 0, 0] flux_j = laplacian[0, 1, 0] - laplacian[0, 0, 0] diffusion = ( - u[0, 0, 0] # noqa: F841 # Local name is assigned to but never used + u[0, 0, 0] # noqa: F841 [unused-variable] - weight * (flux_i[0, 0, 0] - flux_i[-1, 0, 0] + flux_j[0, 0, 0] - flux_j[0, -1, 0]) ) @@ -294,7 +293,7 @@ def definition(u, diffusion, *, weight): laplacian = lap_op(u=u) flux_i, flux_j = fwd_diff(field=laplacian) diffusion = ( - u[0, 0, 0] # noqa: F841 # Local name is assigned to but never used + u[0, 0, 0] # noqa: F841 [unused-variable] - weight * (flux_i[0, 0, 0] - flux_i[-1, 0, 0] + flux_j[0, 0, 0] - flux_j[0, -1, 0]) ) @@ -335,7 +334,7 @@ def definition(u, diffusion, *, weight): else: flux_i, flux_j = fwd_diff_op_xy(field=laplacian) diffusion = ( - u[0, 0, 0] # noqa: F841 # Local name is assigned to but never used + u[0, 0, 0] # noqa: F841 [unused-variable] - weight * (flux_i[0, 0, 0] - flux_i[-1, 0, 0] + flux_j[0, 0, 0] - flux_j[0, -1, 0]) ) @@ -363,7 +362,7 @@ def definition(outfield): if True: outfield = 1 else: - outfield = 2 # noqa: F841 # Local name is assigned to but never used + outfield = 2 # noqa: F841 [unused-variable] def validation(outfield, *, domain, origin, **kwargs): outfield[...] = 1 @@ -434,12 +433,12 @@ def definition(field_a, field_b, field_c, *, factor): if field_a < 0: field_b = -field_a else: - field_b = field_a # noqa: F841 # Local name is assigned to but never used + field_b = field_a # noqa: F841 [unused-variable] else: if field_a < 0: field_c = -field_a else: - field_c = field_a # noqa: F841 # Local name is assigned to but never used + field_c = field_a # noqa: F841 [unused-variable] field_a = add_one(field_a) @@ -462,7 +461,7 @@ class TestTernaryOp(gt_testing.StencilTestSuite): def definition(infield, outfield): with computation(PARALLEL), interval(...): - outfield = ( # noqa: F841 # Local name is assigned to but never used + outfield = ( # noqa: F841 [unused-variable] infield if infield > 0.0 else -infield[0, 1, 0] ) @@ -488,7 +487,7 @@ def definition(outfield, *, a, b, c): if a > 0 and b > 0 and c > 0: outfield = 1 else: - outfield = 0 # noqa: F841 # Local name is assigned to but never used + outfield = 0 # noqa: F841 [unused-variable] def validation(outfield, *, a, b, c, domain, origin, **kwargs): outfield[...] = 1 if a > 0 and b > 0 and c > 0 else 0 @@ -510,7 +509,7 @@ def definition(outfield, *, a, b, c): if a > 0 or b > 0 or c > 0: outfield = 1 else: - outfield = 0 # noqa: F841 # Local name is assigned to but never used + outfield = 0 # noqa: F841 [unused-variable] def validation(outfield, *, a, b, c, domain, origin, **kwargs): outfield[...] = 1 if a > 0 or b > 0 or c > 0 else 0 @@ -533,7 +532,7 @@ class TestOptionalField(gt_testing.StencilTestSuite): def validation(in_field, out_field, dyn_tend, phys_tend=None, *, dt, domain, origin, **kwargs): out_field[...] = in_field + dt * dyn_tend - if PHYS_TEND: # noqa: F821 # Undefined name + if PHYS_TEND: # noqa: F821 [undefined-name] out_field += dt * phys_tend @@ -581,9 +580,9 @@ def validation( ): out_a[...] = in_a + dt * dyn_tend_a out_b[...] = in_b + dt * dyn_tend_b - if PHYS_TEND_A: # noqa: F821 # Undefined name + if PHYS_TEND_A: # noqa: F821 [undefined-name] out_a += dt * phys_tend_a - if PHYS_TEND_B: # noqa: F821 # Undefined name + if PHYS_TEND_B: # noqa: F821 [undefined-name] out_b += dt * phys_tend_b @@ -702,7 +701,7 @@ class TestReadOutsideKInterval1(gt_testing.StencilTestSuite): def definition(field_in, field_out): with computation(PARALLEL), interval(...): - field_out = ( # noqa: F841 # Local name is assigned to but never used + field_out = ( # noqa: F841 [unused-variable] field_in[0, 0, -1] + field_in[0, 0, 1] ) @@ -728,7 +727,7 @@ class TestReadOutsideKInterval2(gt_testing.StencilTestSuite): def definition(field_in, field_out): with computation(PARALLEL), interval(-1, None): - field_out = field_in[0, 0, 1] # noqa: F841 # Local name is assigned to but never used + field_out = field_in[0, 0, 1] # noqa: F841 [unused-variable] def validation(field_in, field_out, *, domain, origin): field_out[:, :, -1] = field_in[:, :, domain[2]] @@ -752,7 +751,7 @@ class TestReadOutsideKInterval3(gt_testing.StencilTestSuite): def definition(field_in, field_out): with computation(PARALLEL), interval(0, 1): - field_out = field_in[0, 0, -1] # noqa: F841 # Local name is assigned to but never used + field_out = field_in[0, 0, -1] # noqa: F841 [unused-variable] def validation(field_in, field_out, *, domain, origin): field_out[:, :, 0] = field_in[:, :, 0] @@ -797,7 +796,7 @@ class TestVariableKRead(gt_testing.StencilTestSuite): def definition(field_in, field_out, index): with computation(PARALLEL), interval(1, None): - field_out = field_in[0, 0, index] # noqa: F841 # Local name is assigned to but never used + field_out = field_in[0, 0, index] # noqa: F841 [unused-variable] def validation(field_in, field_out, index, *, domain, origin): field_out[:, :, 1:] = field_in[:, :, (np.arange(field_in.shape[-1]) + index)[1:]] @@ -824,7 +823,7 @@ class TestVariableKAndReadOutside(gt_testing.StencilTestSuite): def definition(field_in, field_out, index): with computation(PARALLEL), interval(1, None): field_out[0, 0, 0] = ( - field_in[0, 0, index] # noqa: F841 # Local name is assigned to but never used + field_in[0, 0, index] # noqa: F841 [unused-variable] + field_in[0, 0, -2] ) @@ -879,15 +878,15 @@ class TestHorizontalRegions(gt_testing.StencilTestSuite): def definition(field_in, field_out): with computation(PARALLEL), interval(...): - field_out = ( # noqa: F841 # local variable 'field_out' is assigned to but never used + field_out = ( # noqa: F841 [unused-variable] field_in ) with horizontal(region[I[0], :], region[I[-1], :]): - field_out = ( # noqa: F841 # local variable 'field_out' is assigned to but never used + field_out = ( # noqa: F841 [unused-variable] field_in + 1.0 ) with horizontal(region[:, J[0]], region[:, J[-1]]): - field_out = ( # noqa: F841 # local variable 'field_out' is assigned to but never used + field_out = ( # noqa: F841 [unused-variable] field_in - 1.0 ) @@ -918,11 +917,11 @@ class TestHorizontalRegionsCorners(gt_testing.StencilTestSuite): def definition(field_in, field_out): with computation(PARALLEL), interval(...): with horizontal(region[I[0] : I[2], J[0] : J[2]], region[I[-3] : I[-1], J[-3] : J[-1]]): - field_out = ( # noqa: F841 # local variable 'field_out' is assigned to but never used + field_out = ( # noqa: F841 [unused-variable] field_in + 1.0 ) with horizontal(region[I[0] : I[2], J[-3] : J[-1]], region[I[-3] : I[-1], J[0] : J[2]]): - field_out = ( # noqa: F841 # local variable 'field_out' is assigned to but never used + field_out = ( # noqa: F841 [unused-variable] field_in - 1.0 ) @@ -954,11 +953,11 @@ def definition(field_in, field_out): tmp[0, 0, 0][1, 0] = field_in[0, 0, 1] tmp[0, 0, 0][0, 1] = -1.0 tmp[0, 0, 0][1, 1] = -1.0 - field_out = ( # noqa: F841 # local variable 'field_out' is assigned to but never used + field_out = ( # noqa: F841 [unused-variable] tmp[0, 0, 0][0, 0] + tmp[0, 0, 0][1, 0] ) with interval(-1, None): - field_out = ( # noqa: F841 # local variable 'field_out' is assigned to but never used + field_out = ( # noqa: F841 [unused-variable] 0 ) @@ -982,7 +981,7 @@ class TestVectorGenAssignment(gt_testing.StencilTestSuite): def definition(field_in, field_out): with computation(PARALLEL), interval(...): - field_out = 2 * field_in # noqa: F841 # field_out is assigned to but never used + field_out = 2 * field_in # noqa: F841 [unused-variable] def validation(field_in, field_out, *, domain, origin): field_out[...] = 2 * field_in @@ -1006,7 +1005,7 @@ class TestMatrixAssignment(gt_testing.StencilTestSuite): def definition(field_in, field_out): with computation(PARALLEL), interval(...): - field_out = field_in # noqa: F841 # field_out is assigned to but never used + field_out = field_in # noqa: F841 [unused-variable] def validation(field_in, field_out, *, domain, origin): field_out[...] = field_in @@ -1030,7 +1029,7 @@ class TestVectorVectorOp(gt_testing.StencilTestSuite): def definition(field_1, field_2, field_out): with computation(PARALLEL), interval(...): - field_out = field_1 + field_2 # noqa: F841 # field_out is assigned to but never used + field_out = field_1 + field_2 # noqa: F841 [unused-variable] def validation(field_1, field_2, field_out, *, domain, origin): field_out[...] = field_1 + field_2 @@ -1054,7 +1053,7 @@ class TestCombinedVectorScalarOp(gt_testing.StencilTestSuite): def definition(field_1, field_2, field_out): with computation(PARALLEL), interval(...): - field_out = 3 * ( # noqa: F841 # field_out is assigned to but never used + field_out = 3 * ( # noqa: F841 [unused-variable] field_1 + field_2 * field_2 ) @@ -1080,7 +1079,7 @@ def definition(field_in, field_out): with computation(PARALLEL), interval(...): tmp[0, 0, 0][0] = 2 tmp[0, 0, 0][1] = 3 - field_out = tmp * field_in # noqa: F841 # field_out is assigned to but never used + field_out = tmp * field_in # noqa: F841 [unused-variable] def validation(field_in, field_out, *, domain, origin): field_out[:, :, :, 0] = 2 * field_in[:, :, :, 0] diff --git a/tests/cartesian_tests/unit_tests/frontend_tests/test_defir_to_gtir.py b/tests/cartesian_tests/unit_tests/frontend_tests/test_defir_to_gtir.py index 934597f4e5..0e4e90b9b3 100644 --- a/tests/cartesian_tests/unit_tests/frontend_tests/test_defir_to_gtir.py +++ b/tests/cartesian_tests/unit_tests/frontend_tests/test_defir_to_gtir.py @@ -28,7 +28,7 @@ ) from gt4py.cartesian.gtc import common, gtir -from cartesian_tests.unit_tests.frontend_tests.defir_to_gtir_definition_setup import ( # noqa: F401 +from cartesian_tests.unit_tests.frontend_tests.defir_to_gtir_definition_setup import ( # noqa: F401 [unused-import] BlockStmt, IterationOrder, TAssign, @@ -46,7 +46,7 @@ def defir_to_gtir(): def test_stencil_definition( defir_to_gtir, - ijk_domain, # noqa: F811 [redefinition, reason: fixture] + ijk_domain, # [redefinition, reason: fixture] ): stencil_definition = ( TDefinition(name="definition", domain=ijk_domain, fields=["a", "b"]) diff --git a/tests/cartesian_tests/unit_tests/test_gtc/test_definitive_assignment_analysis.py b/tests/cartesian_tests/unit_tests/test_gtc/test_definitive_assignment_analysis.py index 08e01c853e..1d259c0742 100644 --- a/tests/cartesian_tests/unit_tests/test_gtc/test_definitive_assignment_analysis.py +++ b/tests/cartesian_tests/unit_tests/test_gtc/test_definitive_assignment_analysis.py @@ -11,7 +11,6 @@ # distribution for a copy of the license or check . # # SPDX-License-Identifier: GPL-3.0-or-later -# flake8: noqa: F841 import typing from typing import Callable, List, Tuple, TypedDict diff --git a/tests/cartesian_tests/unit_tests/test_gtc/test_passes/test_min_k_interval.py b/tests/cartesian_tests/unit_tests/test_gtc/test_passes/test_min_k_interval.py index dd39c9deb0..4e67f97a3d 100644 --- a/tests/cartesian_tests/unit_tests/test_gtc/test_passes/test_min_k_interval.py +++ b/tests/cartesian_tests/unit_tests/test_gtc/test_passes/test_min_k_interval.py @@ -11,7 +11,6 @@ # distribution for a copy of the license or check . # # SPDX-License-Identifier: GPL-3.0-or-later -# flake8: noqa: F841 import typing from typing import Callable, List, Tuple, TypedDict diff --git a/tests/eve_tests/unit_tests/test_codegen.py b/tests/eve_tests/unit_tests/test_codegen.py index 7e7ec2244e..153d5bfa0d 100644 --- a/tests/eve_tests/unit_tests/test_codegen.py +++ b/tests/eve_tests/unit_tests/test_codegen.py @@ -19,11 +19,11 @@ from gt4py import eve from gt4py.eve import codegen -from .test_utils import name_with_cases # noqa: F401 +from .test_utils import name_with_cases # noqa: F401 [unused-import] # -- Name tests -- -def test_name(name_with_cases): # noqa: F811 # pytest fixture not detected +def test_name(name_with_cases): name = codegen.Name(name_with_cases.pop("words")) for case, cased_string in name_with_cases.items(): assert name.as_case(case) == cased_string diff --git a/tests/eve_tests/unit_tests/test_datamodels.py b/tests/eve_tests/unit_tests/test_datamodels.py index 0abb893dd4..bd1814b2f1 100644 --- a/tests/eve_tests/unit_tests/test_datamodels.py +++ b/tests/eve_tests/unit_tests/test_datamodels.py @@ -18,7 +18,7 @@ import numbers import types import typing -from typing import Set # noqa: F401 # imported but unused (used in exec() context) +from typing import Set # noqa: F401 [unused-import] used in exec() context from typing import ( Any, Callable, diff --git a/tests/eve_tests/unit_tests/test_utils.py b/tests/eve_tests/unit_tests/test_utils.py index 99513ba175..a6fb5028d2 100644 --- a/tests/eve_tests/unit_tests/test_utils.py +++ b/tests/eve_tests/unit_tests/test_utils.py @@ -71,7 +71,7 @@ class MyVirtualSubclassB: pass @eve.utils.register_subclasses(MyVirtualSubclassA, MyVirtualSubclassB) - class MyBaseClass(abc.ABC): # noqa: B024 + class MyBaseClass(abc.ABC): pass assert issubclass(MyVirtualSubclassA, MyBaseClass) and issubclass( diff --git a/tests/next_tests/integration_tests/cases.py b/tests/next_tests/integration_tests/cases.py index 8513c98d89..c11c1ac256 100644 --- a/tests/next_tests/integration_tests/cases.py +++ b/tests/next_tests/integration_tests/cases.py @@ -34,7 +34,7 @@ from gt4py.next.type_system import type_specifications as ts, type_translation from next_tests import definitions as test_definitions -from next_tests.integration_tests.feature_tests.ffront_tests.ffront_test_utils import ( # noqa: F401 # fixture and aliases +from next_tests.integration_tests.feature_tests.ffront_tests.ffront_test_utils import ( # noqa: F401 [unused-import] C2E, C2V, E2V, @@ -474,7 +474,7 @@ def verify_with_default_data( @pytest.fixture def cartesian_case( - exec_alloc_descriptor: test_definitions.ExecutionAndAllocatorDescriptor, # noqa: F811 # fixtures + exec_alloc_descriptor: test_definitions.ExecutionAndAllocatorDescriptor, ): yield Case( exec_alloc_descriptor.executor, @@ -487,8 +487,8 @@ def cartesian_case( @pytest.fixture def unstructured_case( - mesh_descriptor, # noqa: F811 # fixtures - exec_alloc_descriptor: test_definitions.ExecutionAndAllocatorDescriptor, # noqa: F811 # fixtures + mesh_descriptor, + exec_alloc_descriptor: test_definitions.ExecutionAndAllocatorDescriptor, ): yield Case( exec_alloc_descriptor.executor, diff --git a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_execution.py b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_execution.py index 5050008ef1..5db9886966 100644 --- a/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_execution.py +++ b/tests/next_tests/integration_tests/feature_tests/ffront_tests/test_execution.py @@ -57,7 +57,7 @@ ) -def test_copy(cartesian_case): # noqa: F811 # fixtures +def test_copy(cartesian_case): @gtx.field_operator def testee(a: cases.IJKField) -> cases.IJKField: field_tuple = (a, a) @@ -69,7 +69,7 @@ def testee(a: cases.IJKField) -> cases.IJKField: @pytest.mark.uses_tuple_returns -def test_multicopy(cartesian_case): # noqa: F811 # fixtures +def test_multicopy(cartesian_case): @gtx.field_operator def testee(a: cases.IJKField, b: cases.IJKField) -> tuple[cases.IJKField, cases.IJKField]: return a, b @@ -78,7 +78,7 @@ def testee(a: cases.IJKField, b: cases.IJKField) -> tuple[cases.IJKField, cases. @pytest.mark.uses_cartesian_shift -def test_cartesian_shift(cartesian_case): # noqa: F811 # fixtures +def test_cartesian_shift(cartesian_case): @gtx.field_operator def testee(a: cases.IJKField) -> cases.IJKField: return a(Ioff[1]) @@ -90,7 +90,7 @@ def testee(a: cases.IJKField) -> cases.IJKField: @pytest.mark.uses_unstructured_shift -def test_unstructured_shift(unstructured_case): # noqa: F811 # fixtures +def test_unstructured_shift(unstructured_case): @gtx.field_operator def testee(a: cases.VField) -> cases.EField: return a(E2V[0]) @@ -148,7 +148,7 @@ def composed_shift_unstructured(inp: cases.VField) -> cases.CField: @pytest.mark.uses_cartesian_shift -def test_fold_shifts(cartesian_case): # noqa: F811 # fixtures +def test_fold_shifts(cartesian_case): """Shifting the result of an addition should work.""" @gtx.field_operator @@ -163,7 +163,7 @@ def testee(a: cases.IJKField, b: cases.IJKField) -> cases.IJKField: cases.verify(cartesian_case, testee, a, b, out=out, ref=a.ndarray[1:] + b.ndarray[2:]) -def test_tuples(cartesian_case): # noqa: F811 # fixtures +def test_tuples(cartesian_case): @gtx.field_operator def testee(a: cases.IJKFloatField, b: cases.IJKFloatField) -> cases.IJKFloatField: inps = a, b @@ -175,7 +175,7 @@ def testee(a: cases.IJKFloatField, b: cases.IJKFloatField) -> cases.IJKFloatFiel ) -def test_scalar_arg(unstructured_case): # noqa: F811 # fixtures +def test_scalar_arg(unstructured_case): """Test scalar argument being turned into 0-dim field.""" @gtx.field_operator @@ -194,7 +194,7 @@ def testee(a: int32) -> cases.VField: ) -def test_nested_scalar_arg(unstructured_case): # noqa: F811 # fixtures +def test_nested_scalar_arg(unstructured_case): @gtx.field_operator def testee_inner(a: int32) -> cases.VField: return broadcast(a + 1, (Vertex,)) @@ -212,7 +212,7 @@ def testee(a: int32) -> cases.VField: @pytest.mark.uses_index_fields @pytest.mark.uses_cartesian_shift -def test_scalar_arg_with_field(cartesian_case): # noqa: F811 # fixtures +def test_scalar_arg_with_field(cartesian_case): @gtx.field_operator def testee(a: cases.IJKField, b: int32) -> cases.IJKField: tmp = b * a @@ -226,7 +226,7 @@ def testee(a: cases.IJKField, b: int32) -> cases.IJKField: cases.verify(cartesian_case, testee, a, b, out=out, ref=ref) -def test_scalar_in_domain_spec_and_fo_call(cartesian_case): # noqa: F811 # fixtures +def test_scalar_in_domain_spec_and_fo_call(cartesian_case): pytest.xfail( "Scalar arguments not supported to be used in both domain specification " "and as an argument to a field operator." @@ -253,7 +253,7 @@ def testee(size: gtx.IndexType, out: gtx.Field[[IDim], gtx.IndexType]): @pytest.mark.uses_scan -def test_scalar_scan(cartesian_case): # noqa: F811 # fixtures +def test_scalar_scan(cartesian_case): @gtx.scan_operator(axis=KDim, forward=True, init=(0.0)) def testee_scan(state: float, qc_in: float, scalar: float) -> float: qc = qc_in + state + scalar @@ -273,7 +273,7 @@ def testee(qc: cases.IKFloatField, scalar: float): @pytest.mark.uses_scan @pytest.mark.uses_scan_in_field_operator -def test_tuple_scalar_scan(cartesian_case): # noqa: F811 # fixtures +def test_tuple_scalar_scan(cartesian_case): @gtx.scan_operator(axis=KDim, forward=True, init=0.0) def testee_scan( state: float, qc_in: float, tuple_scalar: tuple[float, tuple[float, float]] @@ -296,7 +296,7 @@ def testee_op( @pytest.mark.uses_cartesian_shift @pytest.mark.uses_scan @pytest.mark.uses_index_fields -def test_scalar_scan_vertical_offset(cartesian_case): # noqa: F811 # fixtures +def test_scalar_scan_vertical_offset(cartesian_case): @gtx.scan_operator(axis=KDim, forward=True, init=(0.0)) def testee_scan(state: float, inp: float) -> float: return inp @@ -336,7 +336,7 @@ def testee_prog(a: cases.IKField): cases.verify(cartesian_case, testee_prog, a, inout=a[1, 3], ref=ref) -def test_astype_int(cartesian_case): # noqa: F811 # fixtures +def test_astype_int(cartesian_case): @gtx.field_operator def testee(a: cases.IFloatField) -> gtx.Field[[IDim], int64]: b = astype(a, int64) @@ -351,7 +351,7 @@ def testee(a: cases.IFloatField) -> gtx.Field[[IDim], int64]: @pytest.mark.uses_tuple_returns -def test_astype_on_tuples(cartesian_case): # noqa: F811 # fixtures +def test_astype_on_tuples(cartesian_case): @gtx.field_operator def field_op_returning_a_tuple( a: cases.IFloatField, b: cases.IFloatField @@ -423,7 +423,7 @@ def cast_nested_tuple( ) -def test_astype_bool_field(cartesian_case): # noqa: F811 # fixtures +def test_astype_bool_field(cartesian_case): @gtx.field_operator def testee(a: cases.IFloatField) -> gtx.Field[[IDim], bool]: b = astype(a, bool) @@ -438,7 +438,7 @@ def testee(a: cases.IFloatField) -> gtx.Field[[IDim], bool]: @pytest.mark.parametrize("inp", [0.0, 2.0]) -def test_astype_bool_scalar(cartesian_case, inp): # noqa: F811 # fixtures +def test_astype_bool_scalar(cartesian_case, inp): @gtx.field_operator def testee(inp: float) -> gtx.Field[[IDim], bool]: return broadcast(astype(inp, bool), (IDim,)) @@ -448,7 +448,7 @@ def testee(inp: float) -> gtx.Field[[IDim], bool]: cases.verify(cartesian_case, testee, inp, out=out, ref=bool(inp)) -def test_astype_float(cartesian_case): # noqa: F811 # fixtures +def test_astype_float(cartesian_case): @gtx.field_operator def testee(a: cases.IFloatField) -> gtx.Field[[IDim], np.float32]: b = astype(a, float32) diff --git a/tests/next_tests/integration_tests/feature_tests/test_util_cases.py b/tests/next_tests/integration_tests/feature_tests/test_util_cases.py index 59c72bbf3f..d739cec659 100644 --- a/tests/next_tests/integration_tests/feature_tests/test_util_cases.py +++ b/tests/next_tests/integration_tests/feature_tests/test_util_cases.py @@ -20,7 +20,7 @@ from next_tests import definitions from next_tests.integration_tests import cases -from next_tests.integration_tests.cases import ( # noqa: F401 # fixtures +from next_tests.integration_tests.cases import ( # noqa: F401 [unused-import] cartesian_case, exec_alloc_descriptor, ) @@ -38,7 +38,7 @@ def mixed_args( return (a, (c, a)) -def test_allocate_default_unique(cartesian_case): # noqa: F811 # fixtures +def test_allocate_default_unique(cartesian_case): a = cases.allocate(cartesian_case, mixed_args, "a")() assert np.min(a.asnumpy()) == 0 @@ -54,7 +54,7 @@ def test_allocate_default_unique(cartesian_case): # noqa: F811 # fixtures assert np.max(c.asnumpy()) == np.prod(tuple(cartesian_case.default_sizes.values())) * 2 -def test_allocate_return_default_zeros(cartesian_case): # noqa: F811 # fixtures +def test_allocate_return_default_zeros(cartesian_case): a, (b, c) = cases.allocate(cartesian_case, mixed_args, cases.RETURN)() assert np.all(a.asnumpy() == 0) @@ -62,7 +62,7 @@ def test_allocate_return_default_zeros(cartesian_case): # noqa: F811 # fixtures assert np.all(c.asnumpy() == 0) -def test_allocate_const(cartesian_case): # noqa: F811 # fixtures +def test_allocate_const(cartesian_case): a = cases.allocate(cartesian_case, mixed_args, "a").strategy(cases.ConstInitializer(42))() assert np.all(a.asnumpy() == 42) @@ -71,7 +71,7 @@ def test_allocate_const(cartesian_case): # noqa: F811 # fixtures @pytest.mark.parametrize("exec_alloc_descriptor", [definitions.ProgramBackendId.ROUNDTRIP.load()]) -def test_verify_fails_with_wrong_reference(cartesian_case): # noqa: F811 # fixtures +def test_verify_fails_with_wrong_reference(cartesian_case): a = cases.allocate(cartesian_case, addition, "a")() b = cases.allocate(cartesian_case, addition, "b")() out = cases.allocate(cartesian_case, addition, cases.RETURN)() @@ -82,7 +82,7 @@ def test_verify_fails_with_wrong_reference(cartesian_case): # noqa: F811 # fixt @pytest.mark.parametrize("exec_alloc_descriptor", [definitions.ProgramBackendId.ROUNDTRIP.load()]) -def test_verify_fails_with_wrong_type(cartesian_case): # noqa: F811 # fixtures +def test_verify_fails_with_wrong_type(cartesian_case): a = cases.allocate(cartesian_case, addition, "a").dtype(np.float32)() b = cases.allocate(cartesian_case, addition, "b")() out = cases.allocate(cartesian_case, addition, cases.RETURN)() @@ -93,7 +93,7 @@ def test_verify_fails_with_wrong_type(cartesian_case): # noqa: F811 # fixtures @pytest.mark.parametrize("exec_alloc_descriptor", [definitions.ProgramBackendId.ROUNDTRIP.load()]) def test_verify_with_default_data_fails_with_wrong_reference( - cartesian_case, # noqa: F811 # fixtures + cartesian_case, ): def wrong_ref(a, b): return a - b diff --git a/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_embedded_regression.py b/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_embedded_regression.py index 65f017a518..289b2ea898 100644 --- a/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_embedded_regression.py +++ b/tests/next_tests/integration_tests/multi_feature_tests/ffront_tests/test_embedded_regression.py @@ -19,14 +19,14 @@ from gt4py.next import errors from next_tests.integration_tests import cases -from next_tests.integration_tests.cases import IField, cartesian_case # noqa: F401 # fixtures -from next_tests.integration_tests.feature_tests.ffront_tests.ffront_test_utils import ( # noqa: F401 # fixtures +from next_tests.integration_tests.cases import IField, cartesian_case # noqa: F401 [unused-import] +from next_tests.integration_tests.feature_tests.ffront_tests.ffront_test_utils import ( # noqa: F401 [unused-import] KDim, exec_alloc_descriptor, ) -def test_default_backend_is_respected_field_operator(cartesian_case): # noqa: F811 # fixtures +def test_default_backend_is_respected_field_operator(cartesian_case): """Test that manually calling the field operator without setting the backend raises an error.""" # Important not to set the backend here! @@ -43,7 +43,7 @@ def copy(a: IField) -> IField: _ = copy(a, out=a, offset_provider={}) -def test_default_backend_is_respected_scan_operator(cartesian_case): # noqa: F811 # fixtures +def test_default_backend_is_respected_scan_operator(cartesian_case): """Test that manually calling the scan operator without setting the backend raises an error.""" # Important not to set the backend here! @@ -58,7 +58,7 @@ def sum(state: float, a: float) -> float: _ = sum(a, out=a, offset_provider={}) -def test_default_backend_is_respected_program(cartesian_case): # noqa: F811 # fixtures +def test_default_backend_is_respected_program(cartesian_case): """Test that manually calling the program without setting the backend raises an error.""" @gtx.field_operator @@ -78,7 +78,7 @@ def copy_program(a: IField, b: IField) -> IField: _ = copy_program(a, b, offset_provider={}) -def test_missing_arg_field_operator(cartesian_case): # noqa: F811 # fixtures +def test_missing_arg_field_operator(cartesian_case): """Test that calling a field_operator without required args raises an error.""" @gtx.field_operator(backend=cartesian_case.executor) @@ -94,7 +94,7 @@ def copy(a: IField) -> IField: _ = copy(a, out=a) -def test_missing_arg_scan_operator(cartesian_case): # noqa: F811 # fixtures +def test_missing_arg_scan_operator(cartesian_case): """Test that calling a scan_operator without required args raises an error.""" @gtx.scan_operator(backend=cartesian_case.executor, axis=KDim, init=0.0, forward=True) @@ -110,7 +110,7 @@ def sum(state: float, a: float) -> float: _ = sum(a, out=a) -def test_missing_arg_program(cartesian_case): # noqa: F811 # fixtures +def test_missing_arg_program(cartesian_case): """Test that calling a program without required args raises an error.""" @gtx.field_operator diff --git a/tests/next_tests/unit_tests/ffront_tests/test_func_to_foast_error_line_number.py b/tests/next_tests/unit_tests/ffront_tests/test_func_to_foast_error_line_number.py index 123d57baf1..02dbfbfee2 100644 --- a/tests/next_tests/unit_tests/ffront_tests/test_func_to_foast_error_line_number.py +++ b/tests/next_tests/unit_tests/ffront_tests/test_func_to_foast_error_line_number.py @@ -80,7 +80,7 @@ def test_fo_type_deduction_error(): line = inspect.getframeinfo(inspect.currentframe()).lineno def field_operator_with_undeclared_symbol(): - return undeclared_symbol # noqa: F821 # undefined on purpose + return undeclared_symbol # noqa: F821 [undefined-name] with pytest.raises(errors.DSLError) as exc_info: _ = f2f.FieldOperatorParser.apply_to_function(field_operator_with_undeclared_symbol) diff --git a/tests/next_tests/unit_tests/ffront_tests/test_func_to_past.py b/tests/next_tests/unit_tests/ffront_tests/test_func_to_past.py index cca05f9917..605048d834 100644 --- a/tests/next_tests/unit_tests/ffront_tests/test_func_to_past.py +++ b/tests/next_tests/unit_tests/ffront_tests/test_func_to_past.py @@ -109,7 +109,7 @@ def test_undefined_field_program(identity_def): identity = gtx.field_operator(identity_def) def undefined_field_program(in_field: gtx.Field[[IDim], "float64"]): - identity(in_field, out=out_field) # noqa: F821 # undefined on purpose + identity(in_field, out=out_field) # noqa: F821 [undefined-name] with pytest.raises( errors.DSLError,