Skip to content

Commit e8b79f7

Browse files
authored
Unify env vars access (#7084)
Fixes #6879. ### Description Some environment variable called using `os.get.environ("MONAI_VAR")` instead of `monai.utils.MONAIEnvVars`. Can't use `monai.utils.MONAIEnvVars` in `monai.utils.module.py` due to circular imports. ### Types of changes <!--- Put an `x` in all the boxes that apply, and remove the not applicable items --> - [x] Non-breaking change (fix or new feature that would not break existing functionality). - [ ] Breaking change (fix or new feature that would cause existing functionality to change). - [ ] New tests added to cover the changes. - [ ] Integration tests passed locally by running `./runtests.sh -f -u --net --coverage`. - [x] Quick tests passed locally by running `./runtests.sh --quick --unittests --disttests`. - [ ] In-line docstrings updated. - [ ] Documentation updated, tested `make html` command in the `docs/` folder. --------- Signed-off-by: vgrau98 <victor.grau93@gmail.com>
1 parent 65e8f5b commit e8b79f7

11 files changed

Lines changed: 43 additions & 14 deletions

File tree

monai/apps/auto3dseg/bundle_gen.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,11 @@
4242
from monai.config import PathLike
4343
from monai.utils import ensure_tuple, look_up_option, run_cmd
4444
from monai.utils.enums import AlgoKeys
45+
from monai.utils.misc import MONAIEnvVars
4546

4647
logger = get_logger(module_name=__name__)
47-
ALGO_HASH = os.environ.get("MONAI_ALGO_HASH", "3e11dd0")
48+
ALGO_HASH = MONAIEnvVars.algo_hash()
49+
4850

4951
__all__ = ["BundleAlgo", "BundleGen"]
5052

monai/metrics/utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -275,10 +275,10 @@ def get_surface_distance(
275275
"""
276276
lib: ModuleType = torch if isinstance(seg_pred, torch.Tensor) else np
277277
if not seg_gt.any():
278-
dis = lib.inf * lib.ones_like(seg_gt, dtype=lib.float32)
278+
dis = np.inf * lib.ones_like(seg_gt, dtype=lib.float32)
279279
else:
280280
if not lib.any(seg_pred):
281-
dis = lib.inf * lib.ones_like(seg_gt, dtype=lib.float32)
281+
dis = np.inf * lib.ones_like(seg_gt, dtype=lib.float32)
282282
dis = dis[seg_gt]
283283
return convert_to_dst_type(dis, seg_pred, dtype=dis.dtype)[0]
284284
if distance_metric == "euclidean":

monai/networks/utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -552,7 +552,7 @@ def copy_model_state(
552552
if inplace and isinstance(dst, torch.nn.Module):
553553
if isinstance(dst, (nn.DataParallel, nn.parallel.DistributedDataParallel)):
554554
dst = dst.module
555-
dst.load_state_dict(dst_dict)
555+
dst.load_state_dict(dst_dict) # type: ignore
556556
return dst_dict, updated_keys, unchanged_keys
557557

558558

monai/optimizers/novograd.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ def __setstate__(self, state):
7070
for group in self.param_groups:
7171
group.setdefault("amsgrad", False)
7272

73-
def step(self, closure: Callable[[], T] | None = None) -> T | None:
73+
def step(self, closure: Callable[[], T] | None = None) -> T | None: # type: ignore
7474
"""Performs a single optimization step.
7575
7676
Arguments:

monai/transforms/inverse.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111

1212
from __future__ import annotations
1313

14-
import os
1514
import warnings
1615
from collections.abc import Hashable, Mapping
1716
from contextlib import contextmanager
@@ -34,6 +33,7 @@
3433
convert_to_numpy,
3534
convert_to_tensor,
3635
)
36+
from monai.utils.misc import MONAIEnvVars
3737

3838
__all__ = ["TraceableTransform", "InvertibleTransform"]
3939

@@ -70,7 +70,7 @@ class TraceableTransform(Transform):
7070
`MONAI_TRACE_TRANSFORM` when initializing the class.
7171
"""
7272

73-
tracing = os.environ.get("MONAI_TRACE_TRANSFORM", "1") != "0"
73+
tracing = MONAIEnvVars.trace_transform() != "0"
7474

7575
def set_tracing(self, tracing: bool) -> None:
7676
"""Set whether to trace transforms."""

monai/utils/misc.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -527,6 +527,30 @@ def debug() -> bool:
527527
def doc_images() -> str | None:
528528
return os.environ.get("MONAI_DOC_IMAGES")
529529

530+
@staticmethod
531+
def algo_hash() -> str | None:
532+
return os.environ.get("MONAI_ALGO_HASH", "e01d67a")
533+
534+
@staticmethod
535+
def trace_transform() -> str | None:
536+
return os.environ.get("MONAI_TRACE_TRANSFORM", "1")
537+
538+
@staticmethod
539+
def eval_expr() -> str | None:
540+
return os.environ.get("MONAI_EVAL_EXPR", "1")
541+
542+
@staticmethod
543+
def allow_missing_reference() -> str | None:
544+
return os.environ.get("MONAI_ALLOW_MISSING_REFERENCE", "1")
545+
546+
@staticmethod
547+
def extra_test_data() -> str | None:
548+
return os.environ.get("MONAI_EXTRA_TEST_DATA", "1")
549+
550+
@staticmethod
551+
def testing_algo_template() -> str | None:
552+
return os.environ.get("MONAI_TESTING_ALGO_TEMPLATE", None)
553+
530554

531555
class ImageMetaKey:
532556
"""

tests/test_monai_env_vars.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,15 +21,15 @@ class TestMONAIEnvVars(unittest.TestCase):
2121
@classmethod
2222
def setUpClass(cls):
2323
super(__class__, cls).setUpClass()
24-
cls.orig_value = os.environ.get("MONAI_DEBUG")
24+
cls.orig_value = str(MONAIEnvVars.debug())
2525

2626
@classmethod
2727
def tearDownClass(cls):
2828
if cls.orig_value is not None:
2929
os.environ["MONAI_DEBUG"] = cls.orig_value
3030
else:
3131
os.environ.pop("MONAI_DEBUG")
32-
print("MONAI debug value:", os.environ.get("MONAI_DEBUG"))
32+
print("MONAI debug value:", str(MONAIEnvVars.debug()))
3333
super(__class__, cls).tearDownClass()
3434

3535
def test_monai_env_vars(self):

tests/test_monai_utils_misc.py

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

1717
from parameterized import parameterized
1818

19-
from monai.utils.misc import check_kwargs_exist_in_class_init, run_cmd, to_tuple_of_dictionaries
19+
from monai.utils.misc import MONAIEnvVars, check_kwargs_exist_in_class_init, run_cmd, to_tuple_of_dictionaries
2020

2121
TO_TUPLE_OF_DICTIONARIES_TEST_CASES = [
2222
({}, tuple(), tuple()),
@@ -75,7 +75,7 @@ def _custom_user_function(self, cls, *args, **kwargs):
7575

7676
class TestCommandRunner(unittest.TestCase):
7777
def setUp(self):
78-
self.orig_flag = os.environ.get("MONAI_DEBUG")
78+
self.orig_flag = str(MONAIEnvVars.debug())
7979

8080
def tearDown(self):
8181
if self.orig_flag is not None:

tests/test_network_consistency.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,10 @@
2323

2424
import monai.networks.nets as nets
2525
from monai.utils import set_determinism
26+
from monai.utils.misc import MONAIEnvVars
2627
from tests.utils import assert_allclose
2728

28-
extra_test_data_dir = os.environ.get("MONAI_EXTRA_TEST_DATA")
29+
extra_test_data_dir = MONAIEnvVars.extra_test_data()
2930

3031
TESTS = []
3132
if extra_test_data_dir is not None:

tests/test_transform.py

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

1717
import monai.transforms as mt
1818
from monai.data import Dataset
19+
from monai.utils.misc import MONAIEnvVars
1920

2021

2122
class FaultyTransform(mt.Transform):
@@ -31,7 +32,7 @@ class TestTransform(unittest.TestCase):
3132
@classmethod
3233
def setUpClass(cls):
3334
super(__class__, cls).setUpClass()
34-
cls.orig_value = os.environ.get("MONAI_DEBUG")
35+
cls.orig_value = str(MONAIEnvVars.debug())
3536

3637
@classmethod
3738
def tearDownClass(cls):

0 commit comments

Comments
 (0)