getopt vs. optparse vs. argparse


sooner or later you’ll end up needing to do some argument parsing. the foolish end up writing their own yucky parser that ends up having a big if statement filled with things like:

if len(sys.argv) > 1

in it. don’t do this unless you have a really good excuse.

sooner or later, someone directs you to getopt, and you happily continue on with buggy manual parsing thinking you’ve “found the way”. useful in some circumstances, but should generally be avoided.

since you’re a good student, you read the docs, and one chapter later, you find out about optparse. higher level parsing! alright! the library that we all wanted to write, actually exists, and it seems to follow some ideals too. this i actually appreciate, and it is lovely to use. you dream about all programs using this common library and unifying the world. consistency is a dream.

you then remember that the positional syntax of cp, git, man, and friends actually does makes sense, and you’d like for them not to change. you go on with life, hacking up optparse when needed. everything is pretty good, and you’re a seasoned coder by now, but sooner or later, someone sets you straight with a nice blog post like this.

there’s a new kid in town, and it’s called argparse. you read the docs, and you promise yourself to use standard argument styles. subparsers, and types finally exist in a sensible way. you love the inheritance schemes, and you’re one step away from being able to complete your parsing code, but you still haven’t found that magic place in the manual that hides the precious answer you need. and now you have (probably the fourth code block down from that link- maybe also the fifth). why this way buried in with the api specs, i don’t know, but i’m glad it was there.

thanks to ivan for getting me to check out argparse in the first place.


You can follow James on Mastodon for more frequent updates and other random thoughts.
You can follow James on Twitter for more frequent updates and other random thoughts.
You can support James on GitHub if you'd like to help sustain this kind of content.
You can support James on Patreon if you'd like to help sustain this kind of content.


Comments

Nothing yet.


Post a comment



(sorry but the spammers were getting too crazy!)

Thank you

Your comment has been submitted and will be published if it gets approved.

Click here to see the patch you generated.

OK