The `choices` parameter of `add_argument()` is not functioning correctly.
hadipash opened this issue Β· comments
π Bug report
To reproduce
from jsonargparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument("--mode", type=int, default=1, choices=[0, 1])
cfg = parser.parse_args()
print(cfg.mode)
Output:
> python argparse_test.py --mode 1
usage: argparse_test.py [-h] [--mode {0,1}]
argparse_test.py: error: argument --mode: invalid choice: '1' (choose from 0, 1)
Expected behavior
Aligned with argparse
.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--mode", type=int, default=1, choices=[0, 1])
cfg = parser.parse_args()
print(cfg.mode)
Output:
> python argparse_test.py --mode 1
1
Environment
- jsonargparse version (e.g., 4.8.0): 4.27.1
- Python version (e.g., 3.9): 3.8.17
- How jsonargparse was installed (e.g.
pip install jsonargparse[all]
): pip install jsonargparse[signatures,omegaconf,urls]>=4.25.0 - OS (e.g., Linux): Ubuntu 20.04.5 LTS
Thank you for reporting! As an update. I looked at this some time ago, and it seems to require quite a complex change to fix. Unfortunately this relates to the fact that argparse wasn't really designed for extending as much as it has been done here. A fundamental change in the core implementation is required. I am not saying it won't be fixed, but very likely it will take time.
For the time being, as a workaround, consider using an Enum
as a type.