base.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. """Base class for preprocessors"""
  2. # Copyright (c) IPython Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. from traitlets import Bool
  5. from nbconvert.utils.base import NbConvertBase
  6. class Preprocessor(NbConvertBase):
  7. """A configurable preprocessor
  8. Inherit from this class if you wish to have configurability for your
  9. preprocessor.
  10. Any configurable traitlets this class exposed will be configurable in
  11. profiles using c.SubClassName.attribute = value
  12. You can overwrite `preprocess_cell()` to apply a transformation
  13. independently on each cell or `preprocess()` if you prefer your own
  14. logic. See corresponding docstring for information.
  15. Disabled by default and can be enabled via the config by
  16. 'c.YourPreprocessorName.enabled = True'
  17. """
  18. enabled = Bool(False).tag(config=True)
  19. def __init__(self, **kw):
  20. """
  21. Public constructor
  22. Parameters
  23. ----------
  24. config : Config
  25. Configuration file structure
  26. `**kw`
  27. Additional keyword arguments passed to parent
  28. """
  29. super().__init__(**kw)
  30. def __call__(self, nb, resources):
  31. """Apply the preprocessor."""
  32. if self.enabled:
  33. self.log.debug("Applying preprocessor: %s", self.__class__.__name__)
  34. return self.preprocess(nb, resources)
  35. return nb, resources
  36. def preprocess(self, nb, resources):
  37. """
  38. Preprocessing to apply on each notebook.
  39. Must return modified nb, resources.
  40. If you wish to apply your preprocessing to each cell, you might want
  41. to override preprocess_cell method instead.
  42. Parameters
  43. ----------
  44. nb : NotebookNode
  45. Notebook being converted
  46. resources : dictionary
  47. Additional resources used in the conversion process. Allows
  48. preprocessors to pass variables into the Jinja engine.
  49. """
  50. for index, cell in enumerate(nb.cells):
  51. nb.cells[index], resources = self.preprocess_cell(cell, resources, index)
  52. return nb, resources
  53. def preprocess_cell(self, cell, resources, index):
  54. """
  55. Override if you want to apply some preprocessing to each cell.
  56. Must return modified cell and resource dictionary.
  57. Parameters
  58. ----------
  59. cell : NotebookNode cell
  60. Notebook cell being processed
  61. resources : dictionary
  62. Additional resources used in the conversion process. Allows
  63. preprocessors to pass variables into the Jinja engine.
  64. index : int
  65. Index of the cell being processed
  66. """
  67. msg = "should be implemented by subclass"
  68. raise NotImplementedError(msg)