Coverage for src/importnb/ipython_extension.py: 36%

1# coding: utf-8

2"""# `importnb` Jupyter magic extensions

3"""

4

5""" %importnb --stdout --stderr --display --shell

6"""

7

8 import argparse

9 import inspect

10 from functools import partial

11 from importlib import import_module

12

13 import pkg_resources

14

15

16 def get_module_object(str):

17 module, object = str.split(":", 1)

18 return getattr(import_module(module), object)

19

20

21 parser = argparse.ArgumentParser(description="""Define the importnb loader properties.""")

22 parser.add_argument("--cls", type=get_module_object, default="importnb:Notebook")

23 parser.add_argument("--fuzzy", action="store_true")

24

25 try:

26 from IPython.core import magic_arguments

27 from IPython.core.magic import (

28 Magics,

29 cell_magic,

30 line_cell_magic,

31 line_magic,

32 magics_class,

33 )

34

35 __IPYTHON__ = True

36 except ImportError:

37 __IPYTHON__ = False

38

39

40 class ImportNbExtensionBase:

41 loaders = None

42

43 def __init__(self, shell, loader=None):

44 self.loaders = []

45 # A default loader to install

46 if loader:

47 self.loaders.append(loader(position=-1).__enter__())

48

49

50 if __IPYTHON__:

51

52 @magics_class

53 class ImportNbExtension(Magics, ImportNbExtensionBase):

54 loaders = None

55

56 def __init__(self, shell, loader=None):

57 Magics.__init__(self, shell)

58 ImportNbExtensionBase.__init__(self, shell, loader)

59

60 @line_cell_magic

61 def importnb(self, line, cell=None):

62 if line.strip() == "pop":

63 return self.pop()

64 module.__package__

65

66 details = vars(parser.parse_args(line.split()))

67 self.loaders.append(details.pop("cls")(**details))

68

69 if cell is None:

70 self.loaders[-1].__enter__()

71 return

72

73 with self.loaders.pop(-1):

74 self.parent.run_cell(cell)

75

76 def unload(self):

77 while self.loaders:

78 self.pop()

79

80 def pop(self):

81 self.loaders.pop().__exit__(None, None, None)

82

83 else:

84

85 class ImportNbExtension(ImportNbExtensionBase):

86 ...

87

88

89 manager = None

90

91

92 def IPYTHON_MAIN():

93 """Decide if the Ipython command line is running code."""

94 import pkg_resources

95

96 runner_frame = inspect.getouterframes(inspect.currentframe())[-2]

97 return (

98 getattr(runner_frame, "function", None)

99 == pkg_resources.load_entry_point("ipython", "console_scripts", "ipython").__name__

100 )

101

102

103 def load_ipython_extension(ip=None):

104 global manager, module

105 if IPYTHON_MAIN():

106 from .parameterize import Parameterize as Notebook

107 else:

108 from .loader import Notebook

109

110 # Auto loading only works in IPython and

111 # we only read need it when there are parameters.

112 manager = ImportNbExtension(ip, Notebook)

113

114 if ip:

115 ip.register_magics(manager)

116 ip.user_ns.update(__path__=[str(__import__("pathlib").Path().absolute())])

117 from .completer import load_ipython_extension

118

119 load_ipython_extension(ip)

120

121 ip.user_ns["reload"] = __import__("importlib").reload

122

123

124 def unload_ipython_extension(ip=None):

125 global manager

126 ip and manager and manager.unload()