[Python-Dev] argparse ugliness (original) (raw)

Ron Adam rrr at ronadam.com
Mon Mar 8 18:17:13 CET 2010


Steven Bethard wrote:

On Mon, Mar 8, 2010 at 7:40 AM, Steven Bethard <steven.bethard at gmail.com> wrote:

On Sun, Mar 7, 2010 at 11:49 AM, Guido van Rossum <guido at python.org> wrote:

On Sun, Mar 7, 2010 at 4:29 AM, Neal Becker <ndbecker2 at gmail.com> wrote:

Brian Curtin wrote:

On Fri, Mar 5, 2010 at 12:51, Neal Becker <ndbecker2 at gmail.com> wrote:

I generally enjoy argparse, but one thing I find rather ugly and unpythonic.

parser.addargument ('--plot', action='storetrue') Specifying the argument 'action' as a string is IMO ugly. What else would you propose? FWIW, this is the same in optparse. I would have thought use the object itself, instead of a string that spells the object's name. What object? How would you write the example instead then? In argparse, unlike optparse, actions are actually defined by objects with a particular API, and the string is just a shorthand for referring to that. So: parser.addargument ('--plot', action='storetrue') is equivalent to: parser.addargument('--plot', argparse.StoreTrueAction) Sorry, that should have been: parser.addargument('--plot', action=argparse.StoreTrueAction) Because the names are so long and you'd have to import them, I've left them as private attributes of the module, but if there's really demand, we could rename them to argparse.StoreTrueAction, etc.

I like the strings. They are simple and easy to use/read and they don't have to be created or imported before the parser is defined. That allows me to put the parser setup right after the 'if name == 'main':' so it's easy to find and read. It also allows me to not import or create objects that may be expensive in either time or resources if I'm not going to use them.

Also the strings help separate the parser from the rest of your program in a much cleaner way. This can make your programs more modular and easier to modify and maintain.

Ron



More information about the Python-Dev mailing list