The try-except-pass stanza was bothering me every time I saw it.
Turns out it was to filter out modules which are deprecated, meaning they emit a DeprecationWarning on an attribute access. Consider
In [1]: from scipy.constants import constants # deprecated submodule constants.constants
In [2]: constants.zetta # DeprecationWarning
<ipython-input-5-835b60441caf>:1: DeprecationWarning: Please import `zetta` from the `scipy.constants` namespace; the `scipy.constants.constants` namespace is deprecated and will be removed in SciPy 2.0.0.
constants.zetta
Out[5]: 1e+21
Note however that non-existent attributes still raise an AttributeError, only with a helpful error message:
In [3]: constants.tapas # non-existent attr: AttributeError w/ special error message
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[2], line 1
----> 1 constants.tapas
File ~/repos/scipy/scipy/build-install/lib/python3.10/site-packages/scipy/constants/constants.py:51, in __getattr__(name)
50 def __getattr__(name):
---> 51 return _sub_module_deprecation(sub_package="constants", module="constants",
52 private_modules=["_constants"], all=__all__,
53 attribute=name)
File ~/repos/scipy/scipy/build-install/lib/python3.10/site-packages/scipy/_lib/deprecation.py:42, in _sub_module_deprecation(sub_package, module, private_modules, all, attribute, correct_module)
39 correct_import = f"scipy.{sub_package}"
41 if attribute not in all:
---> 42 raise AttributeError(
43 f"`scipy.{sub_package}.{module}` has no attribute `{attribute}`; "
44 f"furthermore, `scipy.{sub_package}.{module}` is deprecated "
45 f"and will be removed in SciPy 2.0.0."
46 )
48 attr = getattr(import_module(correct_import), attribute, None)
50 if attr is not None:
AttributeError: `scipy.constants.constants` has no attribute `tapas`; furthermore, `scipy.constants.constants` is deprecated and will be removed in SciPy 2.0.0.
The
try-except-pass
stanza was bothering me every time I saw it.Turns out it was to filter out modules which are deprecated, meaning they emit a DeprecationWarning on an attribute access. Consider
Note however that non-existent attributes still raise an AttributeError, only with a helpful error message: