Python Glossary Русский

Python 3.3+argparseterm

argparse.MetavarTypeHelpFormatter

help formatters

A help formatter that labels an argument's value with the name of its type: --n int instead of --n N.

Syntax

argparse.ArgumentParser(formatter_class=argparse.MetavarTypeHelpFormatter)

It reads type.__name__ from every argument, so it raises AttributeError if even one argument has no type (type=None) — which is any plain string argument. A lambda shows up as an ugly '<lambda>' in the help. So the formatter only fits when every argument has an explicit type, including type=str.

Examples

import argparse
parser = argparse.ArgumentParser(
    prog='app', formatter_class=argparse.MetavarTypeHelpFormatter)
parser.add_argument('--n', type=int)
print(parser.format_usage())  # → usage: app [-h] [--n int]
import argparse
parser = argparse.ArgumentParser(
    prog='app', formatter_class=argparse.MetavarTypeHelpFormatter)
parser.add_argument('--name')  # type не задан
try:
    parser.format_help()
except AttributeError as e:
    print(type(e).__name__)  # → AttributeError

See also

Open in the full glossarydocs.python.orgReport an inaccuracy