0

That question will be strange in some point...

I'm trying to add the option strings in the parser after adding one argument.

For example

import argparse
p = argparse.ArgumentParser()
p.add_argument(dest = 'myvar')
p._actions[1].option_strings = ['-foo']
p.parse_args('-foo 1')

This example doesn't work, it says:

: error: the following arguments are required: -foo

Even though I'm supplying the argument...

Anyone know why this is occurring?

Is there some way to add the option strings after the add_argument method?

0

1 Answer 1

1

After looking at the source code of argparse, I found you also have to register the action by the option string it has:

import argparse

p = argparse.ArgumentParser()
p.add_argument(dest = 'myvar')
p._actions[1].option_strings = ['-foo']

# You also need to do this
p._option_string_actions['-foo'] = p._actions[1]

args = p.parse_args(['-foo', '100'])
print('myvar is', args.myvar)  # myvar is 1

Note the change when calling parse_args.

I hope this help!!

Sign up to request clarification or add additional context in comments.

5 Comments

I know this behaviour, and how the argparse acts using this syntax. Although my question is a little bit more complicated. I want to add the option strings after adding one argument....
@kaihami, the source code of argparse gave me the answer. I edited my answer above and think that is what you are looking for.
@kaihami The main problem is that you are trying to hack on argparse and thus, you were bypassing its registration mechanism and all the setup it does
Thank you indeed I forgot about p._option_strings_actions!
Please, @kaihami , mark my answer as the right one if you think it helped you. I will really appreciate it. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.