Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 33.9k
Description
Bug report
If you add an optional argument to a parser with argparse containing dashes,
those are converted to _ automatically in the resulting Namespace object.
But if you add a positional argument containing a -, this is not converted and the resulting error message suggests the argument name containing the - instead of the _. Which is of course not possible (without getattr), because it's not a valid variable name in Python.
This behaviour is misleading and undocumented and I'd suggest to convert - to _ in positional arguments too.
Reproduction code:
importargparseparser=argparse.ArgumentParser("example") parser.add_argument("foo-bar", type=str) args=parser.parse_args() print("getattr", getattr(args, "foo-bar")) print("- replaced by _", args.foo_bar)Results in:
$ python3 main.py abc getattr aoe Traceback (most recent call last): File "/tmp/main.py", line 11, in<module> print("- replaced by _", args.foo_bar) AttributeError: 'Namespace' object has no attribute 'foo_bar'. Did you mean: 'foo-bar'?Compounding this issue is the fact, that you are prevented from using the dest option on add_argument to overwrite the name in the Namespace.
Your environment
- CPython versions tested on: Python 3.10.5
- Operating system and architecture: Linux
Metadata
Metadata
Assignees
Labels
Projects
Status