New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
argparse: type=<callable> doesn't honor nargs > 1 #66248
Comments
From the documentation, I think that argparse should pass the entire nargs-long string to the "type=" callable. Instead, it only passes the first argument (of nargs), making it impossible within argparse's framework to check for a tuple of mixed types, e.g., 2 ints and a float (my case), or a string and three numbers, etc. See attached reproducer. |
Nope. The documentation says:
The type function is applied to each argument independently. It would be easy enough to make this explicit in one of the nargs multi-argument examples by using type as well. |
Note that
becomes
Your 'type' function sees those 3 strings individually. Try printing 'string' the first thing in your function to see what we mean. |
Yes, I know. My function just sees '1', but I think it should see '1 2 3' so that it can figure out what to do. That's impossible (well, impossible without saving state between calls) when it sees the arguments piecemeal. Sent from my iPhone
|
What you want is a custom Action rather than a custom Type. from the documentation: >>> class FooAction(argparse.Action):
... def __call__(self, parser, namespace, values, option_string=None):
... print('%r %r %r' % (namespace, values, option_string))
... setattr(namespace, self.dest, values) 'values' will be the list ['1','2','3'], which you test and manipulate, before finally saving it to the 'namespace'. ret = (int(values[0]), int(values[1]), float(values[2]))
setattr(namespace, self.dest, ret) Setting 'nargs=3' ensures that this action will always get a 3 item list. If the parser can't give it 3 items, it will raise an error rather than call your Action. 'optparse' passed the remaining argument strings to Option's callback, which could consume as many as it wanted. 'argparse' does not give the Actions that power. There is a fundamental difference in the parsing algorithm. |
Just had a chance to try this, and this does exactly what I wanted from On Fri, Jul 25, 2014 at 4:17 PM, paul j3 <report@bugs.python.org> wrote:
|
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: