Skip to content

notebook

Modeling the Notebook File Format with Pydantic models. It also includes some helper properties relevant to Noteable format, such as whether a code cell is a SQL cell and retrieving the output collection id, which is a Noteable-specific cell output context.

See https://nbformat.readthedocs.io/en/latest/format_description.html# for Notebook model spec.

Devs: as usual with Pydantic modeling, the top-level model (Notebook) is at the bottom of this file, read from bottom up for most clarity.

CellBase #

Bases: BaseModel

All Cell types have id, source and metadata. The source can be a string or list of strings in nbformat spec, but we only want to deal with source as a string throughout our code base so we have a validator here to cast the list of strings to a single string, both at initial read and during any mutations (e.g. applying diff-match-patch cell content updates).

Source code in origami/models/notebook.py
class CellBase(BaseModel):
    """
    All Cell types have id, source and metadata.
    The source can be a string or list of strings in nbformat spec,
    but we only want to deal with source as a string throughout our
    code base so we have a validator here to cast the list of strings
    to a single string, both at initial read and during any mutations
    (e.g. applying diff-match-patch cell content updates).
    """

    id: str = Field(default_factory=lambda: str(uuid.uuid4()))
    source: str = ""
    metadata: Dict[str, Any] = Field(default_factory=dict)

    @validator("source", pre=True)
    def multiline_source(cls, v):
        if isinstance(v, list):
            return "\n".join(v)
        return v

    class Config:
        validate_on_assignment = True

StreamOutput #

Bases: BaseModel

Source code in origami/models/notebook.py
class StreamOutput(BaseModel):
    output_type: Literal["stream"] = "stream"
    name: str  # stdout or stderr
    text: str

    @validator("text", pre=True)
    def multiline_text(cls, v):
        """In the event we get a list of strings, combine into one string with newlines."""
        if isinstance(v, list):
            return "\n".join(v)
        return v

multiline_text(v) #

In the event we get a list of strings, combine into one string with newlines.

Source code in origami/models/notebook.py
@validator("text", pre=True)
def multiline_text(cls, v):
    """In the event we get a list of strings, combine into one string with newlines."""
    if isinstance(v, list):
        return "\n".join(v)
    return v