Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/nbconvert/preprocessors/base.py: 42%

19 statements  

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

1"""Base class for preprocessors""" 

2 

3# Copyright (c) IPython Development Team. 

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

5 

6from traitlets import Bool 

7 

8from nbconvert.utils.base import NbConvertBase 

9 

10 

11class Preprocessor(NbConvertBase): 

12 """A configurable preprocessor 

13 

14 Inherit from this class if you wish to have configurability for your 

15 preprocessor. 

16 

17 Any configurable traitlets this class exposed will be configurable in 

18 profiles using c.SubClassName.attribute = value 

19 

20 You can overwrite `preprocess_cell()` to apply a transformation 

21 independently on each cell or `preprocess()` if you prefer your own 

22 logic. See corresponding docstring for information. 

23 

24 Disabled by default and can be enabled via the config by 

25 'c.YourPreprocessorName.enabled = True' 

26 """ 

27 

28 enabled = Bool(False).tag(config=True) 

29 

30 def __init__(self, **kw): 

31 """ 

32 Public constructor 

33 

34 Parameters 

35 ---------- 

36 config : Config 

37 Configuration file structure 

38 `**kw` 

39 Additional keyword arguments passed to parent 

40 """ 

41 

42 super().__init__(**kw) 

43 

44 def __call__(self, nb, resources): 

45 """Apply the preprocessor.""" 

46 if self.enabled: 

47 self.log.debug("Applying preprocessor: %s", self.__class__.__name__) 

48 return self.preprocess(nb, resources) 

49 else: 

50 return nb, resources 

51 

52 def preprocess(self, nb, resources): 

53 """ 

54 Preprocessing to apply on each notebook. 

55 

56 Must return modified nb, resources. 

57 

58 If you wish to apply your preprocessing to each cell, you might want 

59 to override preprocess_cell method instead. 

60 

61 Parameters 

62 ---------- 

63 nb : NotebookNode 

64 Notebook being converted 

65 resources : dictionary 

66 Additional resources used in the conversion process. Allows 

67 preprocessors to pass variables into the Jinja engine. 

68 """ 

69 for index, cell in enumerate(nb.cells): 

70 nb.cells[index], resources = self.preprocess_cell(cell, resources, index) 

71 return nb, resources 

72 

73 def preprocess_cell(self, cell, resources, index): 

74 """ 

75 Override if you want to apply some preprocessing to each cell. 

76 Must return modified cell and resource dictionary. 

77 

78 Parameters 

79 ---------- 

80 cell : NotebookNode cell 

81 Notebook cell being processed 

82 resources : dictionary 

83 Additional resources used in the conversion process. Allows 

84 preprocessors to pass variables into the Jinja engine. 

85 index : int 

86 Index of the cell being processed 

87 """ 

88 msg = "should be implemented by subclass" 

89 raise NotImplementedError(msg) 

90 return cell, resources