[Python] Make argparse treat dashes and underscore identically

Discussão em 'Python' iniciado por Stack, Abril 7, 2025.

  1. Stack

    Stack Membro Participativo

    argparse replaces dashes in optional arguments by underscores to determine their destination:

    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--use-unicorns', action='store_true')
    args = parser.parse_args(['--use-unicorns'])
    print(args) # returns: Namespace(use_unicorns=True)


    However the user has to remember whether the option is --use-unicorns or --use_unicorns; using the wrong variant raises an error.

    This can cause some frustration as the variable args.use_unicorns in the code does not make it clear which variant was defined.

    How can I make argparse accept both --use-unicorns and --use_unicorns as valid ways to define this optional argument?

    Continue reading...

Compartilhe esta Página