jsonargparse icon indicating copy to clipboard operation
jsonargparse copied to clipboard

CLI: populate List with the * wildcard (like argparse nargs='+')

Open PaulLerner opened this issue 1 year ago • 4 comments

🚀 Feature request

Motivation

def main(foo: List[str] = None):
    pass
    
if __name__ == "__main__":
    CLI(main)

Currently, to pass several arguments to a List, the syntax is quite difficult, you need to do something like

python jsonargparse_demo.py --foo+=ab --foo+=ac 

Pitch

A great thing about argparse is that you can add nargs='+'

def main(foo: List[str]):
    pass


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('foo', type=str, nargs='+')
    main(**vars(parser.parse_args()))

so you can call it like

python jsonargparse_demo.py a*

and match all files starting with "a"

Alternatives

I guess you can already do this using the ArgumentParser from jsonargparse but I like CLI so much, it's really convenient otherwise, thanks again for the great library btw!

PaulLerner avatar Jul 15 '24 15:07 PaulLerner

Thank you for the proposal! I had thought about this a few times. Maybe I add it. The biggest issue is more complex cases and expectations from people. For example a type Optional[List[str]]. It would be problematic to have nargs='+' because --foo null ab should fail, but then it becomes quite complex to implement. And this is only one case out of many there could be.

As a side note, += is not the only way currently. A list can also be given like --foo="[ab,ac]". Still, not as convenient as a* would be.

mauvilsa avatar Jul 19 '24 05:07 mauvilsa

Hi,

Yes I think it only makes sense for positional arguments

PaulLerner avatar Jul 19 '24 07:07 PaulLerner

I think it can make sense for both positional and non-positional. The issue that I meant is the following. Say someone has a function argument with type list[str] and the CLI gets created with nargs='+'. Then that person extends the code and the correct type becomes Union[list[str], int]. The int does not make sense with nargs='+' so what happens?

mauvilsa avatar Jul 19 '24 08:07 mauvilsa

I see your point, with Union[list[str], int] the behavior should change to current behavior but that might be confusing to the user because then they cannot switch between e.g. a* and 42 but will need to use the current behavior "[ab,ac]".

I'm not sure I have a solution to that except letting the users know that nargs='+' only works with "pure" lists like list[str] but not Union[list[str], int] or Optional[List[str]]

PaulLerner avatar Jul 19 '24 09:07 PaulLerner