Skip to main content

Dead simple custom python functions with mkdocs

Project description

Logo
mkdocs-fun-plugin

Dead simple custom python functions with mkdocs

Usage 📖

Install the plugin in your project ...

pip install mkdocs-fun-plugin

... and add it to your mkdocs.yaml configuration ...

# mkdocs.yaml
plugins:
  - fun

... create a docs/fun.py file ...

# docs/fun.py
def hello() -> str:
    return "world"

... and start using your functions in your docs ...

<!-- docs/docs.md -->
This #!hello() comes from my function!

... becomes ...

This world comes from my function!

Configuration 🎛

You can customize the plugin behaviour with configuration:

# mkdocs.yaml
plugins:
  - fun:
      pattern: "#!(?P<func>[^\(]+)\((?P<params>[^\)]*)\)"  # Regex to match functions
      module: fun.py  # Python file that defines your functions

Examples 💡

References and links

# docs/fun.py
def ref(key: str) -> str:
    """
    Bookkeeping and standardized format of references in the docs
    """

    r = {
        "mcguffin": ("McGuffin", "/refs/mcguffin.md"),
    }.get(key)
    assert r, f"No ref for '{key}' found"
    return f"[`{r[0]}`]({r[1]})"

def link(key: str) -> str:
    """
    Bookkeeping and standardized format of external links in the docs
    """

    l = {
        "github": (":fontawesome-brands-github: Github", "https://www.github.com"),
    }.get(key)
    assert l, f"No link for '{key}' found"
    return f'[{l[0]}]({l[1]}){{:target="_blank"}}'
<!-- docs/docs.md -->
Look at our internal #!ref(mcguffin) docs for more info. Also open up #!link(github).

... becomes ...

Look at our internal [`McGuffin`](/refs/mcguffin.md) docs for more info. Also open up [:fontawesome-brands-github: Github](https://www.github.com){:target="_blank"}.

Shell

# docs/fun.py
@functools.cache
def shell(cmd: str) -> str:
    """
    Run arbitrary commands and return stdout
    """

    return (
        subprocess.run(
            cmd,
            shell=True,
            check=True,
            capture_output=True,
        )
        .stdout.decode()
        .strip()
    )
<!-- docs/docs.md -->
#!shell("echo hello | cowsay")

... becomes ...

_______
< hello >
 -------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||

File contents

# docs/fun.py
def func_def(file: str, name: str) -> str:
    """
    Reads 'file' and returns the definition of function 'name'
    """

    with (pathlib.Path(__file__).parent / file).open() as f:
        content = f.read()

    # Find function definition including decorators
    pattern = rf"(@.*\n)*def {name}\s*\([^)]*\)[^:]*:"
    match = re.search(pattern, content, re.MULTILINE)
    assert match, f"Function '{name}' not found in '{file}'"

    # Find where function starts and ends
    start_pos = match.start()
    lines = content.splitlines()
    start_line = content[:start_pos].count("\n")

    # Find function body by tracking indentation
    function_lines = [lines[start_line]]
    indent = (
        re.match(r"(\s*)", lines[start_line + 1]).group(1)
        if start_line + 1 < len(lines)
        else ""
    )

    # Collect and return
    for i in range(start_line + 1, len(lines)):
        line = lines[i]
        if line.strip() and not line.startswith(indent):
            break
        function_lines.append(line)
    return "\n".join(function_lines).strip()
<!-- docs/docs.md -->
#!func_def(fun.py, hello)

... becomes ...

def hello() -> str:
    return "world"

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

mkdocs_fun_plugin-0.1.2.tar.gz (43.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

mkdocs_fun_plugin-0.1.2-py3-none-any.whl (5.7 kB view details)

Uploaded Python 3

File details

Details for the file mkdocs_fun_plugin-0.1.2.tar.gz.

File metadata

  • Download URL: mkdocs_fun_plugin-0.1.2.tar.gz
  • Upload date:
  • Size: 43.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.6.16

File hashes

Hashes for mkdocs_fun_plugin-0.1.2.tar.gz
Algorithm Hash digest
SHA256 b2c1d9af3dcea027abb32e375a7799b8be45653ff32636c3e087a82a98397efe
MD5 d26cbd2305ff905a72d6828ba1f5624a
BLAKE2b-256 f9e6be859ca4570a2a3c8f7b20fff4f7767c2b550541e7c30abda864c24e3898

See more details on using hashes here.

File details

Details for the file mkdocs_fun_plugin-0.1.2-py3-none-any.whl.

File metadata

File hashes

Hashes for mkdocs_fun_plugin-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 07a67b498aad3d222deab10ea2d05e291109a6a4a09cc697f35ebba0f53eeb39
MD5 5a6f1a403c93ef48dd3d30a7aecfc018
BLAKE2b-256 c261a5ca9dd96c9c231f2984a766ba42560e20a4d9acf13175b6ded7d7a853fd

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page