DanCardin / cappa

Declarative CLI argument parser
Apache License 2.0
135 stars 8 forks source link

Fix for non-functional subcommands example in docs #135

Closed blakeNaccarato closed 3 months ago

blakeNaccarato commented 4 months ago

Taking some time to check out Cappa since discovering it through Mastodon. It's pretty slick!

This is probably just a slight oversight after refactoring from a slightly different form, I'm sure. The main issues are that the print parameter of print_cmd clobbers the print built-in it that it later tries to call, and code in Fail.__call__ needs to be prefixed with self. I've applied these fixes below.

from __future__ import annotations
from dataclasses import dataclass
import cappa

@dataclass
class Example:
    cmd: cappa.Subcommands[Print | Fail]

def print_cmd(print_: Print):
    if print_.loudly:
        print("PRINTING!")
    else:
        print("printing!")

@cappa.command(invoke=print_cmd)
class Print:
    loudly: bool

@dataclass
class Fail:
    code: int

    def __call__(self):  # again, __call__ is shorthand for the above explicit `invoke=` form.
        raise cappa.Exit(code=self.code)

cappa.invoke(Example)
blakeNaccarato commented 4 months ago

I created a quick PR for it, but if you'd prefer to merge it in a separate docs rework effort or something, feel free to just pick changes into a separate PR!

DanCardin commented 3 months ago

aha! thanks for the report!