This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author paul.j3
Recipients avdwoude, paul.j3, rhettinger
Date 2020-10-29.16:53:10
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1603990391.05.0.573423207508.issue42191@roundup.psfhosted.org>
In-reply-to
Content
Do you realize that `choices` can be a dictionary?  And since you want the user to supply a key, not a value, you might not want to use a type that does the conversion.

To illustrate consider two ways of using a simple dictionary.

import argparse

adict = {'a': [1,2,3], 'b': 'astring'}

parser = argparse.ArgumentParser()
parser.add_argument('-f', 
    type = lambda x: adict.get(x,x),
    choices = list(adict.values())
    )
parser.add_argument('-g', choices = adict)

args =  parser.parse_args()
print(args)
print(args.f, adict[args.g])

sample runs:

valid key:

    0942:~/mypy$ python3 issue42191.py -f a -g a
    Namespace(f=[1, 2, 3], g='a')
    [1, 2, 3] [1, 2, 3]

help:

    0945:~/mypy$ python3 issue42191.py -h
    usage: issue42191.py [-h] [-f {[1, 2, 3],astring}] [-g {a,b}]

    optional arguments:
        -h, --help            show this help message and exit
        -f {[1, 2, 3],astring}
        -g {a,b}

Error cases:

    0945:~/mypy$ python3 issue42191.py -f x
    usage: issue42191.py [-h] [-f {[1, 2, 3],astring}] [-g {a,b}]
    issue42191.py: error: argument -f: invalid choice: 'x' (choose from 
    [1, 2, 3], 'astring')

    0945:~/mypy$ python3 issue42191.py -g x
    usage: issue42191.py [-h] [-f {[1, 2, 3],astring}] [-g {a,b}]
    issue42191.py: error: argument -g: invalid choice: 'x' (choose from 
    'a', 'b')

With -g, we have to perform the dictionary lookup after parsing, but choices, {a,b}, are clear in both the help and error.

With -f, both the help (which uses str) and the error, give wrong user choices, the dictionary values rather than the keys.
History
Date User Action Args
2020-10-29 16:53:11paul.j3setrecipients: + paul.j3, rhettinger, avdwoude
2020-10-29 16:53:11paul.j3setmessageid: <1603990391.05.0.573423207508.issue42191@roundup.psfhosted.org>
2020-10-29 16:53:11paul.j3linkissue42191 messages
2020-10-29 16:53:10paul.j3create
Morty Proxy This is a proxified and sanitized view of the page, visit original site.