MCPcopy Create free account
hub / github.com/ipython/ipython / ExtensionManager

Class ExtensionManager

IPython/core/extensions.py:22–150  ·  view source on GitHub ↗

A class to manage IPython extensions. An IPython extension is an importable Python module that has a function with the signature:: def load_ipython_extension(ipython): # Do things with ipython This function is called after your extension is imported and the cur

Source from the content-addressed store, hash-verified

20#-----------------------------------------------------------------------------
21
22class ExtensionManager(Configurable):
23 """A class to manage IPython extensions.
24
25 An IPython extension is an importable Python module that has
26 a function with the signature::
27
28 def load_ipython_extension(ipython):
29 # Do things with ipython
30
31 This function is called after your extension is imported and the
32 currently active :class:`InteractiveShell` instance is passed as
33 the only argument. You can do anything you want with IPython at
34 that point, including defining new magic and aliases, adding new
35 components, etc.
36
37 You can also optionally define an :func:`unload_ipython_extension(ipython)`
38 function, which will be called if the user unloads or reloads the extension.
39 The extension manager will only call :func:`load_ipython_extension` again
40 if the extension is reloaded.
41
42 You can put your extension modules anywhere you want, as long as
43 they can be imported by Python's standard import mechanism. However,
44 to make it easy to write extensions, you can also put your extensions
45 in ``os.path.join(self.ipython_dir, 'extensions')``. This directory
46 is added to ``sys.path`` automatically.
47 """
48
49 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
50
51 def __init__(self, shell=None, **kwargs):
52 super(ExtensionManager, self).__init__(shell=shell, **kwargs)
53 self.shell.observe(
54 self._on_ipython_dir_changed, names=('ipython_dir',)
55 )
56 self.loaded = set()
57
58 @property
59 def ipython_extension_dir(self):
60 return os.path.join(self.shell.ipython_dir, u'extensions')
61
62 def _on_ipython_dir_changed(self, change):
63 ensure_dir_exists(self.ipython_extension_dir)
64
65 def load_extension(self, module_str):
66 """Load an IPython extension by its module name.
67
68 Returns the string "already loaded" if the extension is already loaded,
69 "no load function" if the module doesn't have a load_ipython_extension
70 function, or None if it succeeded.
71 """
72 if module_str in self.loaded:
73 return "already loaded"
74
75 from IPython.utils.syspathcontext import prepended_to_syspath
76
77 with self.shell.builtin_trap:
78 if module_str not in sys.modules:
79 with prepended_to_syspath(self.ipython_extension_dir):

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected