__init__.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. """The main API for the v3 notebook format."""
  2. # Copyright (c) IPython Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. from __future__ import annotations
  5. __all__ = [
  6. "NotebookNode",
  7. "new_code_cell",
  8. "new_text_cell",
  9. "new_notebook",
  10. "new_output",
  11. "new_worksheet",
  12. "new_metadata",
  13. "new_author",
  14. "new_heading_cell",
  15. "nbformat",
  16. "nbformat_minor",
  17. "nbformat_schema",
  18. "reads_json",
  19. "writes_json",
  20. "read_json",
  21. "write_json",
  22. "to_notebook_json",
  23. "reads_py",
  24. "writes_py",
  25. "read_py",
  26. "write_py",
  27. "to_notebook_py",
  28. "downgrade",
  29. "upgrade",
  30. "parse_filename",
  31. ]
  32. import os
  33. from .convert import downgrade, upgrade
  34. from .nbbase import (
  35. NotebookNode,
  36. nbformat,
  37. nbformat_minor,
  38. nbformat_schema,
  39. new_author,
  40. new_code_cell,
  41. new_heading_cell,
  42. new_metadata,
  43. new_notebook,
  44. new_output,
  45. new_text_cell,
  46. new_worksheet,
  47. )
  48. from .nbjson import reads as read_json
  49. from .nbjson import reads as reads_json
  50. from .nbjson import to_notebook as to_notebook_json
  51. from .nbjson import writes as write_json
  52. from .nbjson import writes as writes_json
  53. from .nbpy import reads as read_py
  54. from .nbpy import reads as reads_py
  55. from .nbpy import to_notebook as to_notebook_py
  56. from .nbpy import writes as write_py
  57. from .nbpy import writes as writes_py
  58. def parse_filename(fname):
  59. """Parse a notebook filename.
  60. This function takes a notebook filename and returns the notebook
  61. format (json/py) and the notebook name. This logic can be
  62. summarized as follows:
  63. * notebook.ipynb -> (notebook.ipynb, notebook, json)
  64. * notebook.json -> (notebook.json, notebook, json)
  65. * notebook.py -> (notebook.py, notebook, py)
  66. * notebook -> (notebook.ipynb, notebook, json)
  67. Parameters
  68. ----------
  69. fname : unicode
  70. The notebook filename. The filename can use a specific filename
  71. extension (.ipynb, .json, .py) or none, in which case .ipynb will
  72. be assumed.
  73. Returns
  74. -------
  75. (fname, name, format) : (unicode, unicode, unicode)
  76. The filename, notebook name and format.
  77. """
  78. basename, ext = os.path.splitext(fname) # noqa: PTH122
  79. if ext in [".ipynb", ".json"]:
  80. format_ = "json"
  81. elif ext == ".py":
  82. format_ = "py"
  83. else:
  84. basename = fname
  85. fname = fname + ".ipynb"
  86. format_ = "json"
  87. return fname, basename, format_