[Python-3000] Move argv[0]? (Re: Unicode and OS strings)
Ron Adam
rrr at ronadam.com
Tue Sep 18 22:52:50 CEST 2007
Steven Bethard wrote:
> On 9/17/07, Ron Adam <rrr at ronadam.com> wrote:
>> Greg Ewing wrote:
>>> Thomas Wouters wrote:
>>>> If you want to put more meaning in the argv list, use an option
>>>> parser.
>>> I want to put *less* meaning in it, not more. :-)
>>> And using an argument parser is often overkill for
>>> simple programs.
>> Would it be possible to split out the (pre) parsing from optparse so that
>> instead of returning a list, it returns a dictionary of attributes and values?
>>
>> This would only contain what was given in the command line as a first
>> "lighter weight" step to parsing the command line.
>>
>> opts = opt_parser(argv)
>> command_name = opts['argv0'] # better name for argv0?
>
> You might look at argparse_ which allows you to treat positional
> arguments just like optional ones. So you'd write::
>
> parser = argparse.ArgumentParser()
> parser.add_argument('command') # positional argument
> parser.add_argument('--option') # optional argument
> args = parser.parse_args()
> ... args.command ...
> ... args.option ...
>
> If you're really insistent on a dict interface instead of an attribute
> interface, the object returned by parse_args() is just a simple
> namespace, so vars(args) will give you a dict.
>
> .. _argparse: http://argparse.python-hosting.com/
I think a dict interface or even a (list, dict) interface is better in this
case. It makes it much easier to use these in already existing functions
and other objects.
Once an objects data is stored in named attributes, it becomes a more
specialized data structure and requires more specialized functions and
objects to make use of it. In the above case the attribute names are not
even consistent because they depend on the .add_argument() calls. I think
this makes it harder to write reusable code.
If the parser returned a list and dictionary pair, it might make it easy to
use the (*args, **kwds) form to pass these values directly to functions or
other objects.
That also gives an easy and light weight way to validate command line
arguments in the simplest cases without a lot of work. Just let the
function receiving them validate its arguments at call time.
Regards,
Ron
More information about the Python-3000
mailing list