We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Preventing imports of all monai submodules
When importing monai in any way, all submodules are automatically made available, e.g.:
`import monai` results in the root level `import transforms` being suddenly possible (instead of needing `from monai import transforms`)

This seems to me like undesirable behavior: any project that has a **local** `transforms` submodule is suddenly unable to import it, because this results in a name conflict with the imported monai modules.
When looking at any other package, similar behavior doesn't occur: after performing `import torch`, one doesn't expect `import utils` to import `torch.utils`(!)

To conclude:
--- Current (undesirable) situation ---
```python
import monai
import transforms  # no error

# do something with transforms
# e.g. transforms.Compose([...])
```

--- Desired situation ---
```python
import monai

# do something with transforms
# e.g. monai.transforms.Compose([...])
```
Or, with specific import:
```python
from monai import transforms

# do something with transforms
# e.g. transforms.Compose([...])
```
And when no local module is present:
```python
import monai
import transforms
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'transforms'
```

The same holds for all monai submodules (`utils`, `metrics`, `losses`, etc.)


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `monai/utils/module.py`
Content:
```
1 # Copyright 2020 MONAI Consortium
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at
5 #     http://www.apache.org/licenses/LICENSE-2.0
6 # Unless required by applicable law or agreed to in writing, software
7 # distributed under the License is distributed on an "AS IS" BASIS,
8 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9 # See the License for the specific language governing permissions and
10 # limitations under the License.
11 
12 from importlib import import_module
13 from pkgutil import walk_packages
14 from re import match
15 from typing import Any, Callable, Tuple
16 
17 OPTIONAL_IMPORT_MSG_FMT = "{}"
18 
19 
20 def export(modname):
21     """
22     Make the decorated object a member of the named module. This will also add the object under its aliases if it has
23     a `__aliases__` member, thus this decorator should be before the `alias` decorator to pick up those names. Alias
24     names which conflict with package names or existing members will be ignored.
25     """
26 
27     def _inner(obj):
28         mod = import_module(modname)
29         if not hasattr(mod, obj.__name__):
30             setattr(mod, obj.__name__, obj)
31 
32             # add the aliases for `obj` to the target module
33             for alias in getattr(obj, "__aliases__", ()):
34                 if not hasattr(mod, alias):
35                     setattr(mod, alias, obj)
36 
37         return obj
38 
39     return _inner
40 
41 
42 def load_submodules(basemod, load_all: bool = True, exclude_pattern: str = "(.*[tT]est.*)|(_.*)"):
43     """
44     Traverse the source of the module structure starting with module `basemod`, loading all packages plus all files if
45     `loadAll` is True, excluding anything whose name matches `excludePattern`.
46     """
47     submodules = []
48 
49     for importer, name, is_pkg in walk_packages(basemod.__path__):
50         if (is_pkg or load_all) and match(exclude_pattern, name) is None:
51             mod = import_module(basemod.__name__ + "." + name)  # why do I need to do this first?
52             importer.find_module(name).load_module(name)
53             submodules.append(mod)
54 
55     return submodules
56 
57 
58 @export("monai.utils")
59 def get_full_type_name(typeobj):
60     module = typeobj.__module__
61     if module is None or module == str.__class__.__module__:
62         return typeobj.__name__  # Avoid reporting __builtin__
63     else:
64         return module + "." + typeobj.__name__
65 
66 
67 def min_version(the_module, min_version_str: str = "") -> bool:
68     """
69     Convert version strings into tuples of int and compare them.
70 
71     Returns True if the module's version is greater or equal to the 'min_version'.
72     When min_version_str is not provided, it always returns True.
73     """
74     if min_version_str:
75         mod_version = tuple(int(x) for x in the_module.__version__.split(".")[:2])
76         required = tuple(int(x) for x in min_version_str.split(".")[:2])
77         return mod_version >= required
78     return True  # always valid version
79 
80 
81 def exact_version(the_module, version_str: str = "") -> bool:
82     """
83     Returns True if the module's __version__ matches version_str
84     """
85     return bool(the_module.__version__ == version_str)
86 
87 
88 def optional_import(
89     module: str,
90     version: str = "",
91     version_checker: Callable[..., bool] = min_version,
92     name: str = "",
93     descriptor: str = OPTIONAL_IMPORT_MSG_FMT,
94     version_args=None,
95     allow_namespace_pkg: bool = False,
96 ) -> Tuple[Any, bool]:
97     """
98     Imports an optional module specified by `module` string.
99     Any importing related exceptions will be stored, and exceptions raise lazily
100     when attempting to use the failed-to-import module.
101 
102     Args:
103         module: name of the module to be imported.
104         version: version string used by the version_checker.
105         version_checker: a callable to check the module version, Defaults to monai.utils.min_version.
106         name: a non-module attribute (such as method/class) to import from the imported module.
107         descriptor: a format string for the final error message when using a not imported module.
108         version_args: additional parameters to the version checker.
109         allow_namespace_pkg: whether importing a namespace package is allowed. Defaults to False.
110 
111     Returns:
112         The imported module and a boolean flag indicating whether the import is successful.
113 
114     Examples::
115 
116         >>> torch, flag = optional_import('torch', '1.1')
117         >>> print(torch, flag)
118         <module 'torch' from 'python/lib/python3.6/site-packages/torch/__init__.py'> True
119 
120         >>> the_module, flag = optional_import('unknown_module')
121         >>> print(flag)
122         False
123         >>> the_module.method  # trying to access a module which is not imported
124         AttributeError: Optional import: import unknown_module (No module named 'unknown_module').
125 
126         >>> torch, flag = optional_import('torch', '42', exact_version)
127         >>> torch.nn  # trying to access a module for which there isn't a proper version imported
128         AttributeError: Optional import: import torch (requires version '42' by 'exact_version').
129 
130         >>> conv, flag = optional_import('torch.nn.functional', '1.0', name='conv1d')
131         >>> print(conv)
132         <built-in method conv1d of type object at 0x11a49eac0>
133 
134         >>> conv, flag = optional_import('torch.nn.functional', '42', name='conv1d')
135         >>> conv()  # trying to use a function from the not successfully imported module (due to unmatched version)
136         AttributeError: Optional import: from torch.nn.functional import conv1d (requires version '42' by 'min_version').
137     """
138 
139     tb = None
140     exception_str = ""
141     if name:
142         actual_cmd = f"from {module} import {name}"
143     else:
144         actual_cmd = f"import {module}"
145     try:
146         pkg = __import__(module)  # top level module
147         the_module = import_module(module)
148         if not allow_namespace_pkg:
149             is_namespace = getattr(the_module, "__file__", None) is None and hasattr(the_module, "__path__")
150             assert not is_namespace
151         if name:  # user specified to load class/function/... from the module
152             the_module = getattr(the_module, name)
153     except Exception as import_exception:  # any exceptions during import
154         tb = import_exception.__traceback__
155         exception_str = f"{import_exception}"
156     else:  # found the module
157         if version_args and version_checker(pkg, f"{version}", version_args):
158             return the_module, True
159         if not version_args and version_checker(pkg, f"{version}"):
160             return the_module, True
161 
162     # preparing lazy error message
163     msg = descriptor.format(actual_cmd)
164     if version and tb is None:  # a pure version issue
165         msg += f" (requires '{module} {version}' by '{version_checker.__name__}')"
166     if exception_str:
167         msg += f" ({exception_str})"
168 
169     class _LazyRaise:
170         def __init__(self, *_args, **_kwargs):
171             _default_msg = (
172                 f"Optional import: {msg}."
173                 + "\n\nFor details about installing the optional dependencies, please visit:"
174                 + "\n    https://docs.monai.io/en/latest/installation.html#installing-the-recommended-dependencies"
175             )
176             if tb is None:
177                 self._exception = AttributeError(_default_msg)
178             else:
179                 self._exception = AttributeError(_default_msg).with_traceback(tb)
180 
181         def __getattr__(self, name):
182             """
183             Raises:
184                 AttributeError: When you call this method.
185             """
186             raise self._exception
187 
188         def __call__(self, *_args, **_kwargs):
189             """
190             Raises:
191                 AttributeError: When you call this method.
192             """
193             raise self._exception
194 
195     return _LazyRaise(), False
196
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/monai/utils/module.py b/monai/utils/module.py
--- a/monai/utils/module.py
+++ b/monai/utils/module.py
@@ -9,6 +9,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
+import sys
 from importlib import import_module
 from pkgutil import walk_packages
 from re import match
@@ -42,20 +43,19 @@
 def load_submodules(basemod, load_all: bool = True, exclude_pattern: str = "(.*[tT]est.*)|(_.*)"):
     """
     Traverse the source of the module structure starting with module `basemod`, loading all packages plus all files if
-    `loadAll` is True, excluding anything whose name matches `excludePattern`.
+    `load_all` is True, excluding anything whose name matches `exclude_pattern`.
     """
     submodules = []
 
-    for importer, name, is_pkg in walk_packages(basemod.__path__):
-        if (is_pkg or load_all) and match(exclude_pattern, name) is None:
-            mod = import_module(basemod.__name__ + "." + name)  # why do I need to do this first?
+    for importer, name, is_pkg in walk_packages(basemod.__path__, prefix=basemod.__name__ + "."):
+        if (is_pkg or load_all) and name not in sys.modules and match(exclude_pattern, name) is None:
+            mod = import_module(name)
             importer.find_module(name).load_module(name)
             submodules.append(mod)
 
     return submodules
 
 
-@export("monai.utils")
 def get_full_type_name(typeobj):
     module = typeobj.__module__
     if module is None or module == str.__class__.__module__:

{"golden_diff": "diff --git a/monai/utils/module.py b/monai/utils/module.py\n--- a/monai/utils/module.py\n+++ b/monai/utils/module.py\n@@ -9,6 +9,7 @@\n # See the License for the specific language governing permissions and\n # limitations under the License.\n \n+import sys\n from importlib import import_module\n from pkgutil import walk_packages\n from re import match\n@@ -42,20 +43,19 @@\n def load_submodules(basemod, load_all: bool = True, exclude_pattern: str = \"(.*[tT]est.*)|(_.*)\"):\n     \"\"\"\n     Traverse the source of the module structure starting with module `basemod`, loading all packages plus all files if\n-    `loadAll` is True, excluding anything whose name matches `excludePattern`.\n+    `load_all` is True, excluding anything whose name matches `exclude_pattern`.\n     \"\"\"\n     submodules = []\n \n-    for importer, name, is_pkg in walk_packages(basemod.__path__):\n-        if (is_pkg or load_all) and match(exclude_pattern, name) is None:\n-            mod = import_module(basemod.__name__ + \".\" + name)  # why do I need to do this first?\n+    for importer, name, is_pkg in walk_packages(basemod.__path__, prefix=basemod.__name__ + \".\"):\n+        if (is_pkg or load_all) and name not in sys.modules and match(exclude_pattern, name) is None:\n+            mod = import_module(name)\n             importer.find_module(name).load_module(name)\n             submodules.append(mod)\n \n     return submodules\n \n \n-@export(\"monai.utils\")\n def get_full_type_name(typeobj):\n     module = typeobj.__module__\n     if module is None or module == str.__class__.__module__:\n", "issue": "Preventing imports of all monai submodules\nWhen importing monai in any way, all submodules are automatically made available, e.g.:\r\n`import monai` results in the root level `import transforms` being suddenly possible (instead of needing `from monai import transforms`)\r\n\r\nThis seems to me like undesirable behavior: any project that has a **local** `transforms` submodule is suddenly unable to import it, because this results in a name conflict with the imported monai modules.\r\nWhen looking at any other package, similar behavior doesn't occur: after performing `import torch`, one doesn't expect `import utils` to import `torch.utils`(!)\r\n\r\nTo conclude:\r\n--- Current (undesirable) situation ---\r\n```python\r\nimport monai\r\nimport transforms  # no error\r\n\r\n# do something with transforms\r\n# e.g. transforms.Compose([...])\r\n```\r\n\r\n--- Desired situation ---\r\n```python\r\nimport monai\r\n\r\n# do something with transforms\r\n# e.g. monai.transforms.Compose([...])\r\n```\r\nOr, with specific import:\r\n```python\r\nfrom monai import transforms\r\n\r\n# do something with transforms\r\n# e.g. transforms.Compose([...])\r\n```\r\nAnd when no local module is present:\r\n```python\r\nimport monai\r\nimport transforms\r\nTraceback (most recent call last):\r\n  File \"<stdin>\", line 1, in <module>\r\nModuleNotFoundError: No module named 'transforms'\r\n```\r\n\r\nThe same holds for all monai submodules (`utils`, `metrics`, `losses`, etc.)\r\n\n", "before_files": [{"content": "# Copyright 2020 MONAI Consortium\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#     http://www.apache.org/licenses/LICENSE-2.0\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom importlib import import_module\nfrom pkgutil import walk_packages\nfrom re import match\nfrom typing import Any, Callable, Tuple\n\nOPTIONAL_IMPORT_MSG_FMT = \"{}\"\n\n\ndef export(modname):\n    \"\"\"\n    Make the decorated object a member of the named module. This will also add the object under its aliases if it has\n    a `__aliases__` member, thus this decorator should be before the `alias` decorator to pick up those names. Alias\n    names which conflict with package names or existing members will be ignored.\n    \"\"\"\n\n    def _inner(obj):\n        mod = import_module(modname)\n        if not hasattr(mod, obj.__name__):\n            setattr(mod, obj.__name__, obj)\n\n            # add the aliases for `obj` to the target module\n            for alias in getattr(obj, \"__aliases__\", ()):\n                if not hasattr(mod, alias):\n                    setattr(mod, alias, obj)\n\n        return obj\n\n    return _inner\n\n\ndef load_submodules(basemod, load_all: bool = True, exclude_pattern: str = \"(.*[tT]est.*)|(_.*)\"):\n    \"\"\"\n    Traverse the source of the module structure starting with module `basemod`, loading all packages plus all files if\n    `loadAll` is True, excluding anything whose name matches `excludePattern`.\n    \"\"\"\n    submodules = []\n\n    for importer, name, is_pkg in walk_packages(basemod.__path__):\n        if (is_pkg or load_all) and match(exclude_pattern, name) is None:\n            mod = import_module(basemod.__name__ + \".\" + name)  # why do I need to do this first?\n            importer.find_module(name).load_module(name)\n            submodules.append(mod)\n\n    return submodules\n\n\n@export(\"monai.utils\")\ndef get_full_type_name(typeobj):\n    module = typeobj.__module__\n    if module is None or module == str.__class__.__module__:\n        return typeobj.__name__  # Avoid reporting __builtin__\n    else:\n        return module + \".\" + typeobj.__name__\n\n\ndef min_version(the_module, min_version_str: str = \"\") -> bool:\n    \"\"\"\n    Convert version strings into tuples of int and compare them.\n\n    Returns True if the module's version is greater or equal to the 'min_version'.\n    When min_version_str is not provided, it always returns True.\n    \"\"\"\n    if min_version_str:\n        mod_version = tuple(int(x) for x in the_module.__version__.split(\".\")[:2])\n        required = tuple(int(x) for x in min_version_str.split(\".\")[:2])\n        return mod_version >= required\n    return True  # always valid version\n\n\ndef exact_version(the_module, version_str: str = \"\") -> bool:\n    \"\"\"\n    Returns True if the module's __version__ matches version_str\n    \"\"\"\n    return bool(the_module.__version__ == version_str)\n\n\ndef optional_import(\n    module: str,\n    version: str = \"\",\n    version_checker: Callable[..., bool] = min_version,\n    name: str = \"\",\n    descriptor: str = OPTIONAL_IMPORT_MSG_FMT,\n    version_args=None,\n    allow_namespace_pkg: bool = False,\n) -> Tuple[Any, bool]:\n    \"\"\"\n    Imports an optional module specified by `module` string.\n    Any importing related exceptions will be stored, and exceptions raise lazily\n    when attempting to use the failed-to-import module.\n\n    Args:\n        module: name of the module to be imported.\n        version: version string used by the version_checker.\n        version_checker: a callable to check the module version, Defaults to monai.utils.min_version.\n        name: a non-module attribute (such as method/class) to import from the imported module.\n        descriptor: a format string for the final error message when using a not imported module.\n        version_args: additional parameters to the version checker.\n        allow_namespace_pkg: whether importing a namespace package is allowed. Defaults to False.\n\n    Returns:\n        The imported module and a boolean flag indicating whether the import is successful.\n\n    Examples::\n\n        >>> torch, flag = optional_import('torch', '1.1')\n        >>> print(torch, flag)\n        <module 'torch' from 'python/lib/python3.6/site-packages/torch/__init__.py'> True\n\n        >>> the_module, flag = optional_import('unknown_module')\n        >>> print(flag)\n        False\n        >>> the_module.method  # trying to access a module which is not imported\n        AttributeError: Optional import: import unknown_module (No module named 'unknown_module').\n\n        >>> torch, flag = optional_import('torch', '42', exact_version)\n        >>> torch.nn  # trying to access a module for which there isn't a proper version imported\n        AttributeError: Optional import: import torch (requires version '42' by 'exact_version').\n\n        >>> conv, flag = optional_import('torch.nn.functional', '1.0', name='conv1d')\n        >>> print(conv)\n        <built-in method conv1d of type object at 0x11a49eac0>\n\n        >>> conv, flag = optional_import('torch.nn.functional', '42', name='conv1d')\n        >>> conv()  # trying to use a function from the not successfully imported module (due to unmatched version)\n        AttributeError: Optional import: from torch.nn.functional import conv1d (requires version '42' by 'min_version').\n    \"\"\"\n\n    tb = None\n    exception_str = \"\"\n    if name:\n        actual_cmd = f\"from {module} import {name}\"\n    else:\n        actual_cmd = f\"import {module}\"\n    try:\n        pkg = __import__(module)  # top level module\n        the_module = import_module(module)\n        if not allow_namespace_pkg:\n            is_namespace = getattr(the_module, \"__file__\", None) is None and hasattr(the_module, \"__path__\")\n            assert not is_namespace\n        if name:  # user specified to load class/function/... from the module\n            the_module = getattr(the_module, name)\n    except Exception as import_exception:  # any exceptions during import\n        tb = import_exception.__traceback__\n        exception_str = f\"{import_exception}\"\n    else:  # found the module\n        if version_args and version_checker(pkg, f\"{version}\", version_args):\n            return the_module, True\n        if not version_args and version_checker(pkg, f\"{version}\"):\n            return the_module, True\n\n    # preparing lazy error message\n    msg = descriptor.format(actual_cmd)\n    if version and tb is None:  # a pure version issue\n        msg += f\" (requires '{module} {version}' by '{version_checker.__name__}')\"\n    if exception_str:\n        msg += f\" ({exception_str})\"\n\n    class _LazyRaise:\n        def __init__(self, *_args, **_kwargs):\n            _default_msg = (\n                f\"Optional import: {msg}.\"\n                + \"\\n\\nFor details about installing the optional dependencies, please visit:\"\n                + \"\\n    https://docs.monai.io/en/latest/installation.html#installing-the-recommended-dependencies\"\n            )\n            if tb is None:\n                self._exception = AttributeError(_default_msg)\n            else:\n                self._exception = AttributeError(_default_msg).with_traceback(tb)\n\n        def __getattr__(self, name):\n            \"\"\"\n            Raises:\n                AttributeError: When you call this method.\n            \"\"\"\n            raise self._exception\n\n        def __call__(self, *_args, **_kwargs):\n            \"\"\"\n            Raises:\n                AttributeError: When you call this method.\n            \"\"\"\n            raise self._exception\n\n    return _LazyRaise(), False\n", "path": "monai/utils/module.py"}], "after_files": [{"content": "# Copyright 2020 MONAI Consortium\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#     http://www.apache.org/licenses/LICENSE-2.0\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport sys\nfrom importlib import import_module\nfrom pkgutil import walk_packages\nfrom re import match\nfrom typing import Any, Callable, Tuple\n\nOPTIONAL_IMPORT_MSG_FMT = \"{}\"\n\n\ndef export(modname):\n    \"\"\"\n    Make the decorated object a member of the named module. This will also add the object under its aliases if it has\n    a `__aliases__` member, thus this decorator should be before the `alias` decorator to pick up those names. Alias\n    names which conflict with package names or existing members will be ignored.\n    \"\"\"\n\n    def _inner(obj):\n        mod = import_module(modname)\n        if not hasattr(mod, obj.__name__):\n            setattr(mod, obj.__name__, obj)\n\n            # add the aliases for `obj` to the target module\n            for alias in getattr(obj, \"__aliases__\", ()):\n                if not hasattr(mod, alias):\n                    setattr(mod, alias, obj)\n\n        return obj\n\n    return _inner\n\n\ndef load_submodules(basemod, load_all: bool = True, exclude_pattern: str = \"(.*[tT]est.*)|(_.*)\"):\n    \"\"\"\n    Traverse the source of the module structure starting with module `basemod`, loading all packages plus all files if\n    `load_all` is True, excluding anything whose name matches `exclude_pattern`.\n    \"\"\"\n    submodules = []\n\n    for importer, name, is_pkg in walk_packages(basemod.__path__, prefix=basemod.__name__ + \".\"):\n        if (is_pkg or load_all) and name not in sys.modules and match(exclude_pattern, name) is None:\n            mod = import_module(name)\n            importer.find_module(name).load_module(name)\n            submodules.append(mod)\n\n    return submodules\n\n\ndef get_full_type_name(typeobj):\n    module = typeobj.__module__\n    if module is None or module == str.__class__.__module__:\n        return typeobj.__name__  # Avoid reporting __builtin__\n    else:\n        return module + \".\" + typeobj.__name__\n\n\ndef min_version(the_module, min_version_str: str = \"\") -> bool:\n    \"\"\"\n    Convert version strings into tuples of int and compare them.\n\n    Returns True if the module's version is greater or equal to the 'min_version'.\n    When min_version_str is not provided, it always returns True.\n    \"\"\"\n    if min_version_str:\n        mod_version = tuple(int(x) for x in the_module.__version__.split(\".\")[:2])\n        required = tuple(int(x) for x in min_version_str.split(\".\")[:2])\n        return mod_version >= required\n    return True  # always valid version\n\n\ndef exact_version(the_module, version_str: str = \"\") -> bool:\n    \"\"\"\n    Returns True if the module's __version__ matches version_str\n    \"\"\"\n    return bool(the_module.__version__ == version_str)\n\n\ndef optional_import(\n    module: str,\n    version: str = \"\",\n    version_checker: Callable[..., bool] = min_version,\n    name: str = \"\",\n    descriptor: str = OPTIONAL_IMPORT_MSG_FMT,\n    version_args=None,\n    allow_namespace_pkg: bool = False,\n) -> Tuple[Any, bool]:\n    \"\"\"\n    Imports an optional module specified by `module` string.\n    Any importing related exceptions will be stored, and exceptions raise lazily\n    when attempting to use the failed-to-import module.\n\n    Args:\n        module: name of the module to be imported.\n        version: version string used by the version_checker.\n        version_checker: a callable to check the module version, Defaults to monai.utils.min_version.\n        name: a non-module attribute (such as method/class) to import from the imported module.\n        descriptor: a format string for the final error message when using a not imported module.\n        version_args: additional parameters to the version checker.\n        allow_namespace_pkg: whether importing a namespace package is allowed. Defaults to False.\n\n    Returns:\n        The imported module and a boolean flag indicating whether the import is successful.\n\n    Examples::\n\n        >>> torch, flag = optional_import('torch', '1.1')\n        >>> print(torch, flag)\n        <module 'torch' from 'python/lib/python3.6/site-packages/torch/__init__.py'> True\n\n        >>> the_module, flag = optional_import('unknown_module')\n        >>> print(flag)\n        False\n        >>> the_module.method  # trying to access a module which is not imported\n        AttributeError: Optional import: import unknown_module (No module named 'unknown_module').\n\n        >>> torch, flag = optional_import('torch', '42', exact_version)\n        >>> torch.nn  # trying to access a module for which there isn't a proper version imported\n        AttributeError: Optional import: import torch (requires version '42' by 'exact_version').\n\n        >>> conv, flag = optional_import('torch.nn.functional', '1.0', name='conv1d')\n        >>> print(conv)\n        <built-in method conv1d of type object at 0x11a49eac0>\n\n        >>> conv, flag = optional_import('torch.nn.functional', '42', name='conv1d')\n        >>> conv()  # trying to use a function from the not successfully imported module (due to unmatched version)\n        AttributeError: Optional import: from torch.nn.functional import conv1d (requires version '42' by 'min_version').\n    \"\"\"\n\n    tb = None\n    exception_str = \"\"\n    if name:\n        actual_cmd = f\"from {module} import {name}\"\n    else:\n        actual_cmd = f\"import {module}\"\n    try:\n        pkg = __import__(module)  # top level module\n        the_module = import_module(module)\n        if not allow_namespace_pkg:\n            is_namespace = getattr(the_module, \"__file__\", None) is None and hasattr(the_module, \"__path__\")\n            assert not is_namespace\n        if name:  # user specified to load class/function/... from the module\n            the_module = getattr(the_module, name)\n    except Exception as import_exception:  # any exceptions during import\n        tb = import_exception.__traceback__\n        exception_str = f\"{import_exception}\"\n    else:  # found the module\n        if version_args and version_checker(pkg, f\"{version}\", version_args):\n            return the_module, True\n        if not version_args and version_checker(pkg, f\"{version}\"):\n            return the_module, True\n\n    # preparing lazy error message\n    msg = descriptor.format(actual_cmd)\n    if version and tb is None:  # a pure version issue\n        msg += f\" (requires '{module} {version}' by '{version_checker.__name__}')\"\n    if exception_str:\n        msg += f\" ({exception_str})\"\n\n    class _LazyRaise:\n        def __init__(self, *_args, **_kwargs):\n            _default_msg = (\n                f\"Optional import: {msg}.\"\n                + \"\\n\\nFor details about installing the optional dependencies, please visit:\"\n                + \"\\n    https://docs.monai.io/en/latest/installation.html#installing-the-recommended-dependencies\"\n            )\n            if tb is None:\n                self._exception = AttributeError(_default_msg)\n            else:\n                self._exception = AttributeError(_default_msg).with_traceback(tb)\n\n        def __getattr__(self, name):\n            \"\"\"\n            Raises:\n                AttributeError: When you call this method.\n            \"\"\"\n            raise self._exception\n\n        def __call__(self, *_args, **_kwargs):\n            \"\"\"\n            Raises:\n                AttributeError: When you call this method.\n            \"\"\"\n            raise self._exception\n\n    return _LazyRaise(), False\n", "path": "monai/utils/module.py"}]}