[Python-ideas] argparse FileType v.s default arguments...

Gregory P. Smith greg at krypto.org
Mon Apr 30 21:59:09 CEST 2012

On Mon, Apr 30, 2012 at 10:33 AM, Mike Meyer <mwm at mired.org> wrote:

> While I really like the argparse module, I've run into a case I think
> it ought to handle that it doesn't.
> So I'm asking here to see if 1) I've overlooked something, and it can
> do this, or 2) there's a good reason for it not to do this or maybe 3)
> this is a bad idea.
> The usage I ran into looks like this:
> parser.add_argument('configfile', default='/my/default/config',
>                     type=FileType('r'), nargs='?')
> If I provide the argument, everything works fine, and it opens the
> named file for me. If I don't, parser.configfile is set to the string,
> which doesn't work very well when I try to use it's read method.
> Unfortunately, setting default to open('/my/default/config') has the
> side affect of opening the file. Or raising an exception if the file
> doesn't exist (which is a common reason for wanting to provide an
> alternative!)
> Could default handling could be made smarter, and if 1) type is set
> and 2) the value of default is a string, call pass the value of
> default to type? Or maybe a flag to make that happen, or even a
> default_factory argument (incompatible with default) that would accept
> something like default_factory=lambda: open('/my/default/config')?
>          Thanks,
>          <mike

This makes sense to me as described.  I suggest going ahead and file an
issue on bugs.python.org with the above.

-gps (who hasn't actually used argparse enough)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20120430/39255f88/attachment.html>

More information about the Python-ideas mailing list