Stitch

Stitch is a small python library for writing reproducible reports in markdown. It's heavily inspired by (read: a python clone of) knitr and RMarkdown.

You might want to consider Knitpy instead of stitch. It's been around longer is probably more usable at this point.

This document shows you the source markdown side-by-side with the executed and rendered HTML. For more a more complex example, check out the "Examples" tab in the navbar, which links to the source markdown and rendered HTML, PDF, and docx versions of the document.

Code-Chunks

                
The syntax for creating an executable block is

    ```{kernel_name}
    # Your code here
    ```

The output of that block, if any, will be inserted just after the end of the
code block[^literal_code].

[^literal_code]: If you look at the markdown source for this document,
you'll see that I've indented the code block by 4 spaces. This is so that
the block is interpreted as a literal chunk of text, and isn't intercepted
by the engine for execution. To actually run code the code chunk should be at
the start of the line.

Code chunks can accept up to two positional arguments

- `kernel_name` (required)
  See `jupyter-kernelspect list` for a list of the kernels installed on your
  system
- `chunk_name` (optional)
  And identifier for the code chunk. Used in several places for
  naming figures and files

And some keyword arguments

- `echo`
- `eval`
- `include`

The rest of this document is intended to demonstrate `stitch` in action.

            

The syntax for creating an executable block is

```{kernel_name}
# Your code here
```

The output of that block, if any, will be inserted just after the end of the code block1.

Code chunks can accept up to two positional arguments

  • kernel_name (required) See jupyter-kernelspect list for a list of the kernels installed on your system
  • chunk_name (optional) And identifier for the code chunk. Used in several places for naming figures and files

And some keyword arguments

  • echo
  • eval
  • include

The rest of this document is intended to demonstrate stitch in action.


Basics

                
`stitch` keeps a registry of kernels, meaning state is preserved between
code chunks

```{python}
x = 10
```


There was no output there, but we can reuse `x` now

```{python}
print(x + 2)
```

Now we see the output.

            

stitch keeps a registry of kernels, meaning state is preserved between code chunks

In [1]: x = 10

There was no output there, but we can reuse x now

In [2]: print(x + 2)
12

Now we see the output.


Options

                
You can exclude the code, but include the output with the `echo=False` option

For example, we can show the fibbonnaci numbers less than 100, without
bothering the reader with how we calculate them:

```{python, echo=False}
def fib(n):
    a, b = 0, 1
    while a < n:
        print(a, end=', ')
        a, b = b, a+b

fib(100)
```

            

You can exclude the code, but include the output with the echo=False option

For example, we can show the fibbonnaci numbers less than 100, without bothering the reader with how we calculate them:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 

Exceptions

                
By default, exceptions are displayed and the stitching continues

```{python}
raise ValueError("ValueError!")
```

            

By default, exceptions are displayed and the stitching continues

In [4]: raise ValueError("ValueError!")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-4-0dec59cd0416> in <module>()
----> 1 raise ValueError("ValueError!")

ValueError: ValueError!

Rich Display

                
We reuse IPython's rich display system, so objects defining `_repr_html_`,
`_repr_latex_`, etc. will have that represented in the output.
Pandas DataFrames, for example, do so

```{python}
import pandas as pd
pd.options.display.latex.repr = True
import seaborn as sns
df = sns.load_dataset("iris")
df.head()
```


            

We reuse IPython's rich display system, so objects defining _repr_html_, _repr_latex_, etc. will have that represented in the output. Pandas DataFrames, for example, do so

In [5]: import pandas as pd
   ...: pd.options.display.latex.repr = True
   ...: import seaborn as sns
   ...: df = sns.load_dataset("iris")
   ...: df.head()
sepal_length sepal_width petal_length petal_width species
0 5.1 3.5 1.4 0.2 setosa
1 4.9 3.0 1.4 0.2 setosa
2 4.7 3.2 1.3 0.2 setosa
3 4.6 3.1 1.5 0.2 setosa
4 5.0 3.6 1.4 0.2 setosa

Graphics

                
It's possible to capture rich output, like graphics


```{python}
%matplotlib inline

sns.set()
sns.pairplot(df, hue="species");
```

You can control image attributes from the chunk options

```{python, width=80, height=80px}
%matplotlib inline

sns.set()
sns.pairplot(df, hue="species");
```

            

It's possible to capture rich output, like graphics

In [6]: %matplotlib inline
   ...:
   ...: sns.set()
   ...: sns.pairplot(df, hue="species");

You can control image attributes from the chunk options

In [7]: %matplotlib inline
   ...:
   ...: sns.set()
   ...: sns.pairplot(df, hue="species");


Document Options

                
You can provide document-wide options in a YAML metadata block at the
start of the file.
This looks like

    ```
    header-includes:
        - \usepackage{booktabs}
    ```


See the [pandoc documentation](http://pandoc.org/MANUAL.html) about the
`yaml_metadata_block` extension for all the options.
In addition to Pandoc's options, `stitch` defines and intercepts the following
variables

            

You can provide document-wide options in a YAML metadata block at the start of the file. This looks like

```
header-includes:
    - \usepackage{booktabs}
```

See the pandoc documentation about the yaml_metadata_block extension for all the options. In addition to Pandoc's options, stitch defines and intercepts the following variables


Command-line Interface

                
The command-line interface is as similar to pandoc's as possible.
The simplest example is just passing an input markdown file:

    ```
    stitch input.md
    ```

This will take the text in `input.md` execute it and convert it to HTML,
printing the result to stdout.

Other useful options are

- `-o` or `--output_file`: the file to write the stitched output to; defaults
to stdout.
- `-t` or `--to`: the type to transform to. Defaults to `html` or it's
inferred from the `--output_file` extension.

The biggest difference right now is the treatment of stdin.
With pandoc you can convert stdin with

    ```
    $ cat input.md | pandoc
    ```

With `stitch`, it's written as

    ```
    $ cat input.md | stitch -
    ```

So a `-` is the marker for stdin.

            

The command-line interface is as similar to pandoc's as possible. The simplest example is just passing an input markdown file:

```
stitch input.md
```

This will take the text in input.md execute it and convert it to HTML, printing the result to stdout.

Other useful options are

  • -o or --output_file: the file to write the stitched output to; defaults to stdout.
  • -t or --to: the type to transform to. Defaults to html or it's inferred from the --output_file extension.

The biggest difference right now is the treatment of stdin. With pandoc you can convert stdin with

```
$ cat input.md | pandoc
```

With stitch, it's written as

```
$ cat input.md | stitch -
```

So a - is the marker for stdin.


Notes on Pandoc

                
If you aren't familiar, pandoc is a universal document converter written
in Haskell.

For outputs like HTML and LaTeX, pandoc produces document fragments by default.
This means the converted output doesn't include things like ``
tags, just the body.
`stitch`, on the other hand, prefers standalone documents.

The second difference is that stitch prefers self-contained documents.
This means things like images are inlined as base64 encoded PNGs or SVGs.
With pandoc, this options are enabled with the

- `--standalone`
- `--self-contained`

options. With `stitch`, the defaults are flipped to True, and disabled with

- `--no-standalone`
- `--no-self-contained`



            

If you aren't familiar, pandoc is a universal document converter written in Haskell.

For outputs like HTML and LaTeX, pandoc produces document fragments by default. This means the converted output doesn't include things like <head> tags, just the body. stitch, on the other hand, prefers standalone documents.

The second difference is that stitch prefers self-contained documents. This means things like images are inlined as base64 encoded PNGs or SVGs. With pandoc, this options are enabled with the

  • --standalone
  • --self-contained

options. With stitch, the defaults are flipped to True, and disabled with

  • --no-standalone
  • --no-self-contained

  1. If you look at the markdown source for this document, you'll see that I've indented the code block by 4 spaces. This is so that the block is interpreted as a literal chunk of text, and isn't intercepted by the engine for execution. To actually run code the code chunk should be at the start of the line.