Skip to content

Commit a95af93

Browse files
committed
Update docs, deprecate declare_deferred_modules_as_importable
1 parent 6699fde commit a95af93

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

pyomo/common/dependencies.py

+49
Original file line numberDiff line numberDiff line change
@@ -782,6 +782,11 @@ def _perform_import(
782782
return module, False
783783

784784

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+
)
785790
def declare_deferred_modules_as_importable(globals_dict):
786791
"""Make all :py:class:`DeferredImportModules` in ``globals_dict`` importable
787792
@@ -826,6 +831,50 @@ def declare_deferred_modules_as_importable(globals_dict):
826831

827832

828833
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+
"""
829878
def __init__(self, globals_dict):
830879
self.globals_dict = globals_dict
831880
self.init_dict = {}

0 commit comments

Comments
 (0)