base.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. """Base class for preprocessors"""
  2. # Copyright (c) IPython Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. from ..utils.base import NbConvertBase
  5. from traitlets import Bool
  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 :meth:`preprocess_cell` to apply a transformation
  13. independently on each cell or :meth:`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(Preprocessor, self).__init__(**kw)
  30. def __call__(self, nb, resources):
  31. if self.enabled:
  32. self.log.debug("Applying preprocessor: %s",
  33. self.__class__.__name__)
  34. return self.preprocess(nb, resources)
  35. else:
  36. return nb, resources
  37. def preprocess(self, nb, resources):
  38. """
  39. Preprocessing to apply on each notebook.
  40. Must return modified nb, resources.
  41. If you wish to apply your preprocessing to each cell, you might want
  42. to override preprocess_cell method instead.
  43. Parameters
  44. ----------
  45. nb : NotebookNode
  46. Notebook being converted
  47. resources : dictionary
  48. Additional resources used in the conversion process. Allows
  49. preprocessors to pass variables into the Jinja engine.
  50. """
  51. for index, cell in enumerate(nb.cells):
  52. nb.cells[index], resources = self.preprocess_cell(cell, resources, index)
  53. return nb, resources
  54. def preprocess_cell(self, cell, resources, index):
  55. """
  56. Override if you want to apply some preprocessing to each cell.
  57. Must return modified cell and resource dictionary.
  58. Parameters
  59. ----------
  60. cell : NotebookNode cell
  61. Notebook cell being processed
  62. resources : dictionary
  63. Additional resources used in the conversion process. Allows
  64. preprocessors to pass variables into the Jinja engine.
  65. index : int
  66. Index of the cell being processed
  67. """
  68. raise NotImplementedError('should be implemented by subclass')
  69. return cell, resources