argparse FileType v.s default arguments...

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 -- Mike Meyer <mwm@mired.org> http://www.mired.org/ Independent Software developer/SCM consultant, email for more information. O< ascii ribbon campaign - stop html mail - www.asciiribbon.org

On Mon, Apr 30, 2012 at 3:59 PM, Gregory P. Smith <greg@krypto.org> wrote:
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

On Mon, Apr 30, 2012 at 3:59 PM, Gregory P. Smith <greg@krypto.org> wrote:
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
participants (2)
-
Gregory P. Smith
-
Mike Meyer