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

Mike Meyer mwm at mired.org
Mon Apr 30 19:33:38 CEST 2012

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

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')?

Mike Meyer <mwm at 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

More information about the Python-ideas mailing list