argparse and default for FileType

Robert Kern robert.kern at gmail.com
Fri Apr 8 16:22:27 EDT 2011


On 4/8/11 1:11 PM, Paolo Elvati wrote:
> Hi,
>
> I noticed a "strange" behavior of argparse.
> When running a simple code like the following:
>
> import argparse
> parser = argparse.ArgumentParser()
> parser.add_argument(
>    "-o",
>    default = 'fake',
>    dest = 'OutputFile',
>    type = argparse.FileType('w')
>   )
> args = parser.parse_args()
>
> I noticed that the default file (fake) is created every time I run the
> code, even when I explicitly set the -o flag, in which case it will
> produce both files.
> My goal instead is to erite the default file ONLY if the flag is not specified.
> For the moment, I solved it simply by removing the "default=fake" and
> adding the "required=True" keyword, but I was wondering what is the
> correct way of doing it (or if it is simply a bug).

It's an unfortunate (and possibly unforeseen by the author) consequence of how 
specifying defaults interact with specifying the type. I believe the way it is 
implemented is that the default values get injected into the namespace first. In 
order to do that, the default='fake' text that you specify needs to be passed 
through the type function to get the actual value that should be in the 
namespace. *Then* the arguments are parsed and override the defaults that are 
present.

It is possible that the order of these events could be switched around; i.e. the 
arguments get parsed first, then the defaults are injected into the namespace 
for those arguments which are not present. That might have side effects that I 
am not aware of, though, or it might just be too difficult to change at this 
point. Even if it can't be changed, you might be able to suggest what could be 
added to the argparse documentation that would have helped you realize this 
limitation sooner.

Open up a bug report on the Python bug tracker and assign it to the user 
"bethard", who is the author of argparse. He's usually pretty responsive.

   http://bugs.python.org/

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list