msgspec-click

0.2.1 · active · verified Thu Apr 16

msgspec-click is a Python library that generates Click options from msgspec types, facilitating the creation of command-line interfaces with robust data validation and serialization. It is currently at version 0.2.1 and maintains an active development pace with regular updates.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to define a `msgspec.Struct` with `Annotated` and `msgspec.Meta` to customize Click options like help text, short flags, prompts, and type handling. The `generate_options` function automatically creates Click options from the `Connection` struct, which are then added to a Click command. The input is then converted back to the `Connection` struct using `msgspec.convert` for validation and type-safe access.

from __future__ import annotations
from typing import Annotated
import click
from msgspec import Meta, Struct, convert
from msgspec_click import generate_options

class Connection(Struct):
    user: Annotated[
        str,
        Meta(extra={'help': 'The user\'s name', 'params': ['-u', '--user']})
    ] = ""
    password: Annotated[
        str,
        Meta(extra={
            'help': 'The user\'s password',
            'params': ['-p', '--pass'],
            'prompt': True,
            'hide_input': True,
            'confirmation_prompt': True,
        })
    ] = ""
    headers: Annotated[list[str], Meta(extra={'params': ['-H']})] = []
    timeout: float = 10.0
    allow_insecure: bool = False

@click.command()
def command(**kwargs) -> None:
    connection = convert(kwargs, Connection)
    print(connection)

command.params.extend(generate_options(Connection))

if __name__ == "__main__":
    # To run this, save as script.py and then execute:
    # python script.py --user alice -H "Key: Value" --pass
    # (the --pass will prompt for password)
    command()

view raw JSON →