Skip to content

Commit 2a8e097

Browse files
committed
- Added automatic Optional for arguments with default None #30.
1 parent 31d1b18 commit 2a8e097

File tree

3 files changed

+22
-0
lines changed

3 files changed

+22
-0
lines changed

CHANGELOG.rst

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,14 @@ follow `Semantic Versioning <https://semver.org/>`_
99
only be introduced in major versions with advance notice in the **Deprecated**
1010
section of releases.
1111

12+
v3.X.X (YYYY-MM-DD)
13+
-------------------
14+
15+
Added
16+
^^^^^
17+
- Automatic Optional for arguments with default None #30.
18+
19+
1220
v3.1.0 (2020-12-09)
1321
-------------------
1422

jsonargparse/signatures.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
from .util import _issubclass
88
from .actions import ActionEnum
9+
from .typing import is_optional
910
from .jsonschema import ActionJsonSchema
1011
from .optionals import docstring_parser_support, import_docstring_parse, dataclasses_support, import_dataclasses
1112

@@ -247,6 +248,8 @@ def update_has_args_kwargs(base, has_args=True, has_kwargs=True):
247248
kwargs = {'help': doc_params.get(name)}
248249
if not is_required:
249250
kwargs['default'] = default
251+
if default is None and not is_optional(annotation, object):
252+
annotation = Optional[annotation]
250253
elif not as_positional:
251254
kwargs['required'] = True
252255
if annotation in {str, int, float, bool} or \

jsonargparse_tests/signatures_tests.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -386,6 +386,17 @@ def __init__(self, c1: Optional[Class1]):
386386
self.assertEqual(2.3, cfg.c1.a2)
387387

388388

389+
def test_implicit_optional(self):
390+
391+
def func(a1: int = None):
392+
return a1
393+
394+
parser = ArgumentParser(error_handler=None)
395+
parser.add_function_arguments(func)
396+
397+
self.assertIsNone(parser.parse_args(['--a1=null']).a1)
398+
399+
389400
@unittest.skipIf(not docstring_parser_support, 'docstring-parser package is required')
390401
def test_docstring_parse_fail(self):
391402

0 commit comments

Comments
 (0)