python argparse optional erforderlich

# Short answer:
# With argparse, parameters starting with - or -- are considered optional by
# default.

# Longer answer:
# With argparse, parameters starting with - or -- are considered optional by
# default. All other parameters are positional parameters and are required
# by default. It is possible to require optional arguments, but this is a bit
# against their design. Since they are still part of the non-positional
# arguments, they will still be listed under the confusing header 
# “optional arguments” even if they are required. The missing square brackets
# in the usage part however show that they are indeed required.

# Solution:
# I create three categories as follows:
parser._action_groups.pop() # remove existing groups
required_pos = parser.add_argument_group('Required Positional Arguments')
required_nam = parser.add_argument_group('Required Named Arguments')
optional = parser.add_argument_group('Optional Arguments')

# To add arguments to the relevant category, use syntax like:
required_pos.add_argument('dataset', help='path to dataset')
required_nam.add_argument('-o', '--outfile', required=True, 
                          help='path to output file')
optional.add_argument('-t', '--threads', type=int, default=10,
                      help='number of CPUs to use. [default: %(default)s]')

# This creates help messages like:
Required Positional Arguments:
  dataset               path to dataset

Required Named Arguments:
  -o OUTFILE, --outdir OUTFILE
                        path to output file

Optional Arguments:
  -t THREADS, --threads THREADS
                        number of CPUs to use. [default: 10]
Charles-Alexandre Roy