Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/nbformat/__init__.py: 33%

57 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-06-03 06:10 +0000

1"""The Jupyter notebook format 

2 

3Use this module to read or write notebook files as particular nbformat versions. 

4""" 

5 

6# Copyright (c) IPython Development Team. 

7# Distributed under the terms of the Modified BSD License. 

8 

9from traitlets.log import get_logger 

10 

11from . import v1, v2, v3, v4 

12from ._version import __version__, version_info 

13from .sentinel import Sentinel 

14 

15__all__ = [ 

16 "versions", 

17 "validate", 

18 "ValidationError", 

19 "convert", 

20 "from_dict", 

21 "NotebookNode", 

22 "current_nbformat", 

23 "current_nbformat_minor", 

24 "NBFormatError", 

25 "NO_CONVERT", 

26 "reads", 

27 "read", 

28 "writes", 

29 "write", 

30 "version_info", 

31 "__version__", 

32 "Sentinel", 

33] 

34 

35versions = { 

36 1: v1, 

37 2: v2, 

38 3: v3, 

39 4: v4, 

40} 

41 

42from . import reader # noqa 

43from .converter import convert # noqa 

44from .notebooknode import NotebookNode, from_dict # noqa 

45from .v4 import nbformat as current_nbformat # noqa 

46from .v4 import nbformat_minor as current_nbformat_minor # noqa 

47from .validator import ValidationError, validate # noqa 

48 

49 

50class NBFormatError(ValueError): 

51 pass 

52 

53 

54# no-conversion singleton 

55NO_CONVERT = Sentinel( 

56 "NO_CONVERT", 

57 __name__, 

58 """Value to prevent nbformat to convert notebooks to most recent version. 

59 """, 

60) 

61 

62 

63def reads(s, as_version, capture_validation_error=None, **kwargs): 

64 """Read a notebook from a string and return the NotebookNode object as the given version. 

65 

66 The string can contain a notebook of any version. 

67 The notebook will be returned `as_version`, converting, if necessary. 

68 

69 Notebook format errors will be logged. 

70 

71 Parameters 

72 ---------- 

73 s : unicode 

74 The raw unicode string to read the notebook from. 

75 as_version : int 

76 The version of the notebook format to return. 

77 The notebook will be converted, if necessary. 

78 Pass nbformat.NO_CONVERT to prevent conversion. 

79 capture_validation_error : dict, optional 

80 If provided, a key of "ValidationError" with a 

81 value of the ValidationError instance will be added 

82 to the dictionary. 

83 

84 Returns 

85 ------- 

86 nb : NotebookNode 

87 The notebook that was read. 

88 """ 

89 nb = reader.reads(s, **kwargs) 

90 if as_version is not NO_CONVERT: 

91 nb = convert(nb, as_version) 

92 try: 

93 validate(nb) 

94 except ValidationError as e: 

95 get_logger().error("Notebook JSON is invalid: %s", e) 

96 if isinstance(capture_validation_error, dict): 

97 capture_validation_error["ValidationError"] = e 

98 return nb 

99 

100 

101def writes(nb, version=NO_CONVERT, capture_validation_error=None, **kwargs): 

102 """Write a notebook to a string in a given format in the given nbformat version. 

103 

104 Any notebook format errors will be logged. 

105 

106 Parameters 

107 ---------- 

108 nb : NotebookNode 

109 The notebook to write. 

110 version : int, optional 

111 The nbformat version to write. 

112 If unspecified, or specified as nbformat.NO_CONVERT, 

113 the notebook's own version will be used and no conversion performed. 

114 capture_validation_error : dict, optional 

115 If provided, a key of "ValidationError" with a 

116 value of the ValidationError instance will be added 

117 to the dictionary. 

118 

119 Returns 

120 ------- 

121 s : unicode 

122 The notebook as a JSON string. 

123 """ 

124 if version is not NO_CONVERT: 

125 nb = convert(nb, version) 

126 else: 

127 version, _ = reader.get_version(nb) 

128 try: 

129 validate(nb) 

130 except ValidationError as e: 

131 get_logger().error("Notebook JSON is invalid: %s", e) 

132 if isinstance(capture_validation_error, dict): 

133 capture_validation_error["ValidationError"] = e 

134 return versions[version].writes_json(nb, **kwargs) 

135 

136 

137def read(fp, as_version, capture_validation_error=None, **kwargs): 

138 """Read a notebook from a file as a NotebookNode of the given version. 

139 

140 The string can contain a notebook of any version. 

141 The notebook will be returned `as_version`, converting, if necessary. 

142 

143 Notebook format errors will be logged. 

144 

145 Parameters 

146 ---------- 

147 fp : file or str 

148 A file-like object with a read method that returns unicode (use 

149 ``io.open()`` in Python 2), or a path to a file. 

150 as_version : int 

151 The version of the notebook format to return. 

152 The notebook will be converted, if necessary. 

153 Pass nbformat.NO_CONVERT to prevent conversion. 

154 capture_validation_error : dict, optional 

155 If provided, a key of "ValidationError" with a 

156 value of the ValidationError instance will be added 

157 to the dictionary. 

158 

159 Returns 

160 ------- 

161 nb : NotebookNode 

162 The notebook that was read. 

163 """ 

164 

165 try: 

166 buf = fp.read() 

167 except AttributeError: 

168 with open(fp, encoding="utf-8") as f: 

169 return reads(f.read(), as_version, capture_validation_error, **kwargs) 

170 

171 return reads(buf, as_version, capture_validation_error, **kwargs) 

172 

173 

174def write(nb, fp, version=NO_CONVERT, capture_validation_error=None, **kwargs): 

175 """Write a notebook to a file in a given nbformat version. 

176 

177 The file-like object must accept unicode input. 

178 

179 Parameters 

180 ---------- 

181 nb : NotebookNode 

182 The notebook to write. 

183 fp : file or str 

184 Any file-like object with a write method that accepts unicode, or 

185 a path to write a file. 

186 version : int, optional 

187 The nbformat version to write. 

188 If nb is not this version, it will be converted. 

189 If unspecified, or specified as nbformat.NO_CONVERT, 

190 the notebook's own version will be used and no conversion performed. 

191 capture_validation_error : dict, optional 

192 If provided, a key of "ValidationError" with a 

193 value of the ValidationError instance will be added 

194 to the dictionary. 

195 """ 

196 s = writes(nb, version, capture_validation_error, **kwargs) 

197 if isinstance(s, bytes): 

198 s = s.decode("utf8") 

199 

200 try: 

201 fp.write(s) 

202 if not s.endswith("\n"): 

203 fp.write("\n") 

204 except AttributeError: 

205 with open(fp, "w", encoding="utf-8") as f: 

206 f.write(s) 

207 if not s.endswith("\n"): 

208 f.write("\n")