|
8 | 8 |
|
9 | 9 | import functools
|
10 | 10 | from importlib import import_module
|
| 11 | +from importlib.util import find_spec |
11 | 12 | from typing import Literal
|
12 | 13 |
|
13 | 14 | import numpy as np
|
@@ -194,26 +195,32 @@ def _fn(*args, **kwargs):
|
194 | 195 | else:
|
195 | 196 | # first try to import the module
|
196 | 197 | if tidy3d_extras["mod"] is None:
|
197 |
| - try: |
198 |
| - import tidy3d_extras as tidy3d_extras_mod |
199 |
| - |
200 |
| - except ImportError as exc: |
201 |
| - tidy3d_extras["mod"] = None |
202 |
| - tidy3d_extras["use_local_subpixel"] = False |
203 |
| - if config.use_local_subpixel is True: |
| 198 | + tidy3d_extras["use_local_subpixel"] = False |
| 199 | + module_exists = find_spec("tidy3d_extras") is not None |
| 200 | + if config.use_local_subpixel is True and not module_exists: |
| 201 | + raise Tidy3dImportError( |
| 202 | + "The package 'tidy3d-extras' is required for this " |
| 203 | + "operation when 'config.use_local_subpixel' is 'True'. " |
| 204 | + "Please install the 'tidy3d-extras' package using, for " |
| 205 | + "example, 'pip install tidy3d[extras]'." |
| 206 | + ) |
| 207 | + |
| 208 | + if module_exists: |
| 209 | + try: |
| 210 | + import tidy3d_extras as tidy3d_extras_mod |
| 211 | + |
| 212 | + except ImportError as exc: |
| 213 | + # this should not happen; if the API key is invalid, |
| 214 | + # the package should still import but the version will be None |
204 | 215 | raise Tidy3dImportError(
|
205 |
| - "The package 'tidy3d-extras' is required for this " |
206 |
| - "operation when 'config.use_local_subpixel' is 'True'. " |
207 |
| - "Please install the 'tidy3d-extras' package using, for " |
208 |
| - "example, 'pip install tidy3d[extras]'." |
| 216 | + "The package 'tidy3d-extras' did not initialize correctly. " |
| 217 | + "To suppress this error, you can set " |
| 218 | + "'config.use_local_subpixel=False'." |
209 | 219 | ) from exc
|
210 | 220 |
|
211 |
| - else: |
212 | 221 | version = tidy3d_extras_mod.__version__
|
213 | 222 |
|
214 | 223 | if version is None:
|
215 |
| - tidy3d_extras["mod"] = None |
216 |
| - tidy3d_extras["use_local_subpixel"] = False |
217 | 224 | raise Tidy3dImportError(
|
218 | 225 | "The package 'tidy3d-extras' did not initialize correctly, "
|
219 | 226 | "likely due to an invalid API key. To suppress this error, "
|
@@ -245,8 +252,9 @@ def disable_local_subpixel(fn):
|
245 | 252 | def _fn(*args, **kwargs):
|
246 | 253 | use_local_subpixel = config.use_local_subpixel
|
247 | 254 | config.use_local_subpixel = False
|
248 |
| - result = fn(*args, **kwargs) |
249 |
| - config.use_local_subpixel = use_local_subpixel |
250 |
| - return result |
| 255 | + try: |
| 256 | + return fn(*args, **kwargs) |
| 257 | + finally: |
| 258 | + config.use_local_subpixel = use_local_subpixel |
251 | 259 |
|
252 | 260 | return _fn
|
0 commit comments