sander76 / clipstick

create cli applications using pydantic models
https://sander76.github.io/clipstick/
MIT License
24 stars 3 forks source link

Is optional arg e.g. `int | None` supported somehow? #45

Closed NikolayXHD closed 8 months ago

NikolayXHD commented 8 months ago

Hi @sander76, I'am trying clipstick for the first time. Love the feeling, elegant & minimal. I take my 🎩 off!

The issue I am facing, I don't recall seeing in the docs, how do I handle the optional argument if the default value is None.

With good old argparse I'd write

parser = argparse.ArgumentParser()
parser.add_argument('--effort', '-e', type=int, required=False)
args = parser.parse_args()

effective type of args.effort would be int | None

With clipstick I do

# test.py
from clipstick import parse
from pydantic import BaseModel

class Arguments(BaseModel):
    effort: int | None = None

def main() -> None:
    print(parse(Arguments))

if __name__ == '__main__':
    main()
python -m test -h

Parsing fails with following output

Usage: test.py [Options]

Options:
Traceback (most recent call last):
  File "<frozen runpy>", line 198, in _run_module_as_main
  File "<frozen runpy>", line 88, in _run_code
  File "/home/kolia/git/sandbox/src/test.py", line 14, in <module>
    main()
  File "/home/kolia/git/sandbox/src/test.py", line 10, in main
    print(parse(Arguments))
          ^^^^^^^^^^^^^^^^
  File "/home/kolia/.cache/pypoetry/virtualenvs/sandbox-y84fort7-py3.11/lib/python3.11/site-packages/clipstick/_clipstick.py", line 45, in parse
    success, idx = root_node.match(0, args)
                   ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/kolia/.cache/pypoetry/virtualenvs/sandbox-y84fort7-py3.11/lib/python3.11/site-packages/clipstick/_tokens.py", line 501, in match
    _help.help(self)
  File "/home/kolia/.cache/pypoetry/virtualenvs/sandbox-y84fort7-py3.11/lib/python3.11/site-packages/clipstick/_help.py", line 99, in help
    tbl.add_row("", *_help_from_token(kwarg.help()))
                                      ^^^^^^^^^^^^
  File "/home/kolia/.cache/pypoetry/virtualenvs/sandbox-y84fort7-py3.11/lib/python3.11/site-packages/clipstick/_tokens.py", line 182, in help
    "type": self.field_info.annotation.__name__
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'types.UnionType' object has no attribute '__name__'. Did you mean: '__ne__'?
NikolayXHD commented 8 months ago

Btw the problem only shows up while building help, actually running the program works as intended:

master[1] ~/g/sandbox> python -m test --effort 1
effort=1
master ~/g/sandbox> python -m test
effort=None
sander76 commented 8 months ago

Thanks for this! (And the PR). I'll pick it up today

sander76 commented 8 months ago

Fixed in https://github.com/sander76/clipstick/releases/tag/v0.4.2