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

Mike Meyer mwm at mired.org
Thu May 3 03:28:21 CEST 2012


On Mon, Apr 30, 2012 at 3:59 PM, Gregory P. Smith <greg at krypto.org> wrote:
> 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')?
> This makes sense to me as described.  I suggest going ahead and file an
> issue on bugs.python.org with the above.

I finally got around to this. There are already two issues that
address this problem, though in different ways: 12776 and 11389.

12776 includes a patch that worked against a build of a checkout
today. I've added a patch for test_argparse that adds tests to verify
that a default filename that doesn't exist with type=FileType
complains if you don't specify the argument, and opens the correct
file if you do.

     <mike



More information about the Python-ideas mailing list