@@ -782,6 +782,11 @@ def _perform_import(
782
782
return module , False
783
783
784
784
785
+ @deprecated (
786
+ "declare_deferred_modules_as_importable() is dperecated. "
787
+ "Use the declare_modules_as_importable() context manager."
788
+ version = '6.7.2.dev0'
789
+ )
785
790
def declare_deferred_modules_as_importable (globals_dict ):
786
791
"""Make all :py:class:`DeferredImportModules` in ``globals_dict`` importable
787
792
@@ -826,6 +831,50 @@ def declare_deferred_modules_as_importable(globals_dict):
826
831
827
832
828
833
class declare_modules_as_importable (object ):
834
+ """Make all :py:class:`ModuleType` and :py:class:`DeferredImportModules`
835
+ importable through the ``globals_dict`` context.
836
+
837
+ This context manager will detect all modules imported into the
838
+ specified ``globals_dict`` environment (either directly or through
839
+ :py:fcn:`attempt_import`) and will make those modules importable
840
+ from the specified ``globals_dict`` context. It works by detecting
841
+ changes in the specified ``globals_dict`` dictionary and adding any new
842
+ modules or instances of :py:class:`DeferredImportModule` that it
843
+ finds (and any of their deferred submodules) to ``sys.modules`` so
844
+ that the modules can be imported through the ``globals_dict``
845
+ namespace.
846
+
847
+ For example, ``pyomo/common/dependencies.py`` declares:
848
+
849
+ .. doctest::
850
+ :hide:
851
+
852
+ >>> from pyomo.common.dependencies import (
853
+ ... attempt_import, _finalize_scipy, __dict__ as dep_globals,
854
+ ... declare_deferred_modules_as_importable, )
855
+ >>> # Sphinx does not provide a proper globals()
856
+ >>> def globals(): return dep_globals
857
+
858
+ .. doctest::
859
+
860
+ >>> with declare_modules_as_importable(globals()):
861
+ ... scipy, scipy_available = attempt_import(
862
+ ... 'scipy', callback=_finalize_scipy,
863
+ ... deferred_submodules=['stats', 'sparse', 'spatial', 'integrate'])
864
+
865
+ Which enables users to use:
866
+
867
+ .. doctest::
868
+
869
+ >>> import pyomo.common.dependencies.scipy.sparse as spa
870
+
871
+ If the deferred import has not yet been triggered, then the
872
+ :py:class:`DeferredImportModule` is returned and named ``spa``.
873
+ However, if the import has already been triggered, then ``spa`` will
874
+ either be the ``scipy.sparse`` module, or a
875
+ :py:class:`ModuleUnavailable` instance.
876
+
877
+ """
829
878
def __init__ (self , globals_dict ):
830
879
self .globals_dict = globals_dict
831
880
self .init_dict = {}
0 commit comments