diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 50a762a1..0c3153f2 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -31,6 +31,8 @@ Changed parameter of ``ArgumentParser.{dump, save, get_defaults}`` renamed to ``skip_validation`` (`#639 `__). +- Fail when ``Namespace`` is used as a type to make it clear about being + unsupported (`#656 `__). Fixed ^^^^^ diff --git a/jsonargparse/_typehints.py b/jsonargparse/_typehints.py index d3a89d05..bd6b2f71 100644 --- a/jsonargparse/_typehints.py +++ b/jsonargparse/_typehints.py @@ -299,6 +299,9 @@ def is_supported_typehint(typehint, full=False): """Whether the given type hint is supported.""" typehint = get_unaliased_type(typehint) + if is_subclass(typehint, Namespace): + raise ValueError("jsonargparse.Namespace is only intended for parsing results and not supported as a type.") + supported = ( typehint in root_types or get_typehint_origin(typehint) in root_types diff --git a/jsonargparse_tests/test_typehints.py b/jsonargparse_tests/test_typehints.py index 1be16ec0..16ae8097 100644 --- a/jsonargparse_tests/test_typehints.py +++ b/jsonargparse_tests/test_typehints.py @@ -67,6 +67,12 @@ def test_add_argument_failure_given_type_and_action(parser): ctx.match("Providing both type and action not allowed") +@pytest.mark.parametrize("typehint", [Namespace, Optional[Namespace], Union[int, Namespace], List[Namespace]]) +def test_namespace_unsupported_as_type(parser, typehint): + with pytest.raises(ValueError, match="Namespace .* not supported as a type"): + parser.add_argument("--ns", type=typehint) + + # basic types tests