Skip to content

Commit bf6115e

Browse files
germa89pyansys-ci-botclatapie
authored
fix: mypy type checking issues across core modules (#4309)
* docs(examples): escape backslash in Young's modulus math expression in bracket_static example * refactor(commands): introduce CommandsBase with typed run() and make command mixins inherit Add a CommandsBase class (with a typed run(command, write_to_log, mute, **kwargs) stub) to declare the interface used by APDL command mixins. Update numerous command modules to import and inherit from CommandsBase so mixins consistently express the expected run() contract for the parent MAPDL class. * typing: use TypeAlias for Literal-based type aliases and add type annotations Convert several Literal tuple usages to explicit TypeAlias (ENTITIES_TYP, RESIDUAL_ALGORITHM_LITERAL, VALID_DEVICES_LITERAL, VALID_FILE_TYPE_FOR_PLOT_LITERAL), import TypeAlias where needed, and add typing annotations for base_report_class. Minor typing cleanup and ignore-type for Report subclassing. * typing: refine type annotations, add type ignores, and fix minor issues - common_grpc: annotate parse_chunks as grpc.CallIterator (ignore name-defined) - component: correct ENTITIES_MAPPING typing, tighten Component __new__/repr/type signatures and add attr type ignores - helpers: fix namedtuple import from collections - krylov: guard residuals with None check and add attr type ignore on append - logging: add type ignores for dynamic logger handler attributes - mapdl_core: fix mesh check (grid.n_node), accept pathlib.Path in _decompose_fname, add asserts for newly created/opened resources, and local rename for clarity - mapdl_geometry: allow ndarray for _select_items parameter - misc: broaden routine parameters to accept str or ROUTINES and add type ignores for mapdl attribute access - pool: avoid shadowing timeout by renaming and add type ignore for progress bar update These changes improve typing correctness, silence false-positive type errors, and address several small bugs/clarifications. * typing: refine type annotations and improve runtime robustness across core modules - component: broaden Component.__new__ to accept lists, ndarrays, ints, strs, Components and None; coerce items to tuple and handle fallbacks. Make ComponentManager handle cmtype as string or [selection, type] and guard cmlist parsing for None. - krylov: tighten typing (Optional[str] for full_file), accept int/str for frequency inputs, allow residual_algorithm to be Optional and validate only when provided. - licensing: raise OSError when home directory cannot be determined before building license path. - mapdl_core: accept pathlib.Path or str in _wrap_directory. - mapdl_extended / mapdl_grpc: add targeted type ignores and refine parameter types (chunk_size, progress_bar, _mapdl_process, vget/nvar, VAR_IR) to satisfy static typing and avoid mypy issues. - misc: robust MODULE_PATH resolution using inspect.currentframe() with fallback to __file__. * fix(core): improve robustness for regex matches, None handling, and parent/type guards - component: refine __getitem__ return annotation to Component (type: ignore[override]) - krylov: guard residual_algorithm against None before calling .lower() - licensing: handle missing subprocess.stdout, ensure licenses is a list, and check output type before searching for error messages - logging: check self.extra is not None before accessing .name - mapdl_core: cache parent reference in WithInterativePlotting and assert it's not None; avoid repeated _parent() calls - mapdl_extended: safely search for the table block before parsing and only populate the table if a match is found - mapdl_grpc: return empty string instead of None from command response helper - mesh_grpc: use safe regex matches when extracting REAL CONSTANT SET, ITEMS, and TO values - parameters: guard regex searches when extracting parameter names and string elements to avoid AttributeError * typing: refine annotations and add type ignores across core modules - fix Literal alias declaration in common_grpc - tighten Optional/Union signatures and use TypeAlias where appropriate - add explicit variable typings and where necessary - small parsing/type improvements in component, parameters, misc - annotate/adjust dynamic fields in mapdl_core, mapdl_grpc, licensing, pool, krylov, logging Improve type clarity and runtime robustness while keeping dynamic assignments compatible with runtime values. * mypy: add exclude paths and enable namespace/explicit package bases in pyproject.toml * typing: refine annotations and fix mypy issues across core modules Add/adjust type hints (TextIO, Optional, list[str], TYPE_CHECKING imports), tighten function signatures, add targeted type:ignore comments, cast query results to int for SelectionStatus, and improve internal type checks/assertions. Also rename a few tests for clearer descriptions. * Fix licensing.py type annotation for licenses list assignment * Fix mapdl_grpc.py type issues: None checks, type annotations, timeout handling * Fix common_grpc.py: replace None with empty string in list items * Fix database.py: add None check for environment variable * Fix mapdl_core.py: initialize _remove_tmp as bool instead of None * Fix pool.py: handle Optional timeout parameter * Fix mesh_grpc.py: cast float to int for list assignment * Fix verif_files.py: add None check for inspect.currentframe() * Fix commands.py: add value parameter to property setter * Fix helpers.py: remove unused namedtuple import * Fix parameters.py: move type ignore to individual dict entries * Fix krylov.py: add type ignore for operator issues with dynamic types * Fix .ci/pytest_summary.py: add index type ignore comments * Add doc/ and examples/ exclusions to mypy pre-commit hook * chore: adding changelog file 4309.fixed.md [dependabot-skip] * Delete .codacy/codacy.yaml * fix (common_grpc.py): relax parse_chunks typing to Any, add numpy.typing import, and update docstring * fix (mapdl_core.py, mesh_grpc.py, tests/test_commands.py): return plot filename from screenshot, refine rlist typing, update test commands - mapdl_core.py: change _download_plot to return the copied filename (str); update screenshot signature/return to str | None and adjust logic/docstring so providing savefig returns the saved filename. - mesh_grpc.py: tighten _parse_rlist typing to dict[int, list[int | float]] and fix parsing/assignment so real-constant values preserve numeric types. - tests/test_commands.py: include "run" in the tested command list. * ci (.pre-commit-config.yaml): remove skip for mypy hook * refactor (misc.py): simplify creation_time by using hasattr(stat, "st_birthtime") and return mtime fallback * fix (misc.py): add type: ignore for stat.st_birthtime in creation_time * fix (parameters.py): initialize name_ in interp_star_status to avoid unbound local reference * ci (.github/workflows/migrator.yml): add zizmor ignore comment to persist-credentials setting * fix(action): correct shell command for starting Julia in test action * fix: bandit check * fix: asserts --------- Co-authored-by: pyansys-ci-bot <[email protected]> Co-authored-by: clatapie <[email protected]>
1 parent 8a2ed11 commit bf6115e

File tree

151 files changed

+814
-388
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

151 files changed

+814
-388
lines changed

.ci/pytest_summary.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -79,15 +79,15 @@ def compute_statistics(
7979
test_stats: dict[str, TEST_STATS_TYPE] = {}
8080

8181
for test in tests:
82-
test_id: str = test["id"]
82+
test_id = test["id"] # type: ignore[assignment]
8383
if test_id not in test_stats:
84-
test_stats[test_id] = {
84+
test_stats[test_id] = { # type: ignore[index]
8585
"durations": [],
8686
"n_tests": 0,
8787
}
8888

89-
test_stats[test_id]["durations"].append(test["duration"])
90-
test_stats[test_id]["n_tests"] += 1
89+
test_stats[test_id]["durations"].append(test["duration"]) # type: ignore[arg-type,index]
90+
test_stats[test_id]["n_tests"] += 1 # type: ignore[index]
9191

9292
summary: list[dict[str, Any]] = []
9393

@@ -170,10 +170,10 @@ def make_bold(s: str) -> str:
170170
for i, each_key in enumerate(keys):
171171

172172
if i == 0:
173-
id_: str = test[each_key]
173+
id_ = test[each_key] # type: ignore[assignment]
174174

175175
id_ = (
176-
id_.replace("(", r"(")
176+
id_.replace("(", r"(") # type: ignore[union-attr]
177177
.replace(")", r")")
178178
.replace("[", r"[")
179179
.replace("]", r"]")
@@ -197,8 +197,8 @@ def make_bold(s: str) -> str:
197197

198198
def print_summary(summary: list[dict[str, str | float]], num: int = 10):
199199
"""Print the top N longest tests and the top N most variable tests."""
200-
longest_tests = sorted(summary, key=lambda x: -x["average_duration"])[:num]
201-
most_variable_tests = sorted(summary, key=lambda x: -x["std_dev"])[:num]
200+
longest_tests = sorted(summary, key=lambda x: -x["average_duration"])[:num] # type: ignore[operator]
201+
most_variable_tests = sorted(summary, key=lambda x: -x["std_dev"])[:num] # type: ignore[operator]
202202

203203
print(f"\n## Top {num} Longest Running Tests\n")
204204
print_table(

.github/actions/test-julia/action.yml

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ runs:
3333
"$PYTHON_PATH" -m pip install -e .
3434
3535
- name: "Starting Julia"
36-
shell: julia {0}
36+
shell: bash
3737
run: |
38-
using Pkg; Pkg.add("PyCall");using PyCall;pymapdl = pyimport("ansys.mapdl.core");print(pymapdl.__version__)
38+
julia -e 'using Pkg; Pkg.add("PyCall");using PyCall;pymapdl = pyimport("ansys.mapdl.core");print(pymapdl.__version__)'
39+

.github/workflows/migrator.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,7 @@ jobs:
298298
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 #v5.0.0
299299
with:
300300
ref: main
301-
persist-credentials: true
301+
persist-credentials: true # zizmor: ignore[artipacked]
302302

303303
- name: Clone head repo and checkout branch. Resolve conflicts if needed.
304304
if : ${{ env.CONTINUE == 'true' }}

.pre-commit-config.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ ci:
99
1010
# PR name when autoupdate
1111
autoupdate_commit_msg: 'ci: pre-commit autoupdate'
12-
skip: [mypy]
1312

1413

1514
repos:
@@ -24,6 +23,7 @@ repos:
2423
hooks:
2524
- id: mypy
2625
args: [ --follow-imports=silent, --config-file=pyproject.toml]
26+
exclude: ^(doc/|examples/)
2727

2828
- repo: https://github.com/ansys/pre-commit-hooks
2929
rev: v0.5.2

doc/changelog.d/4309.fixed.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Mypy type checking issues across core modules

examples/00-mapdl-examples/bracket_static.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@
6868
~~~~~~~~~~~~~
6969
7070
The dimensions of the corner bracket are shown in the following figure.
71-
The bracket is made of A36 steel with a Young's modulus of :math:`3\cdot 10^7` psi
71+
The bracket is made of A36 steel with a Young's modulus of :math:`3\\cdot 10^7` psi
7272
and Poisson's ratio of :math:`0.27`.
7373
7474
.. figure:: ../../../images/bracket_dimensions.png

pyproject.toml

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,18 @@ disable_error_code = [
274274
"return",
275275
"return-value",
276276
]
277+
exclude = [
278+
"^\\.ci/",
279+
"^build/",
280+
"^dist/",
281+
"^doc/",
282+
"^examples/",
283+
"^htmlcov/",
284+
"^tests/",
285+
]
286+
explicit_package_bases = true
287+
namespace_packages = true
288+
277289

278290
[tool.towncrier]
279291
directory = "doc/changelog.d"

src/ansys/mapdl/core/_commands/__init__.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,46 @@
1919
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
2020
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2121
# SOFTWARE.
22+
23+
from typing import Any, Optional
24+
25+
26+
class CommandsBase:
27+
"""Base class for MAPDL command mixin classes.
28+
29+
This class declares the interface that command mixin classes rely on.
30+
The actual implementation of the run method is provided by the parent
31+
MAPDL class when these command mixins are combined via multiple inheritance.
32+
"""
33+
34+
def run(
35+
self,
36+
command: str,
37+
write_to_log: bool = True,
38+
mute: Optional[bool] = None,
39+
**kwargs: Any,
40+
) -> str:
41+
"""Run a single APDL command.
42+
43+
This method is implemented by the parent MAPDL class.
44+
Command mixins can call this method to execute APDL commands.
45+
46+
Parameters
47+
----------
48+
command : str
49+
ANSYS APDL command.
50+
write_to_log : bool, optional
51+
Whether to write command to log. Default ``True``.
52+
mute : bool, optional
53+
Whether to mute command output.
54+
**kwargs : Any
55+
Additional keyword arguments.
56+
57+
Returns
58+
-------
59+
str
60+
Command output from MAPDL.
61+
"""
62+
raise NotImplementedError(
63+
"The run method must be provided by the parent MAPDL class"
64+
)

src/ansys/mapdl/core/_commands/apdl/abbreviations.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,10 @@
2020
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2121
# SOFTWARE.
2222

23+
from ansys.mapdl.core._commands import CommandsBase
2324

24-
class Abbreviations:
25+
26+
class Abbreviations(CommandsBase):
2527

2628
def abbr(self, abbr: str = "", string: str = "", **kwargs):
2729
r"""Defines an abbreviation.

src/ansys/mapdl/core/_commands/apdl/array_parameters.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,10 @@
2020
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2121
# SOFTWARE.
2222

23+
from ansys.mapdl.core._commands import CommandsBase
2324

24-
class ArrayParameters:
25+
26+
class ArrayParameters(CommandsBase):
2527

2628
def mfouri(
2729
self,

0 commit comments

Comments
 (0)