Skip to content

Commit 840a3f0

Browse files
authored
Fix choices with an int type not working correctly (#827)
1 parent 7e97a30 commit 840a3f0

File tree

3 files changed

+23
-0
lines changed

3 files changed

+23
-0
lines changed

CHANGELOG.rst

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,15 @@ The semantic versioning only considers the public API as described in
1212
paths are considered internals and can change in minor and patch releases.
1313

1414

15+
v4.45.1 (unreleased)
16+
--------------------
17+
18+
Fixed
19+
^^^^^
20+
- Choices with an int type not working correctly (`#827
21+
<https://github.com/omni-us/jsonargparse/pull/827>`__).
22+
23+
1524
v4.45.0 (2025-12-26)
1625
--------------------
1726

jsonargparse/_typehints.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -296,6 +296,8 @@ def prepare_add_argument(args, kwargs, enable_path, container, logger, sub_add_k
296296
if sub_add_kwargs:
297297
help_action.sub_add_kwargs = sub_add_kwargs
298298
kwargs["action"] = ActionTypeHint(typehint=typehint, enable_path=enable_path, logger=logger)
299+
if kwargs.get("choices"):
300+
kwargs["type"] = lambda v: adapt_typehints(v, typehint)
299301
return args
300302

301303
@staticmethod

jsonargparse_tests/test_core.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from io import StringIO
1010
from pathlib import Path
1111
from random import randint, shuffle
12+
from typing import Union
1213
from unittest.mock import patch
1314

1415
import pytest
@@ -183,6 +184,17 @@ def test_parse_args_choices_nargs_plus(parser):
183184
ctx.match("invalid choice")
184185

185186

187+
def test_parse_args_choices_type_int(parser):
188+
parser.add_argument("--ch", type=int, choices=[0, 1])
189+
assert 0 == parser.parse_args(["--ch=0"]).ch
190+
191+
192+
def test_parse_args_choices_type_union(parser):
193+
parser.add_argument("--ch", type=Union[int, str], choices=[0, 1, "x", "y"])
194+
assert 0 == parser.parse_args(["--ch=0"]).ch
195+
assert "x" == parser.parse_args(["--ch=x"]).ch
196+
197+
186198
def test_parse_object_simple(parser):
187199
parser.add_argument("--op", type=int)
188200
assert parser.parse_object({"op": 1}) == Namespace(op=1)

0 commit comments

Comments
 (0)