Usage

Configuration

To use Sphinx Code Include in a project

  • Create a Sphinx project if you haven’t already (using sphinx-quickstart or otherwise)

  • Add sphinx-code-include to your conf.py

extensions = [
    "code_include.extension",
]

Options

This block shows every option that you can add into a code-include block.

.. code-include :: :func:`module_name.foo`
    :language: python
    :link-at-bottom:
    :link-to-documentation:
    :link-to-source:
    :no-unindent:

Here’s a description of what each option does.

Option

Description

language

The syntax highlight that will be used. Examples of valid input in pygment’s documentation. The default value is “python”

link-at-bottom

Add source code and/or documentation links at the bottom of the block.

link-to-documentation

Add a clickable link to where the source code’s API documentation is.

link-to-source

Add a clickable link to where the source code is from.

no-unindent

If the found source-code has indentation, don’t remove any of it.

Advanced Usage

If you have to use link-to-source, 2 things are required.

  • Your project must be set up for intersphinx.

  • The project that you’re trying to reference must have sphinx.ext.viewcode included in their extensions.

Example Project

sphinx-code-include shows how to use the code-include directive in its own documentation.

This page includes this in its text:

.. code-include :: :mod:`conf`

And this is the conf.py that generates this documentation.

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import os

extensions = [
    'sphinx.ext.autodoc',
    'sphinx.ext.autosummary',
    'sphinx.ext.coverage',
    'sphinx.ext.doctest',
    'sphinx.ext.extlinks',
    'sphinx.ext.ifconfig',
    'sphinx.ext.napoleon',
    'sphinx.ext.todo',
    'sphinx.ext.viewcode',
]
source_suffix = '.rst'
master_doc = 'index'
project = u'Sphinx Code Include'
year = '2019'
author = u'Colin Kennedy'
copyright = '{0}, {1}'.format(year, author)
version = release = u'1.1.1'

pygments_style = 'trac'
templates_path = ['.']
extlinks = {
    'issue': ('https://github.com/ColinKennedy/sphinx-code-include/issues/%s', '#'),
    'pr': ('https://github.com/ColinKennedy/sphinx-code-include/pull/%s', 'PR #'),
}
# on_rtd is whether we are on readthedocs.org
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'

if not on_rtd:  # only set the theme if we're building docs locally
    html_theme = 'sphinx_rtd_theme'

html_use_smartypants = True
html_last_updated_fmt = '%b %d, %Y'
html_split_index = False
html_sidebars = {
   '**': ['searchbox.html', 'globaltoc.html', 'sourcelink.html'],
}
html_short_title = '%s-%s' % (project, version)

napoleon_use_ivar = True
napoleon_use_rtype = False
napoleon_use_param = False


# Add this folder to `sys.path` so that Python can import conf.py.
# Normally we'd never do this. But this is done to show that the
# code-include directive can get the source-code anything that's
# importable.
#
import os
import sys

sys.path.append(os.path.dirname(os.path.abspath(__file__)))

# Add `code-include` so that the code-include directives used in this documentation work
extensions += [
    "code_include.extension",
]

# These next settings are required if you want to link to other Sphinx projects
#extensions += [
#    "sphinx.ext.intersphinx",
#]

intersphinx_mapping = {
    "https://requests.kennethreitz.org/en/latest": None,
}

Notice intersphinx_mapping towards the bottom. This attribute must be set up to point to your other project. intersphinx_mapping cannot be empty. In our case, we’ll point it to some external Sphinx project.

.. code-include :: :func:`requests.get`

And this is what the block above renders as:

def get(url, params=None, **kwargs):
    r"""Sends a GET request.

    :param url: URL for the new :class:`Request` object.
    :param params: (optional) Dictionary, list of tuples or bytes to send
        in the query string for the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response
    """

    kwargs.setdefault('allow_redirects', True)
    return request('get', url, params=params, **kwargs)

Notice that requests.get is actually using a different theme than this documentation’s theme but it still renders with the correct color scheme.

And of course, you can refer to objects in your current project using code-include, too.

.. code-include :: :func:`code_include.helper.memoize`
def memoize(function):
    """Wrap a function with this decorator to cache its results.

    Reference:
        http://code.activestate.com/recipes/578231-probably-the-fastest-memoization-decorator-in-the-/#c1

    Args:
        function (callable):
            Some Python callable will become cache-able by this function.

    Returns:
        :class:`MemoDict`:
            A per-function instance gets called only once for a set of
            arguments once.

    """

    class MemoDict(dict):
        """A class that stores a function and caches each unique function call."""

        def __init__(self, function):
            super(MemoDict, self).__init__()

            self.function = function

        def __call__(self, *args):
            return self[args]

        def __missing__(self, key):
            ret = self[key] = self.function(*key)

            return ret

    return MemoDict(function)

Advanced Customization - Pre-Processor Function

You have total control over how source-code is rendered in your Sphinx project. Say, for example, you want to get source-code of a function but you want to remove the function’s docstring, or delete its comments.

Note

code_include_preprocessor is only run if your code comes from another Sphinx project. If the source-code that you’re targetting comes from imported content then the pre-processor is ignored.

Add a function called code_include_preprocessor to your conf.py

def code_include_preprocessor(soup):
    """`soup` is a :class:`bs4.element.Tag` object."""
    pass

code-include brings in the source-code from projects as HTML tags. This function lets you directly access and modify those tags before it gets converted into raw text. So you’re free to change whatever you want and it will be applied to every code-include directive.