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
« prev ^ index » next coverage.py v7.2.7, created at 2023-07-01 06:54 +0000
1"""Base class for preprocessors"""
3# Copyright (c) IPython Development Team.
4# Distributed under the terms of the Modified BSD License.
6from traitlets import Bool
8from nbconvert.utils.base import NbConvertBase
11class Preprocessor(NbConvertBase):
12 """A configurable preprocessor
14 Inherit from this class if you wish to have configurability for your
15 preprocessor.
17 Any configurable traitlets this class exposed will be configurable in
18 profiles using c.SubClassName.attribute = value
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.
24 Disabled by default and can be enabled via the config by
25 'c.YourPreprocessorName.enabled = True'
26 """
28 enabled = Bool(False).tag(config=True)
30 def __init__(self, **kw):
31 """
32 Public constructor
34 Parameters
35 ----------
36 config : Config
37 Configuration file structure
38 `**kw`
39 Additional keyword arguments passed to parent
40 """
42 super().__init__(**kw)
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
52 def preprocess(self, nb, resources):
53 """
54 Preprocessing to apply on each notebook.
56 Must return modified nb, resources.
58 If you wish to apply your preprocessing to each cell, you might want
59 to override preprocess_cell method instead.
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
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.
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