Skip to main content

Your all-in-one for beautiful, lightweight, prod-ready CLIs

Project description

🦄 clypi

PyPI version License PyPI - Python Version PyPI - Downloads Contributors

Your all-in-one for beautiful, lightweight, prod-ready CLIs

What is clypi?

I've been working with Python-based CLIs for several years with many users and strict quality requirements and always run into the sames problems with the go-to packages. Therefore, I decided to embark on a journey to build a lightweight, intuitive, pretty, and production ready framework. Here are the key features:

  • Type safe: making use of dataclass-like commands, you can easily specify the types you want for each argument and clypi automatically parses and validates them.
  • Asynchronous: clypi is built to run asynchronously to provide the best performance possible when re-rendering.
  • Easily testable: thanks to being type checked and to using it's own parser, clypi let's you test each individual step. From from parsing command-line arguments to running your commands in tests just like a user would.
  • Composable: clypi lets you easily reuse arguments across subcommands without having to specify them again.
  • Configurable: clypi lets you configure almost everything you'd like to configure. You can create your own themes, help pages, error messages, and more!

Getting started

uv add clypi  # or `pip install clypi`

📖 Docs

Read the API docs for examples and a full API reference. If you want a full guide on how to create and distribute your own Python CLI, check our our tutorial.

🧰 CLI

Read the docs

# examples/basic_cli.py
from clypi import Command, Positional, arg

class Lint(Command):
    files: Positional[tuple[Path, ...]]
    verbose: bool = arg(...)  # Comes from MyCli but I want to use it too

    async def run(self):
        print(f"Linting {', '.join(self.files)} and {self.verbose=}")

class MyCli(Command):
    """
    my-cli is a very nifty demo CLI tool
    """
    subcommand: Lint | None = None
    config: Path | None = arg(parser=cp.Path(exists=True))
    verbose: bool = arg(
        help="Whether to show extra logs",
        prompt="Do you want to see extra logs?",
        default=False,
        short="v",  # User can pass in --verbose or -v
    )

    async def run(self):
        print(f"Running the main command with {self.verbose}")

if __name__ == "__main__":
    cli: MyCli = MyCli.parse()
    cli.start()

uv run -m examples.basic_cli lin

image

🛠️ Configurable

Read the docs

Clypi lets you configure the app globally. This means that all the styling will be easy, uniform across your entire app, and incredibly maintainable.

For example, this is how you'd achieve a UI like uv's CLI:

from clypi import ClypiConfig, ClypiFormatter, Styler, Theme, configure

configure(
    ClypiConfig(
        theme=Theme(
            usage=Styler(fg="green", bold=True),
            prog=Styler(fg="cyan", bold=True),
            section_title=Styler(fg="green", bold=True),
            subcommand=Styler(fg="cyan"),
            long_option=Styler(fg="cyan"),
            short_option=Styler(fg="cyan"),
            positional=Styler(fg="cyan"),
            type_str=Styler(fg="cyan"),
            prompts=Styler(fg="green", bold=True),
        ),
        help_formatter=ClypiFormatter(boxed=False),
    )
)

uv run -m examples.uv ad

image

🌈 Colors

Read the docs

# demo.py
import clypi

# Style text
print(clypi.style("This is blue", fg="blue"), "and", clypi.style("this is red", fg="red"))

# Print with colors directly
clypi.print("Some colorful text", fg="green", reverse=True, bold=True, italic=True)

# Store a styler and reuse it
wrong = clypi.Styler(fg="red", strikethrough=True)
print("The old version said", wrong("Pluto was a planet"))
print("The old version said", wrong("the Earth was flat"))

uv run -m examples.colors

image

🌀 Spinners

Read the docs

You can use spinners as an async context manager:

import asyncio
from clypi import Spinner

async def main():
    async with Spinner("Downloading assets") as s:
        for i in range(1, 6):
            await asyncio.sleep(0.5)
            s.title = f"Downloading assets [{i}/5]"

asyncio.run(main())

Or as a decorator:

import asyncio
from clypi import spinner

@spinner("Doing work", capture=True)
async def do_some_work():
    await asyncio.sleep(2)

asyncio.run(do_some_work())

uv run -m examples.spinner

https://github.com/user-attachments/assets/2065b3dd-c73c-4e21-b698-8bf853e8e520

❓ Prompting

Read the docs

First, you'll need to import the clypi module:

import clypi

answer = clypi.confirm("Are you going to use clypi?", default=True)

🔀 Async by default

clypi was built with an async-first mentality. Asynchronous code execution is incredibly valuable for applications like CLIs where we want to update the UI as we take certain actions behind the scenes. Most often, these actions can be made asynchronous since they involve things like file manipulation, network requests, subprocesses, etc.

🐍 Type-checking

This library is fully type-checked. This means that all types will be correctly inferred from the arguments you pass in.

In this example your editor will correctly infer the type:

hours = clypi.prompt(
    "How many hours are there in a year?",
    parser=lambda x: float(x) if int(x) < 24 else timedelta(days=x),
)
reveal_type(hours)  # Type of "res" is "float | timedelta"

Why should I care?

Type checking will help you catch issues way earlier in the development cycle. It will also provide nice autocomplete features in your editor that will make you faster 󱐋.

📦 Comparison to other packages

[!NOTE] This section is my (danimelchor's) personal opinion I've gathered during my time working with Python CLIs. If you do not agree, please feel free to reach out and I'm open to discussing / trying out new tools.

Argparse is the builtin solution for CLIs, but, as expected, it's functionality is very restrictive. It is not very extensible, it's UI is not pretty and very hard to change, lacks type checking and type parsers, and does not offer any modern UI components that we all love.

Rich is too complex and threaded. The vast catalog of UI components they offer is amazing, but it is both easy to get wrong and break the UI, and too complicated/verbose to onboard coworkers to. It's prompting functionality is also quite limited and it does not offer command-line arguments parsing.

Click is too restrictive. It enforces you to use decorators, which is great for locality of behavior but not so much if you're trying to reuse arguments across your application. It is also painful to deal with the way arguments are injected into functions and very easy to miss one, misspell, or get the wrong type. Click is also fully untyped for the core CLI functionality and hard to test.

Typer seems great! I haven't personally tried it, but I have spent time looking through their docs and code. I think the overall experience is a step up from click's but, at the end of the day, it's built on top of it. Hence, many of the issues are the same: testing is hard, shared contexts are untyped, their built-in type parsing is quite limited, and it does not offer modern features like suggestions on typos. Using Annotated types is also very verbose inside function definitions.

Project details


Release history Release notifications | RSS feed

Download files

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

Source Distribution

clypi-1.0.8.tar.gz (61.8 kB view details)

Uploaded Source

Built Distribution

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

clypi-1.0.8-py3-none-any.whl (37.1 kB view details)

Uploaded Python 3

File details

Details for the file clypi-1.0.8.tar.gz.

File metadata

  • Download URL: clypi-1.0.8.tar.gz
  • Upload date:
  • Size: 61.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for clypi-1.0.8.tar.gz
Algorithm Hash digest
SHA256 510bf6d5fde971de7373a1a1fbb244d55dcd8601bad875b719a0a25270cc0eb8
MD5 82a736a78f51e1cb853930143e92556c
BLAKE2b-256 9eb049f6bac746085f7bba8068a5857a7ae58f93d976ed29fe81f59b0f926526

See more details on using hashes here.

Provenance

The following attestation bundles were made for clypi-1.0.8.tar.gz:

Publisher: release.yml on danimelchor/clypi

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file clypi-1.0.8-py3-none-any.whl.

File metadata

  • Download URL: clypi-1.0.8-py3-none-any.whl
  • Upload date:
  • Size: 37.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for clypi-1.0.8-py3-none-any.whl
Algorithm Hash digest
SHA256 d2c4dd2d07a6cb344d54fc7c874b70fd0aa497f183f56770adff222a8617e828
MD5 946eb311f93ab8463030fd808a5880db
BLAKE2b-256 ef4847d6eacd4c50310e90f55aeeab620a11b3d1cd3f6be5bde2f538fbb08166

See more details on using hashes here.

Provenance

The following attestation bundles were made for clypi-1.0.8-py3-none-any.whl:

Publisher: release.yml on danimelchor/clypi

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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