Python API for working with notebook files¶
Reading and writing¶
- nbformat.read(fp, as_version, capture_validation_error=None, **kwargs)¶
Read a notebook from a file as a NotebookNode of the given version.
The string can contain a notebook of any version. The notebook will be returned as_version, converting, if necessary.
Notebook format errors will be logged.
- Parameters
fp (file or str) – A file-like object with a read method that returns unicode (use
io.open()
in Python 2), or a path to a file.as_version (int) – The version of the notebook format to return. The notebook will be converted, if necessary. Pass nbformat.NO_CONVERT to prevent conversion.
capture_validation_error (dict, optional) – If provided, a key of “ValidationError” with a value of the ValidationError instance will be added to the dictionary.
- Returns
nb – The notebook that was read.
- Return type
- nbformat.reads(s, as_version, capture_validation_error=None, **kwargs)¶
Read a notebook from a string and return the NotebookNode object as the given version.
The string can contain a notebook of any version. The notebook will be returned as_version, converting, if necessary.
Notebook format errors will be logged.
- Parameters
s (unicode) – The raw unicode string to read the notebook from.
as_version (int) – The version of the notebook format to return. The notebook will be converted, if necessary. Pass nbformat.NO_CONVERT to prevent conversion.
capture_validation_error (dict, optional) – If provided, a key of “ValidationError” with a value of the ValidationError instance will be added to the dictionary.
- Returns
nb – The notebook that was read.
- Return type
The reading functions require you to pass the as_version parameter. Your code should specify the notebook format that it knows how to work with: for instance, if your code handles version 4 notebooks:
nb = nbformat.read('path/to/notebook.ipynb', as_version=4)
This will automatically upgrade or downgrade notebooks in other versions of the notebook format to the structure your code knows about.
- nbformat.write(nb, fp, version=nbformat.NO_CONVERT, capture_validation_error=None, **kwargs)¶
Write a notebook to a file in a given nbformat version.
The file-like object must accept unicode input.
- Parameters
nb (NotebookNode) – The notebook to write.
fp (file or str) – Any file-like object with a write method that accepts unicode, or a path to write a file.
version (int, optional) – The nbformat version to write. If nb is not this version, it will be converted. If unspecified, or specified as nbformat.NO_CONVERT, the notebook’s own version will be used and no conversion performed.
capture_validation_error (dict, optional) – If provided, a key of “ValidationError” with a value of the ValidationError instance will be added to the dictionary.
- nbformat.writes(nb, version=nbformat.NO_CONVERT, capture_validation_error=None, **kwargs)¶
Write a notebook to a string in a given format in the given nbformat version.
Any notebook format errors will be logged.
- Parameters
nb (NotebookNode) – The notebook to write.
version (int, optional) – The nbformat version to write. If unspecified, or specified as nbformat.NO_CONVERT, the notebook’s own version will be used and no conversion performed.
capture_validation_error (dict, optional) – If provided, a key of “ValidationError” with a value of the ValidationError instance will be added to the dictionary.
- Returns
s – The notebook as a JSON string.
- Return type
unicode
- nbformat.NO_CONVERT¶
This special value can be passed to the reading and writing functions, to indicate that the notebook should be loaded/saved in the format it’s supplied.
NotebookNode objects¶
The functions in this module work with NotebookNode
objects, which are
like dictionaries, but allow attribute access (nb.cells
). The structure of
these objects matches the notebook format described in The Notebook file format.
- class nbformat.NotebookNode(*args, **kw)¶
A dict-like node with attribute-access
- nbformat.from_dict(d)¶
Convert dict to dict-like NotebookNode
Recursively converts any dict in the container to a NotebookNode. This does not check that the contents of the dictionary make a valid notebook or part of a notebook.
Other functions¶
- nbformat.convert(nb, to_version)¶
Convert a notebook node object to a specific version. Assumes that all the versions starting from 1 to the latest major X are implemented. In other words, there should never be a case where v1 v2 v3 v5 exist without a v4. Also assumes that all conversions can be made in one step increments between major versions and ignores minor revisions.
- Parameters
nb (NotebookNode) –
to_version (int) – Major revision to convert the notebook to. Can either be an upgrade or a downgrade.
- Raises
ValueError – Notebook failed to convert.
ValueError – The version specified is invalid or doesn’t exist.
ValidationError – Conversion failed due to missing expected attributes.
- nbformat.validate(nbdict: typing.Optional[typing.Any] = None, ref: typing.Optional[str] = None, version: typing.Optional[int] = None, version_minor: typing.Optional[int] = None, relax_add_props: bool = <object object>, nbjson: typing.Optional[typing.Any] = None, repair_duplicate_cell_ids: bool = <object object>, strip_invalid_metadata: bool = <object object>) None ¶
Checks whether the given notebook dict-like object conforms to the relevant notebook format schema.
- Parameters
nbdict (dict) – notebook document
ref (optional, str) – reference to the subset of the schema we want to validate against. for example
"markdown_cell"
, “code_cell” ….version (int) –
version_minor (int) –
relax_add_props (bool) – Deprecated since 5.5.0 – will be removed in the future. Wether to allow extra property in the Json schema validating the notebook.
nbjson –
repair_duplicate_cell_ids (boolny) – Deprecated since 5.5.0 – will be removed in the future.
strip_invalid_metadata (bool) – Deprecated since 5.5.0 – will be removed in the future.
- Return type
None
- Raises
ValidationError if not valid. –
Notes
Prior to Nbformat 5.5.0 the validate and isvalid method would silently try to fix invalid notebook and mutate arguments. This behavior is deprecated and will be removed in a near future.
Please explicitly call normalize if you need to normalize notebooks.
- class nbformat.ValidationError(message, validator=<unset>, path=(), cause=None, context=(), validator_value=<unset>, instance=<unset>, schema=<unset>, schema_path=(), parent=None, type_checker=<unset>)¶
An instance was invalid under a provided schema.
Constructing notebooks programmatically¶
These functions return NotebookNode
objects with the necessary fields.
- nbformat.v4.new_notebook(**kwargs)¶
Create a new notebook
- nbformat.v4.new_code_cell(source='', **kwargs)¶
Create a new code cell
- nbformat.v4.new_markdown_cell(source='', **kwargs)¶
Create a new markdown cell
- nbformat.v4.new_raw_cell(source='', **kwargs)¶
Create a new raw cell
- nbformat.v4.new_output(output_type, data=None, **kwargs)¶
Create a new output, to go in the
cell.outputs
list of a code cell.
- nbformat.v4.output_from_msg(msg)¶
Create a NotebookNode for an output from a kernel’s IOPub message.
- Returns
NotebookNode
- Return type
the output as a notebook node.
- Raises
ValueError – if the message is not an output message.:
Notebook signatures¶
This machinery is used by the notebook web application to record which notebooks are trusted, and may show dynamic output as soon as they’re loaded. See notebook:notebook_security for more information.
- class nbformat.sign.NotebookNotary(**kwargs: Any)¶
A class for computing and verifying notebook signatures.
- sign(nb)¶
Sign a notebook, indicating that its output is trusted on this machine
Stores hash algorithm and hmac digest in a local database of trusted notebooks.
- unsign(nb)¶
Ensure that a notebook is untrusted
by removing its signature from the trusted database, if present.
- check_signature(nb)¶
Check a notebook’s stored signature
If a signature is stored in the notebook’s metadata, a new signature is computed and compared with the stored value.
Returns True if the signature is found and matches, False otherwise.
The following conditions must all be met for a notebook to be trusted: - a signature is stored in the form ‘scheme:hexdigest’ - the stored scheme matches the requested scheme - the requested scheme is available from hashlib - the computed hash from notebook_signature matches the stored hash
- mark_cells(nb, trusted)¶
Mark cells as trusted if the notebook’s signature can be verified
Sets
cell.metadata.trusted = True | False
on all code cells, depending on the trusted parameter. This will typically be the return value fromself.check_signature(nb)
.This function is the inverse of check_cells
- check_cells(nb)¶
Return whether all code cells are trusted.
A cell is trusted if the ‘trusted’ field in its metadata is truthy, or if it has no potentially unsafe outputs. If there are no code cells, return True.
This function is the inverse of mark_cells.
Signature storage¶
Signatures are stored using a pluggable SignatureStore
subclass. To
implement your own, override the methods below and configure
NotebookNotary.store_factory
.
- class nbformat.sign.SignatureStore¶
Base class for a signature store.
- store_signature(digest, algorithm)¶
Implement in subclass to store a signature.
Should not raise if the signature is already stored.
- remove_signature(digest, algorithm)¶
Implement in subclass to delete a signature.
Should not raise if the signature is not stored.
- check_signature(digest, algorithm)¶
Implement in subclass to check if a signature is known.
Return True for a known signature, False for unknown.
- close()¶
Close any open connections this store may use.
If the store maintains any open connections (e.g. to a database), they should be closed.
By default, NotebookNotary
will use an SQLite based store if SQLite
bindings are available, and an in-memory store otherwise.
- class nbformat.sign.SQLiteSignatureStore(**kwargs: Any)¶
Store signatures in an SQLite database.
- class nbformat.sign.MemorySignatureStore¶
Non-persistent storage of signatures in memory.