Skip to main content

Automatically generate CLI interfaces from function signatures and docstrings

Project description

philiprehberger-docstring-cli

Tests PyPI version Last updated

Automatically generate CLI interfaces from function signatures and docstrings.

Installation

pip install philiprehberger-docstring-cli

Usage

With the @cli decorator

from philiprehberger_docstring_cli import cli

@cli
def greet(name: str, count: int = 1, loud: bool = False):
    """Greet someone by name.

    Args:
        name: The person to greet.
        count: Number of times to greet.
        loud: Whether to shout.
    """
    greeting = f"Hello, {name}!"
    if loud:
        greeting = greeting.upper()
    for _ in range(count):
        print(greeting)

# Call from CLI: python greet.py Alice --count 3 --loud
# Or call normally: greet("Alice", count=3, loud=True)

The decorated function can still be called normally with arguments. When called with no arguments, it parses sys.argv and runs as a CLI command.

Use .cli(argv=[...]) to pass explicit arguments:

greet.cli(["Alice", "--count", "2", "--loud"])

With run()

For one-off usage without decorating:

from philiprehberger_docstring_cli import run

def add(a: int, b: int):
    """Add two numbers.

    Args:
        a: First number.
        b: Second number.
    """
    return a + b

run(add, ["3", "4"])  # prints 7

Adding --version

Pass version="..." to run() to enable a built-in --version flag:

from philiprehberger_docstring_cli import run

def add(a: int, b: int):
    """Add two numbers."""
    return a + b

run(add, version="1.0.0")
# Invoking with --version prints "1.0.0" and exits.

Introspecting commands

Use command_info(fn) to inspect a @cli-decorated (or plain) function without invoking it. Useful for building help screens, completion data, or programmatic command listings.

from philiprehberger_docstring_cli import cli, command_info

@cli
def greet(name: str, count: int = 1):
    """Greet someone by name.

    Args:
        name: The person to greet.
        count: Number of times to greet.
    """
    ...

info = command_info(greet)
# {
#   "name": "greet",
#   "description": "Greet someone by name.",
#   "params": [
#     {"name": "name",  "type": "str", "default": None, "required": True,  "help": "The person to greet."},
#     {"name": "count", "type": "int", "default": 1,    "required": False, "help": "Number of times to greet."},
#   ],
# }

API

Name Description
cli Decorator that makes a function callable from the CLI.
run Run any function as a CLI command without decorating it.
command_info Introspect a function and return its CLI metadata.

@cli

  • Reads type hints to set argument types (int, float, str, etc.)
  • Parameters without defaults become positional arguments
  • Parameters with defaults become optional --flags
  • bool parameters become --flag / --no-flag toggles
  • Underscore parameter names are converted to hyphenated flags (dry_run -> --dry-run)
  • Google-style docstring Args: sections are used for help text

run(func, argv=None, *, version=None)

  • Builds a parser from the function and parses the given argv (or sys.argv[1:])
  • Does not require the @cli decorator
  • version: when set, the parser accepts --version and prints this string

command_info(func)

  • Returns a dict with name, description, and params
  • Each entry in params is a dict with name, type, default, required, and help
  • Works on @cli-decorated functions as well as plain functions

Development

pip install -e .
python -m pytest tests/ -v

Support

If you find this project useful:

Star the repo

🐛 Report issues

💡 Suggest features

❤️ Sponsor development

🌐 All Open Source Projects

💻 GitHub Profile

🔗 LinkedIn Profile

License

MIT

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

philiprehberger_docstring_cli-0.2.0.tar.gz (189.9 kB view details)

Uploaded Source

Built Distribution

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

philiprehberger_docstring_cli-0.2.0-py3-none-any.whl (6.3 kB view details)

Uploaded Python 3

File details

Details for the file philiprehberger_docstring_cli-0.2.0.tar.gz.

File metadata

File hashes

Hashes for philiprehberger_docstring_cli-0.2.0.tar.gz
Algorithm Hash digest
SHA256 7f6bcb74a1ba21c87f9a6394c3892a6e28e09e33ab4682c07034b99ebf6f3d5d
MD5 5010b56594bfeb7ebd2c99223014588b
BLAKE2b-256 2101fd7adae7cf81fe3cc673626df522094e383bfd6c2d1cfbfb37985fd99d64

See more details on using hashes here.

File details

Details for the file philiprehberger_docstring_cli-0.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for philiprehberger_docstring_cli-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 3340c40ac1b41bf47eee9bb545bbfa6b2ba7fea3a58fe7e660bded9c1b4070c4
MD5 54ec120982cbc3125a8b7b6a41657497
BLAKE2b-256 aa296912f4b6af0bbaee50eb23bcd9515381258557b2c309cf0664e6711a87dc

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