Skip to content

Commit 4bb5192

Browse files
refactor: __init__ file (#3490)
* refactor: cleaning up the init file * feat: centralizing globals in `__init__` file * chore: adding changelog file 3490.added.md [dependabot-skip] * feat: adding missing import --------- Co-authored-by: pyansys-ci-bot <[email protected]>
1 parent 84085c3 commit 4bb5192

File tree

9 files changed

+201
-163
lines changed

9 files changed

+201
-163
lines changed

doc/changelog.d/3490.added.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
refactor: `__init__` file

src/ansys/mapdl/core/__init__.py

Lines changed: 76 additions & 93 deletions
Original file line numberDiff line numberDiff line change
@@ -20,102 +20,89 @@
2020
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2121
# SOFTWARE.
2222

23-
# Importing logging
23+
import importlib.metadata as importlib_metadata
24+
25+
###############################################################################
26+
# Imports
27+
# =======
28+
#
2429
import logging
2530
import os
2631
import sys
32+
from typing import Dict, List, Tuple
2733
from warnings import warn
2834

29-
import platformdirs
30-
31-
# Setup data directory
32-
USER_DATA_PATH = platformdirs.user_data_dir(
33-
appname="ansys_mapdl_core", appauthor="Ansys"
34-
)
35-
if not os.path.exists(USER_DATA_PATH): # pragma: no cover
36-
os.makedirs(USER_DATA_PATH)
37-
38-
DEPRECATING_MINIMUM_PYTHON_VERSION = True
39-
MINIMUM_PYTHON_VERSION = (3, 10)
40-
41-
first_time_file = os.path.join(USER_DATA_PATH, ".firstime")
42-
if not os.path.exists(first_time_file): # pragma: no cover
43-
py_ver = f"{sys.version_info[0]}.{sys.version_info[1]}"
44-
py_ver_min = f"{MINIMUM_PYTHON_VERSION[0]}.{MINIMUM_PYTHON_VERSION[1]}"
45-
46-
if (
47-
sys.version_info[1] == MINIMUM_PYTHON_VERSION[1]
48-
and DEPRECATING_MINIMUM_PYTHON_VERSION
49-
):
50-
warn(
51-
f"Support for Python {py_ver} will be dropped in the next minor " "release."
52-
)
53-
54-
if sys.version_info[1] <= MINIMUM_PYTHON_VERSION[1]:
55-
warn(
56-
f"Python {py_ver} is not being tested or officially supported. "
57-
"It is recommended you use a newer version of Python. "
58-
f"The mininimum supported and tested version is {py_ver_min}.\n\n"
59-
"**This warning is shown only the first time you run PyMAPDL.**\n"
60-
)
61-
62-
with open(first_time_file, "w") as fid:
63-
fid.write("")
64-
65-
EXAMPLES_PATH = os.path.join(USER_DATA_PATH, "examples")
35+
from platformdirs import user_data_dir
6636

37+
###############################################################################
38+
# Logging
39+
# =======
40+
#
6741
from ansys.mapdl.core.logging import Logger
6842

6943
LOG = Logger(level=logging.ERROR, to_file=False, to_stdout=True)
7044
LOG.debug("Loaded logging module as LOG")
7145

46+
###############################################################################
47+
# Globals
48+
# =======
49+
#
50+
from ansys.mapdl.core.helpers import is_installed, run_every_import, run_first_time
7251

73-
BUILDING_GALLERY = False
74-
RUNNING_TESTS = False
75-
76-
if RUNNING_TESTS: # pragma: no cover
77-
LOG.debug("Running tests on Pytest")
78-
79-
_LOCAL_PORTS = []
80-
52+
__version__: str = importlib_metadata.version(__name__.replace(".", "-"))
8153

82-
try:
83-
from ansys.tools.visualization_interface import Plotter
54+
# A dictionary relating PyMAPDL server versions with the unified install ones
55+
VERSION_MAP: Dict[Tuple[int, int, int], str] = {
56+
(0, 0, 0): "2020R2",
57+
(0, 3, 0): "2021R1",
58+
(0, 4, 0): "2021R2",
59+
(0, 4, 1): "2021R2",
60+
(0, 5, 0): "2022R1",
61+
(0, 5, 1): "2022R2",
62+
}
8463

85-
_HAS_VISUALIZER = True
86-
except ModuleNotFoundError: # pragma: no cover
87-
LOG.debug("The module 'ansys-tools-visualization_interface' is not installed.")
88-
_HAS_VISUALIZER = False
64+
BUILDING_GALLERY: bool = False
65+
RUNNING_TESTS: bool = False
8966

90-
try:
91-
import pyvista as pv
67+
DEPRECATING_MINIMUM_PYTHON_VERSION: bool = True
68+
MINIMUM_PYTHON_VERSION: Tuple[int, int] = (3, 10)
9269

93-
_HAS_PYVISTA = True
94-
except ModuleNotFoundError: # pragma: no cover
95-
LOG.debug("The module 'pyvista' is not installed.")
96-
_HAS_PYVISTA = False
70+
# Import related globals
71+
_HAS_ATP: bool = is_installed("ansys.tools.path")
72+
_HAS_PIM: bool = is_installed("ansys.platform.instancemanagement")
73+
_HAS_PYANSYS_REPORT: bool = is_installed("ansys.tools.report")
74+
_HAS_PYVISTA: bool = is_installed("pyvista")
75+
_HAS_TQDM: bool = is_installed("tqdm")
76+
_HAS_VISUALIZER: bool = is_installed("ansys.tools.visualization_interface")
9777

78+
# Setup directories
79+
USER_DATA_PATH: str = user_data_dir(appname="ansys_mapdl_core", appauthor="Ansys")
80+
EXAMPLES_PATH = os.path.join(USER_DATA_PATH, "examples")
9881

99-
try:
100-
import importlib.metadata as importlib_metadata
101-
except ModuleNotFoundError: # pragma: no cover
102-
import importlib_metadata
82+
# Store local ports
83+
_LOCAL_PORTS: List[int] = []
10384

104-
__version__ = importlib_metadata.version(__name__.replace(".", "-"))
85+
###############################################################################
86+
# First time
87+
# ==========
88+
#
89+
# This function runs only the first time PyMAPDL is importad after it is installed.
90+
# It creates the required directories and raise Python version related warnings.
91+
#
92+
run_first_time()
10593

106-
try:
107-
from ansys.tools.path.path import (
108-
change_default_ansys_path,
109-
find_ansys,
110-
get_ansys_path,
111-
get_available_ansys_installations,
112-
save_ansys_path,
113-
)
114-
except:
115-
# We don't really use these imports in the library. They are here for
116-
# convenience.
117-
pass
94+
###############################################################################
95+
# Runs every time
96+
# ===============
97+
#
98+
# This function runs every time that PyMAPDL is imported.
99+
#
100+
run_every_import()
118101

102+
###############################################################################
103+
# Library imports
104+
# ===============
105+
#
119106
from ansys.mapdl.core._version import SUPPORTED_ANSYS_VERSIONS
120107
from ansys.mapdl.core.convert import convert_apdl_block, convert_script
121108
from ansys.mapdl.core.launcher import close_all_local_instances
@@ -131,23 +118,19 @@
131118
from ansys.mapdl.core.misc import Report, _check_has_ansys
132119
from ansys.mapdl.core.pool import MapdlPool
133120

134-
_HAS_ANSYS = _check_has_ansys()
121+
###############################################################################
122+
# Convenient imports
123+
# ==================
124+
#
125+
# For compatibility with other versions or for convenience
126+
if _HAS_ATP:
127+
from ansys.tools.path.path import (
128+
change_default_ansys_path,
129+
find_ansys,
130+
get_ansys_path,
131+
get_available_ansys_installations,
132+
save_ansys_path,
133+
)
135134

136135
if _HAS_VISUALIZER:
137-
from ansys.mapdl.core.plotting.theme import _apply_default_theme
138-
139-
_apply_default_theme()
140-
141-
BUILDING_GALLERY = False
142-
RUNNING_TESTS = False
143-
144-
145-
VERSION_MAP = {
146-
(0, 0, 0): "2020R2",
147-
(0, 3, 0): "2021R1",
148-
(0, 4, 0): "2021R2",
149-
(0, 4, 1): "2021R2",
150-
(0, 5, 0): "2022R1",
151-
(0, 5, 1): "2022R2", # as of 21 Mar 2022 unreleased
152-
}
153-
"""A dictionary relating PyMAPDL server versions with the unified install ones."""
136+
from ansys.tools.visualization_interface import Plotter

src/ansys/mapdl/core/helpers.py

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
# Copyright (C) 2016 - 2024 ANSYS, Inc. and/or its affiliates.
2+
# SPDX-License-Identifier: MIT
3+
#
4+
#
5+
# Permission is hereby granted, free of charge, to any person obtaining a copy
6+
# of this software and associated documentation files (the "Software"), to deal
7+
# in the Software without restriction, including without limitation the rights
8+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
# copies of the Software, and to permit persons to whom the Software is
10+
# furnished to do so, subject to the following conditions:
11+
#
12+
# The above copyright notice and this permission notice shall be included in all
13+
# copies or substantial portions of the Software.
14+
#
15+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
# SOFTWARE.
22+
23+
"""Module for helper functions"""
24+
25+
import importlib
26+
import os
27+
import sys
28+
from warnings import warn
29+
30+
from ansys.mapdl.core import LOG
31+
32+
33+
def is_installed(package_name: str) -> bool:
34+
"""Check if a package is installed"""
35+
36+
if os.name == "nt":
37+
package_name = package_name.replace("-", ".")
38+
39+
try:
40+
importlib.import_module(package_name)
41+
42+
return True
43+
except ModuleNotFoundError: # pragma: no cover
44+
LOG.debug(f"The module '{package_name}' is not installed.")
45+
return False
46+
47+
48+
def run_first_time() -> None:
49+
"""Run this function the first time PyMAPDL is imported"""
50+
from ansys.mapdl.core import (
51+
DEPRECATING_MINIMUM_PYTHON_VERSION,
52+
MINIMUM_PYTHON_VERSION,
53+
USER_DATA_PATH,
54+
)
55+
56+
first_time_file: str = os.path.join(USER_DATA_PATH, ".firstime")
57+
58+
# Run the first time only
59+
if not os.path.exists(first_time_file): # pragma: no cover
60+
61+
# Create USER_DATA_PATH directory
62+
if not os.path.exists(USER_DATA_PATH): # pragma: no cover
63+
os.makedirs(USER_DATA_PATH)
64+
65+
# Show warning about Python compatibility
66+
py_ver = f"{sys.version_info[0]}.{sys.version_info[1]}"
67+
py_ver_min = f"{MINIMUM_PYTHON_VERSION[0]}.{MINIMUM_PYTHON_VERSION[1]}"
68+
69+
if (
70+
sys.version_info[1] == MINIMUM_PYTHON_VERSION[1]
71+
and DEPRECATING_MINIMUM_PYTHON_VERSION
72+
):
73+
warn(
74+
f"Support for Python {py_ver} will be dropped in the next minor "
75+
"release."
76+
)
77+
78+
if sys.version_info[1] <= MINIMUM_PYTHON_VERSION[1]:
79+
warn(
80+
f"Python {py_ver} is not being tested or officially supported. "
81+
"It is recommended you use a newer version of Python. "
82+
f"The mininimum supported and tested version is {py_ver_min}.\n\n"
83+
"**This warning is shown only the first time you run PyMAPDL.**\n"
84+
)
85+
86+
with open(first_time_file, "w") as fid:
87+
fid.write("")
88+
89+
90+
def run_every_import() -> None:
91+
# Run every time we import PyMAPDL
92+
from ansys.mapdl.core import _HAS_VISUALIZER, RUNNING_TESTS
93+
94+
# Apply custom theme
95+
if _HAS_VISUALIZER:
96+
from ansys.mapdl.core.plotting.theme import _apply_default_theme
97+
98+
_apply_default_theme()
99+
100+
# In case we want to do something specific for testing.
101+
if RUNNING_TESTS: # pragma: no cover
102+
LOG.debug("Running tests on Pytest")

src/ansys/mapdl/core/launcher.py

Lines changed: 7 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -36,23 +36,8 @@
3636

3737
import psutil
3838

39-
try:
40-
import ansys.platform.instancemanagement as pypim
41-
42-
_HAS_PIM = True
43-
44-
except ModuleNotFoundError: # pragma: no cover
45-
_HAS_PIM = False
46-
47-
try:
48-
from ansys.tools.path import find_ansys, get_ansys_path, version_from_path
49-
50-
_HAS_ATP = True
51-
except ModuleNotFoundError:
52-
_HAS_ATP = False
53-
5439
from ansys.mapdl import core as pymapdl
55-
from ansys.mapdl.core import LOG
40+
from ansys.mapdl.core import _HAS_ATP, _HAS_PIM, LOG
5641
from ansys.mapdl.core._version import SUPPORTED_ANSYS_VERSIONS
5742
from ansys.mapdl.core.errors import (
5843
LockFileException,
@@ -72,6 +57,12 @@
7257
threaded,
7358
)
7459

60+
if _HAS_PIM:
61+
import ansys.platform.instancemanagement as pypim
62+
63+
if _HAS_ATP:
64+
from ansys.tools.path import find_ansys, get_ansys_path, version_from_path
65+
7566
if TYPE_CHECKING: # pragma: no cover
7667
from ansys.mapdl.core.mapdl_console import MapdlConsole
7768

src/ansys/mapdl/core/licensing.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -27,19 +27,13 @@
2727
import subprocess
2828
import time
2929

30-
from ansys.mapdl.core import LOG
30+
from ansys.mapdl.core import _HAS_ATP, LOG
3131
from ansys.mapdl.core.errors import LicenseServerConnectionError
3232
from ansys.mapdl.core.misc import threaded_daemon
3333

34-
try:
34+
if _HAS_ATP:
3535
from ansys.tools.path import get_ansys_path, version_from_path
3636

37-
_HAS_ATP = True
38-
39-
except ModuleNotFoundError:
40-
_HAS_ATP = False
41-
42-
4337
LOCALHOST = "127.0.0.1"
4438
LIC_PATH_ENVAR = "ANSYSLIC_DIR"
4539
LIC_FILE_ENVAR = "ANSYSLMD_LICENSE_FILE"

0 commit comments

Comments
 (0)