extensions.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. # encoding: utf-8
  2. """A class for managing IPython extensions."""
  3. # Copyright (c) IPython Development Team.
  4. # Distributed under the terms of the Modified BSD License.
  5. import os
  6. import os.path
  7. import sys
  8. from importlib import import_module, reload
  9. from traitlets.config.configurable import Configurable
  10. from IPython.utils.path import ensure_dir_exists
  11. from traitlets import Instance
  12. #-----------------------------------------------------------------------------
  13. # Main class
  14. #-----------------------------------------------------------------------------
  15. BUILTINS_EXTS = {"storemagic": False, "autoreload": False}
  16. class ExtensionManager(Configurable):
  17. """A class to manage IPython extensions.
  18. An IPython extension is an importable Python module that has
  19. a function with the signature::
  20. def load_ipython_extension(ipython):
  21. # Do things with ipython
  22. This function is called after your extension is imported and the
  23. currently active :class:`InteractiveShell` instance is passed as
  24. the only argument. You can do anything you want with IPython at
  25. that point, including defining new magic and aliases, adding new
  26. components, etc.
  27. You can also optionally define an :func:`unload_ipython_extension(ipython)`
  28. function, which will be called if the user unloads or reloads the extension.
  29. The extension manager will only call :func:`load_ipython_extension` again
  30. if the extension is reloaded.
  31. You can put your extension modules anywhere you want, as long as
  32. they can be imported by Python's standard import mechanism.
  33. """
  34. shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
  35. def __init__(self, shell=None, **kwargs):
  36. super(ExtensionManager, self).__init__(shell=shell, **kwargs)
  37. self.loaded = set()
  38. def load_extension(self, module_str: str):
  39. """Load an IPython extension by its module name.
  40. Returns the string "already loaded" if the extension is already loaded,
  41. "no load function" if the module doesn't have a load_ipython_extension
  42. function, or None if it succeeded.
  43. """
  44. try:
  45. return self._load_extension(module_str)
  46. except ModuleNotFoundError:
  47. if module_str in BUILTINS_EXTS:
  48. BUILTINS_EXTS[module_str] = True
  49. return self._load_extension("IPython.extensions." + module_str)
  50. raise
  51. def _load_extension(self, module_str: str):
  52. if module_str in self.loaded:
  53. return "already loaded"
  54. assert self.shell is not None
  55. with self.shell.builtin_trap:
  56. if module_str not in sys.modules:
  57. mod = import_module(module_str)
  58. mod = sys.modules[module_str]
  59. if self._call_load_ipython_extension(mod):
  60. self.loaded.add(module_str)
  61. else:
  62. return "no load function"
  63. def unload_extension(self, module_str: str):
  64. """Unload an IPython extension by its module name.
  65. This function looks up the extension's name in ``sys.modules`` and
  66. simply calls ``mod.unload_ipython_extension(self)``.
  67. Returns the string "no unload function" if the extension doesn't define
  68. a function to unload itself, "not loaded" if the extension isn't loaded,
  69. otherwise None.
  70. """
  71. if BUILTINS_EXTS.get(module_str, False) is True:
  72. module_str = "IPython.extensions." + module_str
  73. if module_str not in self.loaded:
  74. return "not loaded"
  75. if module_str in sys.modules:
  76. mod = sys.modules[module_str]
  77. if self._call_unload_ipython_extension(mod):
  78. self.loaded.discard(module_str)
  79. else:
  80. return "no unload function"
  81. def reload_extension(self, module_str: str):
  82. """Reload an IPython extension by calling reload.
  83. If the module has not been loaded before,
  84. :meth:`InteractiveShell.load_extension` is called. Otherwise
  85. :func:`reload` is called and then the :func:`load_ipython_extension`
  86. function of the module, if it exists is called.
  87. """
  88. if BUILTINS_EXTS.get(module_str, False) is True:
  89. module_str = "IPython.extensions." + module_str
  90. if (module_str in self.loaded) and (module_str in sys.modules):
  91. self.unload_extension(module_str)
  92. mod = sys.modules[module_str]
  93. reload(mod)
  94. if self._call_load_ipython_extension(mod):
  95. self.loaded.add(module_str)
  96. else:
  97. self.load_extension(module_str)
  98. def _call_load_ipython_extension(self, mod):
  99. if hasattr(mod, 'load_ipython_extension'):
  100. mod.load_ipython_extension(self.shell)
  101. return True
  102. def _call_unload_ipython_extension(self, mod):
  103. if hasattr(mod, 'unload_ipython_extension'):
  104. mod.unload_ipython_extension(self.shell)
  105. return True