extensions.py 5.6 KB

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