This isn’t really language specific, but if it helps I’m using Python. I can get the parameters just fine with the Traitlets module, but I’m still a novice really and figuring out which patterns to use is challenging.
Say you have a bunch of command line parameters. Some are booleans, where their presence means True, absence means False. Other parameters must accept one text string, and others can be used multiple times to build a list of strings.
It feels inefficient/wrong to use a bunch of IF/THEN/ELSE statements to decide what to do with the parameters, and prone to edge case errors. Is there a pattern that would invoke the correct method based on the combination of input parameters?
Examples:
app thing --dry-run --create --name=newname01 --name=newname02 --verbose app thing --create --name=newname01 --name=newname02 --name=newname03 app job --cancel -i 01 -i 02 -i 03
Thank you, sorry for my noobness.
nickwitha_k@lemmy.sdf.org 1 year ago
As a few others mentioned, the argparse module from the stdlib is the way to go for Python. It takes care of most of this for you in an optimized way. Here’s a minimal example of the above:
bloopernova@programming.dev 1 year ago
That’s an awesome answer, thank you very much. It’s much more elegant than my stuff!
nickwitha_k@lemmy.sdf.org 1 year ago
You’re very welcome! I’ve spent a lot of time with Python and really think that argparse as of 3.x makes most non-stdlib libraries for parsing are unnecessary. You get a ton of functionally and ability to add end-user documentation as you go, while abstracting away some of the basics like type casting/checking
The addition of Match-Case, while not adding much, functionally, does a LOT for readability and keeping logic clear.