Skip to content

Commit c47d63f

Browse files
committed
Strengthen tidy3d-extras packaging test
1 parent e03175a commit c47d63f

File tree

1 file changed

+25
-17
lines changed

1 file changed

+25
-17
lines changed

tidy3d/packaging.py

Lines changed: 25 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
import functools
1010
from importlib import import_module
11+
from importlib.util import find_spec
1112
from typing import Literal
1213

1314
import numpy as np
@@ -194,26 +195,32 @@ def _fn(*args, **kwargs):
194195
else:
195196
# first try to import the module
196197
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
204215
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'."
209219
) from exc
210220

211-
else:
212221
version = tidy3d_extras_mod.__version__
213222

214223
if version is None:
215-
tidy3d_extras["mod"] = None
216-
tidy3d_extras["use_local_subpixel"] = False
217224
raise Tidy3dImportError(
218225
"The package 'tidy3d-extras' did not initialize correctly, "
219226
"likely due to an invalid API key. To suppress this error, "
@@ -245,8 +252,9 @@ def disable_local_subpixel(fn):
245252
def _fn(*args, **kwargs):
246253
use_local_subpixel = config.use_local_subpixel
247254
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
251259

252260
return _fn

0 commit comments

Comments
 (0)