@@ -1005,32 +1005,33 @@ choices
10051005^^^^^^^
10061006
10071007Some command-line arguments should be selected from a restricted set of values.
1008- These can be handled by passing a container object as the `` choices `` keyword
1008+ These can be handled by passing a container object as the * choices * keyword
10091009argument to :meth: `~ArgumentParser.add_argument `. When the command line is
1010- parsed, argument values will be checked, and an error message will be displayed if
1011- the argument was not one of the acceptable values::
1012-
1013- >>> parser = argparse.ArgumentParser(prog='PROG')
1014- >>> parser.add_argument('foo', choices='abc')
1015- >>> parser.parse_args('c'.split())
1016- Namespace(foo='c')
1017- >>> parser.parse_args('X'.split())
1018- usage: PROG [-h] {a,b,c}
1019- PROG: error: argument foo: invalid choice: 'X' (choose from 'a', 'b', 'c')
1020-
1021- Note that inclusion in the ``choices `` container is checked after any type _
1022- conversions have been performed, so the type of the objects in the ``choices ``
1010+ parsed, argument values will be checked, and an error message will be displayed
1011+ if the argument was not one of the acceptable values::
1012+
1013+ >>> parser = argparse.ArgumentParser(prog='game.py')
1014+ >>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
1015+ >>> parser.parse_args(['rock'])
1016+ Namespace(move='rock')
1017+ >>> parser.parse_args(['fire'])
1018+ usage: game.py [-h] {rock,paper,scissors}
1019+ game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
1020+ 'paper', 'scissors')
1021+
1022+ Note that inclusion in the *choices * container is checked after any type _
1023+ conversions have been performed, so the type of the objects in the *choices *
10231024container should match the type _ specified::
10241025
1025- >>> parser = argparse.ArgumentParser(prog='PROG ')
1026- >>> parser.add_argument('foo ', type=complex , choices=[ 1, 1j] )
1027- >>> parser.parse_args('1j'.split( ))
1028- Namespace(foo=1j )
1029- >>> parser.parse_args('-- -4'.split() )
1030- usage: PROG [-h] {1,1j }
1031- PROG : error: argument foo : invalid choice: (-4+0j) (choose from 1, 1j )
1032-
1033- Any object that supports the ``in `` operator can be passed as the `` choices ``
1026+ >>> parser = argparse.ArgumentParser(prog='doors.py ')
1027+ >>> parser.add_argument('door ', type=int , choices=range( 1, 4) )
1028+ >>> print( parser.parse_args(['3'] ))
1029+ Namespace(door=3 )
1030+ >>> parser.parse_args(['4'] )
1031+ usage: doors.py [-h] {1,2,3 }
1032+ doors.py : error: argument door : invalid choice: 4 (choose from 1, 2, 3 )
1033+
1034+ Any object that supports the ``in `` operator can be passed as the * choices *
10341035value, so :class: `dict ` objects, :class: `set ` objects, custom containers,
10351036etc. are all supported.
10361037
0 commit comments