Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8543899
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T12:25:15+00:00 2026-06-11T12:25:15+00:00

Python 2.7’s argparse gives you two extension points where you can control how your

  • 0

Python 2.7’s argparse gives you two extension points where you can control how your command-line arguments are parsed: type functions and action classes.

Going from the built-in types and actions, the best practice seems to be that type functions should contain the validation/initialization code and actions should be concerned with storing values into namespace. The problem with this approach is when you have type-checking code that has side effects. Consider this simple example:

from argparse import ArgumentParser, FileType
argp = ArgumentParser()
argp.add_argument('-o', type=FileType('w'), default='myprog.out')
argp.parse_args(['-o', 'debug.out'])

If you run this, you find python will open two files on the system, myprog.out and debug.out. It would make more sense to only open debug.out when the user doesn’t supply the -o argument.

Poking around a bit, it seems that argparse will only call your type function on passed arguments or default arguments of type str. This is unfortunate if your type-checker has side-effects as it will be called on the default even if a value was passed. So for initialization with side-effects, maybe it would be better to do it in the action. The problem with this is that the action won’t be called if you supply a default value!

Consider the following code:

from argparse import ArgumentParser, Action

def mytype(arg):
    print 'checking type for ' + repr(arg)
    return arg

class OutputFileAction(Action):
    def __call__(self, parser, namespace, values, option_string=None):
        print 'running action for ' + repr(values)
        try:
            outstream = open(values, 'w')
        except IOError as e:
            raise ArgumentError('error opening file ' + values)
        setattr(namespace, self.dest, outstream)

argp = ArgumentParser()
argp.add_argument('-o', type=mytype, action=OutputFileAction, default='myprog.out')

Now try to use it:

>>> argp.parse_args([])
checking type for 'myprog.out'
Namespace(o='myprog.out')
>>> argp.parse_args(['-o', 'debug.out'])
checking type for 'myprog.out'
checking type for 'debug.out'
running action for 'debug.out'
Namespace(o=<open file 'debug.out', mode 'w' at 0x2b7fced07300>)

Who ordered that behavior? Is there a sane way to have default values behave exactly as if they were passed in by the user? Or to not typecheck defaults when values are supplied?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T12:25:16+00:00Added an answer on June 11, 2026 at 12:25 pm

    As far as I am aware, there is no “sensible” way to do this. Of course, it is trivial to leave the type conversion off and then postprocess the Namespace returned from parse_args:

    args = argp.parse_args()
    args.o = open(args.o,'w')
    

    but I suppose that isn’t what you’re looking for.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Python, through it's readline bindings allows for great command-line autocompletion (as described in here
Python's logging functions allow you to pass them multiple arguments that they can interpolate
(Python) Given two numbers A and B. I need to find all nested groups
Python beginner >>> import oauth2 Traceback (most recent call last): File , line 1,
python newbie here. I'm writing the code to control an experiment that has multiple
Python extension modules written in C are faster than the equivalent programs written in
Python 2 and 3, are the bytecode (pyo & pyc) backward compatible? can i
Python's arbitrary precision decimals are lovely, but I can't seem to find a way
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) [GCC 4.5.2] on linux2 Type help, copyright,
Python is pretty clean, and I can code neat apps quickly. But I notice

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.