Skip to content

Commit 1ba9012

Browse files
authored
Fix parsing of floats with implicit leading zero (#847)
1 parent db65582 commit 1ba9012

4 files changed

Lines changed: 19 additions & 2 deletions

File tree

CHANGELOG.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ Fixed
2020
- Positional arguments with ``nargs="*"`` or ``nargs="?"`` now correctly allow
2121
default values, matching standard argparse behavior (`#846
2222
<https://github.com/omni-us/jsonargparse/pull/846>`__).
23+
- Parsing of floats with implicit leading zero (e.g. ``-.5``) not working (`#847
24+
<https://github.com/omni-us/jsonargparse/pull/847>`__).
2325

2426
Changed
2527
^^^^^^^

jsonargparse/_loaders_dumpers.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,13 @@ def json_or_yaml_load(value):
176176
return json_load(value)
177177

178178

179+
def basic_json_or_yaml_load(value):
180+
loaded_value = load_basic(value)
181+
if loaded_value is not not_loaded:
182+
return loaded_value
183+
return json_or_yaml_load(value)
184+
185+
179186
json_or_yaml_loader_exceptions = get_loader_exceptions("yaml" if pyyaml_available else "json")
180187

181188

jsonargparse/_typehints.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,8 @@
6262
validating_defaults,
6363
)
6464
from ._loaders_dumpers import (
65+
basic_json_or_yaml_load,
6566
get_loader_exceptions,
66-
json_or_yaml_load,
6767
json_or_yaml_loader_exceptions,
6868
load_value,
6969
)
@@ -800,7 +800,7 @@ def adapt_typehints(
800800
elif typehint in leaf_types:
801801
if isinstance(val, str) and typehint is not str:
802802
with suppress(*json_or_yaml_loader_exceptions):
803-
val = json_or_yaml_load(val)
803+
val = basic_json_or_yaml_load(val)
804804
if typehint is float and isinstance(val, int) and not isinstance(val, bool):
805805
val = float(val)
806806
if not isinstance(val, typehint) or (typehint in (int, float) and isinstance(val, bool)):

jsonargparse_tests/test_typehints.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,14 @@ def test_float_scientific_notation(parser):
151151
assert 1e-3 == parser.parse_args(["--num=1e-3"]).num
152152

153153

154+
@parser_modes
155+
def test_float_implicit_leading_zero(parser):
156+
parser.parser_mode = "yaml"
157+
parser.add_argument("--num", type=float)
158+
assert 0.5 == parser.parse_args(["--num=.5"]).num
159+
assert -0.5 == parser.parse_args(["--num=-.5"]).num
160+
161+
154162
def test_complex_number(parser):
155163
parser.add_argument("--complex", type=complex)
156164
cfg = parser.parse_args(["--complex=(2+3j)"])

0 commit comments

Comments
 (0)