Skip to content

Commit

Permalink
Fail when Namespace is used as a type to make it clear about being un…
Browse files Browse the repository at this point in the history
…supported (#656)
  • Loading branch information
mauvilsa authored Dec 27, 2024
1 parent 6fcae42 commit 2a9cacd
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ Changed
parameter of ``ArgumentParser.{dump, save, get_defaults}`` renamed to
``skip_validation`` (`#639
<https://github.com/omni-us/jsonargparse/pull/639>`__).
- Fail when ``Namespace`` is used as a type to make it clear about being
unsupported (`#656 <https://github.com/omni-us/jsonargparse/pull/656>`__).

Fixed
^^^^^
Expand Down
3 changes: 3 additions & 0 deletions jsonargparse/_typehints.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions jsonargparse_tests/test_typehints.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down

0 comments on commit 2a9cacd

Please sign in to comment.