0

I'm using argparse to handle the command-line arguments to my program but it seems like the parser accepts arguments I haven't defined. I've managed to reproduce the issue with this minimal example:

import argparse

def init():
    parse_args()
    exit()

def parse_args():
    parser = argparse.ArgumentParser(add_help = False)
    parser.add_argument("--kmers")
    parser.parse_args()

if __name__ == '__main__':
    init()

Save this a in file say a.py and run:

python a.py --kmers /file.json

This exits normally; surprisingly, the following also works without the parser complaining:

python a.py --kmer /file.json

Which shouldn't be the case as --kmer is not a defined argument. Running this however raises an error:

python a.py --kmersss /file.json

`kmers.py: error: unrecognized arguments: --kmerss`

It seems to me that the parser accepts an argument as long as it is a unique prefix of something already defined. Is this the case?

Paghillect
  • 822
  • 1
  • 11
  • 30
  • 1
    [Yes](https://docs.python.org/2/library/argparse.html#argument-abbreviations-prefix-matching). – Blorgbeard Apr 24 '19 at 18:30
  • 1
    And it looks like you can [turn it off](https://stackoverflow.com/questions/33900846/disable-unique-prefix-matches-for-argparse-and-optparse) if you're on Python 3.5+ – Blorgbeard Apr 24 '19 at 18:31

1 Answers1

0

It is usually the case that one finds the answer to their question minutes after posting it.

This behavior has to do with the allow_abbrev option to the parser which is set to True by default. With this enabled, the parser will happily accept any passed arguments as longs as it is a non-ambiguous substring of a defined one.

This was been previously reported as a bug here here.

Paghillect
  • 822
  • 1
  • 11
  • 30