Correct way to get allowed arguments from ArgumentParser
<p><strong>Question:</strong> What is the intended / official way of accessing possible arguments from an existing <code>argparse.ArgumentParser</code> object?</p>

<p><strong>Example:</strong> Let's assume the following context:</p>

<pre><code>import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo', '-f', type=str)
</code></pre>

<p>Here I'd like to get the following list of allowed arguments:</p>

<pre><code>['-h', '--foo', '--help', '-f']
</code></pre>

<p>I found the following workaround which does the trick for me</p>

<pre><code>parser._option_string_actions.keys()
</code></pre>

<p>But I'm not happy with it, as it involves accessing a <code>_</code>-member that is not officially documented. Whats the correct alternative for this task?</p>

<p>I have to agree with Tryph's answer.</p>

<p>Not pretty, but you can retrieve them from <code>parser.format_help()</code>:</p>

<pre><code>import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--foo', '-f', type=str)
goal = parser._option_string_actions.keys()

def get_allowed_arguments(parser):
    lines = parser.format_help().split('\n')
    line_index = 0
    number_of_lines = len(lines)
    found_optional_arguments = False
    # skip the first lines until the section 'optional arguments'
    while line_index &lt; number_of_lines:
        if lines[line_index] == 'optional arguments:':
            found_optional_arguments = True
            line_index += 1
            break
        line_index += 1
    result_list = []
    if found_optional_arguments:
        while line_index &lt; number_of_lines:
            arg_list = get_arguments_from_line(lines[line_index])
            if len(arg_list) == 0:
                break
            result_list += arg_list
            line_index += 1
    return result_list

def get_arguments_from_line(line):
    if line[:2] != '  ':
        return []
    arg_list = []
    i = 2
    N = len(line)
    inside_arg = False
    arg_start = 2
    while i &lt; N:
        if line[i] == '-' and not inside_arg:
            arg_start = i
            inside_arg = True
        elif line[i] in [',',' '] and inside_arg:
            arg_list.append(line[arg_start:i+1])
            inside_arg = False
        i += 1
    return arg_list

answer = get_allowed_arguments(parser)
</code></pre>

<p>There's probably a regular expressions alternative to the above mess...</p>

python argparse