---
title: clean
description: Strip superfluous metadata from notebooks
order: 9
---
<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

Clean notebooks before committing to remove execution counts and metadata that cause unnecessary merge conflicts. Cleaning also adds missing cell IDs, which nbformat 4.5\+ requires. See the [Git-friendly Jupyter tutorial](../tutorials/git_friendly_jupyter.md) to configure the Git diff and merge drivers or opt-in Jupyter pre-save cleaning.

## Clean

[source](https://github.com/AnswerDotAI/fastship/blob/main/fastship/clean.py#L56)

### clean\_nb

```python
def clean_nb(
    nb, # The notebook to clean
    clear_all:bool=False, # Remove cell outputs and non-nbdev cell metadata?
    allowed_metadata_keys:list=None, # Preserve the list of keys in the main notebook metadata
    allowed_cell_metadata_keys:list=None, # Preserve the list of keys in cell level metadata
    clean_ids:bool=True, # Remove ids from plaintext reprs?
    repair:bool=True, # Fix structural problems first (see `repair_nb`)?
):
```

*Clean `nb` from superfluous metadata*

Jupyter adds a trailing `\n` to images in cell outputs. VS Code's Jupyter extension does not. In this PNG example, [`clean_nb`](clean.md#clean_nb) removes the newline to avoid editor-dependent diffs:

```python
test_nb = read_nb('../../tests/image.ipynb')
assert test_nb.cells[0].outputs[0].data['image/png'][-1] == "\n" # Make sure it was not converted by acccident
clean_nb(test_nb)
assert test_nb.cells[0].outputs[0].data['image/png'][-1] != "\n"
```

The test notebook contains notebook metadata and metadata on its second cell:

```python
test_nb = read_nb('../../tests/metadata.ipynb')

assert {'meta', 'jekyll', 'nbdev', 'my_extra_key', 'my_removed_key'} <= test_nb.metadata.keys()
assert {'meta', 'hide_input', 'my_extra_cell_key', 'nbdev', 'my_removed_cell_key'} == test_nb.cells[1].metadata.keys()
```

[`clean_nb`](clean.md#clean_nb) keeps the default allowed metadata keys and removes the others:

```python
clean_nb(test_nb)

assert {'kernelspec', 'nbdev'} == test_nb.metadata.keys()
assert {'nbdev'} == test_nb.cells[1].metadata.keys()
```

[`clean_nb`](clean.md#clean_nb) calls `repair_nb` by default to fix invalid notebook structure. For example, Markdown cells must not have `outputs` or `execution_count` attributes:

```python
_nb = dict2nb(dict(cells=[dict(cell_type='markdown', source='hi', outputs=[], execution_count=1, id='m1', metadata={})],
                   metadata=dict(kernelspec=dict(name='python3', display_name='Python 3')), nbformat=4, nbformat_minor=5))
clean_nb(_nb)
assert 'outputs' not in _nb.cells[0] and 'execution_count' not in _nb.cells[0]
validate_nb(_nb)
```

We can preserve some additional keys at the notebook or cell levels:

```python
test_nb = read_nb('../../tests/metadata.ipynb')
clean_nb(test_nb, allowed_metadata_keys={'my_extra_key'}, allowed_cell_metadata_keys={'my_extra_cell_key'})

assert {'kernelspec', 'nbdev', 'my_extra_key'} == test_nb.metadata.keys()
assert {'nbdev', 'my_extra_cell_key'} == test_nb.cells[1].metadata.keys()
```

Passing `clear_all=True` clears outputs and removes all cell metadata except `nbdev` directives:

```python
test_nb = read_nb('../../tests/metadata.ipynb')
clean_nb(test_nb, clear_all=True)

assert {'kernelspec', 'nbdev'} == test_nb.metadata.keys()
test_eq(test_nb.cells[1].metadata, {'nbdev': {'hide': 'true'}})
```

`clean_ids=True` removes object memory addresses from text representations in outputs. These addresses can change between runs and cause unnecessary Git diffs and merge conflicts. For example:

```
<PIL.PngImagePlugin.PngImageFile image mode=L size=28x28 at 0x7FB4F8979690>
```

becomes:

```
<PIL.PngImagePlugin.PngImageFile image mode=L size=28x28>
```

[`clean_nb`](clean.md#clean_nb) adds missing cell IDs:

```python
test_cell = {'source': 'x=1', 'cell_type': 'code', 'metadata': {}}
_clean_cell(test_cell, False, set(), True)
test_cell['id']
```

```output
'64e20756'
```

[source](https://github.com/AnswerDotAI/fastship/blob/main/fastship/clean.py#L83)

### process\_write

```python
def process_write(
    warn_msg, proc_nb, f_in, f_out=None, disp:bool=False
):
```

## Directive migrations

Set `to_meta = ["export"]` in `ship.toml` or under `[tool.fastship]` in `pyproject.toml` to move listed directives from comments to cell metadata on every clean.

Move selected directives from comments to cell metadata without changing their meaning:

```python
c = mk_cell('#| hide\n#| eval: false\n#| export: utils\n1+1')
_to_meta(c, ['hide','eval'])
test_eq(c.metadata['nbdev'], dict(hide='true', eval='false'))
test_eq(c.source, '#| export: utils\n1+1')

c2 = mk_cell('#| export\n\n1+1')
_to_meta(c2, ['export'])
test_eq((c2.source, c2.metadata['nbdev']), ('1+1', {'export': 'true'}))
```

[source](https://github.com/AnswerDotAI/fastship/blob/main/fastship/clean.py#L137)

### ship\_clean

```python
def ship_clean(
    fname:str=None, # A notebook name or glob to clean
    clear_all:bool=False, # Remove cell outputs and non-nbdev cell metadata?
    disp:bool=False, # Print the cleaned outputs
    stdin:bool=False, # Read notebook from input stream
    repair:<function bool_arg at 0x7d9c12ca7b00>=True, # Fix structural problems, e.g. stray outputs on non-code cells (see `repair_nb`)?
    to_meta:str=None, # Space-separated directive names to move from comments to cell metadata (defaults to config's `to_meta`)
):
```

*Clean all notebooks in `fname` to avoid merge conflicts*

By default (`fname` left to `None`), all the notebooks in `config.ship_path` are cleaned. Passing `clear_all=True` removes cell outputs and all cell metadata except `nbdev` directives.

To preserve extra metadata, use these settings in `ship.toml` or under `[tool.fastship]` in `pyproject.toml`:

- `allowed_metadata_keys` preserves notebook metadata.
- `allowed_cell_metadata_keys` preserves cell metadata.
- `to_meta` moves listed comment directives into cell metadata on every clean (e.g. `to_meta = ["export"]`).

This example preserves `k1` and `k2` at both levels:

```toml
[tool.fastship]
allowed_metadata_keys = ["k1", "k2"]
allowed_cell_metadata_keys = ["k1", "k2"]
to_meta = ["export"]
```

[source](https://github.com/AnswerDotAI/fastship/blob/main/fastship/clean.py#L155)

### clean\_jupyter

```python
def clean_jupyter(
    path, model, **kwargs
):
```

*Clean Jupyter `model` pre save to `path`*

This cleans notebooks on save when `jupyter_hooks = true` is set for the project, avoiding unnecessary merge conflicts. It implements a `pre_save_hook` for Jupyter's [file save hook API](https://jupyter-server.readthedocs.io/en/latest/developers/savehooks.html). See the [Git-friendly Jupyter tutorial](../tutorials/git_friendly_jupyter.md#opt-in-jupyter-pre-save-cleaning) for opt-in Jupyter configuration.
