Skip to main content

Notebook text and Python parsing

Normalize notebook text, directives and Python syntax without a notebook model.

Turning text into notebook cells

Write tools accept plain text because that is what agents and humans can produce quickly. This section turns that text into real cells: split on block separators, honor %%markdown/%%code markers, and split exported code into symbol-sized chunks when needed. It is the small parser that makes notebook edits feel like editing a document instead of assembling JSON.

symbol_short_name derives a display alias from a qualified name. Keep the qualified name in records because different modules can expose the same short name.

symbol_short_name removes the owner prefix when a caller needs only the local symbol name.


source

symbol_short_name

def symbol_short_name(
    symbol
):

Return the final dotted component of a symbol name.

assert symbol_short_name("Cell.source") == "source"

Graph records retain dotted names through call_name. symbol_short_name and short_call_name derive display aliases from those names; a call target that cannot be named remains None or the supplied default.

call_name preserves qualification when resolving a call target.


source

call_name

def call_name(
    node
):

Return dotted name text for an AST name, attribute, or call expression.

qualified_call = ast.parse("package.calculate(value)").body[0].value
assert call_name(qualified_call) == "package.calculate"

source

call_sites

def call_sites(
    node, source:str=''
):

Return dotted call names and source locations from one parsed Python tree.

call_sites gives calls one representation in foundation. Graph navigation can add short aliases while retaining the original source locations.

calls_source = "result = package.calculate(value)"
assert call_sites(ast.parse(calls_source), calls_source) == (dict(name="package.calculate", lineno=1, line=calls_source),)
call_sites(ast.parse(calls_source), calls_source)

short_call_name selects the local component of an AST call target.


source

short_call_name

def short_call_name(
    node, default:NoneType=None
):

Return the final dotted component of a call/name node, or default.

assert short_call_name(ast.parse("package.calculate(value)").body[0].value) == "calculate"

is_definition_node recognizes classes as well as synchronous and asynchronous functions. Definition consumers share this predicate instead of maintaining different AST type lists.

is_definition_node distinguishes declarations from ordinary statements.


source

is_definition_node

def is_definition_node(
    node
):

Return whether an AST node defines a function or class.

assert is_definition_node(ast.parse("def calculate(): return 42").body[0])
assert not is_definition_node(ast.parse("answer = 42").body[0])

node_start_line includes decorators when selecting a definition for editing.


source

node_start_line

def node_start_line(
    node
):

Return the zero-based start line including decorators.

decorated_definition = ast.parse("@cache\ndef calculate(): return 42").body[0]
assert node_start_line(decorated_definition) == 0

The shared directive reader uses fastcore to merge comment and metadata directives. This keeps export detection and execution consistent with nbdev 3.3, including colon variants and comment precedence.


source

cell_directives

def cell_directives(
    cell
)->dict:

Return normalized nbdev directives, with comments taking precedence over metadata.

cell_directives merges metadata and leading comments through fastcore. Using one parser prevents export detection from disagreeing with execution about the same cell.

normalized_directives = cell_directives(mk_cell("#| export: true\n#| eval false\nvalue = 42"))
normalized_directives

source

is_export_directive

def is_export_directive(
    line
):

Return whether a line directs executable code to a module.

is_export_directive recognizes executable export directives through the shared parser, including their colon spellings.

is_export_directive("#| export: true")

Python notebook blocks can contain exported and non-exported regions. The splitter retains source order and separates those regions before creating cells.

Multiple definitions in an exported cell become separate cells. Their order and export directives remain intact.

parse_cells normalizes text blocks or existing cell structures before splitting exported definitions into separate cells.


source

parse_cells

def parse_cells(
    cells, default_type:str='code'
):

Normalize cell structures or marked text blocks into notebook cells.

parsed_cells = parse_cells("%%markdown\n## Results\n---\n%%code\nanswer = 42")
assert [cell.cell_type for cell in parsed_cells] == ["markdown", "code"]
[cell.source for cell in parsed_cells]

parse_one_cell enforces the single-cell boundary used by replacement operations. Multiple blocks need a structural edit instead.


source

parse_one_cell

def parse_one_cell(
    text, default_type:str='code'
):

Normalize one cell block and reject multi-cell replacements.

single_cell = parse_one_cell("%%code\nanswer = 42")
assert single_cell.source == "answer = 42"
single_cell.source
mixed_cells = _split_symbol_cells([mk_cell("#| export\ndef first(): return 1\n\ndef second(): return 2")])
assert len(mixed_cells) == 2
assert "def first" in mixed_cells[0].source and "def second" in mixed_cells[1].source
assert all(cell.source.startswith("#| export") for cell in mixed_cells)
[cell.source for cell in mixed_cells]

The notebook format permits source as one string or a list of fragments. cell_source normalizes both at the read boundary; the cell object remains the source of metadata and outputs.


source

cell_source

def cell_source(
    cell
):

Return cell source as one string for mapping and object inputs.

assert cell_source(dict(cell_type="code", source=["answer = ", "42"])) == "answer = 42"

parse_cell retains the syntax error alongside the AST result. Source analysis needs that distinction to report malformed Python without dropping the original cell.


source

parse_cell

def parse_cell(
    cell
):

Return a Python AST and syntax error separately without changing the cell.

parsed_example, parse_error = parse_cell(mk_cell("answer = 42"))
assert isinstance(parsed_example, ast.Module) and parse_error is None
ast.dump(parsed_example)

parse_code_cell returns a tree for valid code and None for malformed or non-code cells. Use cell_analysis when the reason for a failed parse matters.


source

parse_code_cell

def parse_code_cell(
    cell
):

Return the Python tree, or None for non-code and unparseable source.

parsed = parse_code_cell(mk_cell("answer = 42"))
assert isinstance(parsed.body[0], ast.Assign)
assert parse_code_cell(mk_cell("answer =")) is None
assert parse_code_cell(mk_cell("# Heading", cell_type="markdown")) is None
parsed.body[0].targets[0].id

parse_code_cell keeps its tree-or-None interface for AST consumers. Use cell_analysis when a caller must distinguish a parse failure from non-code and inspect the original exception.