This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: unstable behaviour for options in argparse
Type: behavior Stage: resolved
Components: Versions:
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: chris.jerdonek, eric.smith, gaborjbernat, paul.j3
Priority: normal Keywords:

Created on 2020-05-13 11:49 by gaborjbernat, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (5)
msg368776 - (view) Author: gaborjbernat (gaborjbernat) * Date: 2020-05-13 11:49
Consider the following code:

from argparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument("--clear-magic", action="store_true")
print(parser.parse_args(["--clear"]))

parser.add_argument("--clear", action="store_true")
print(parser.parse_args(["--clear"]))

This has the following output:

Namespace(clear_magic=True)
Namespace(clear=True, clear_magic=False)

I find it surprising and confusing why the clear magic option is accepted when clear is not defined. I'm tempted to say it's a bug. This unstable behaviour is very surprising when iteratively building up the parser.  

Discovered with https://github.com/pypa/virtualenv/issues/1824#issuecomment-627919033
msg368778 - (view) Author: Chris Jerdonek (chris.jerdonek) * (Python committer) Date: 2020-05-13 12:19
Do you know about this section of the docs?
https://docs.python.org/3/library/argparse.html#argument-abbreviations-prefix-matching
msg368779 - (view) Author: gaborjbernat (gaborjbernat) * Date: 2020-05-13 12:25
I did not, nm then. Thanks for the link.
msg368780 - (view) Author: Chris Jerdonek (chris.jerdonek) * (Python committer) Date: 2020-05-13 12:28
One thing that's interesting is that you don't get the "ambiguous option" error if what's provided is an exact match (even if a prefix of both).

For example, if you instead parsed "--clea", it would give the error:

> error: ambiguous option: --clea could match --clear-magic, --clear
msg368781 - (view) Author: Eric V. Smith (eric.smith) * (Python committer) Date: 2020-05-13 13:14
I wish the abbreviation behavior was opt-in instead of opt-out, but such is life.

Closing as not a bug.
History
Date User Action Args
2022-04-11 14:59:30adminsetgithub: 84795
2020-06-07 16:32:17paul.j3setnosy: + paul.j3
2020-05-13 13:14:25eric.smithsetstatus: open -> closed

type: behavior

nosy: + eric.smith
messages: + msg368781
resolution: not a bug
stage: resolved
2020-05-13 12:28:09chris.jerdoneksetmessages: + msg368780
2020-05-13 12:25:48gaborjbernatsetmessages: + msg368779
2020-05-13 12:19:25chris.jerdoneksetnosy: + chris.jerdonek
messages: + msg368778
2020-05-13 11:50:11gaborjbernatsettitle: argparse -> unstable behaviour for options in argparse
2020-05-13 11:49:46gaborjbernatcreate