Skip to content

Commit

Permalink
Respect TypedDict.__required_keys__
Browse files Browse the repository at this point in the history
  • Loading branch information
a-gardner1 committed Oct 14, 2024
1 parent 2160982 commit fd1b8d7
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
13 changes: 12 additions & 1 deletion jsonargparse/_typehints.py
Original file line number Diff line number Diff line change
Expand Up @@ -931,7 +931,18 @@ def adapt_typehints(
kwargs["prev_val"] = None
val[k] = adapt_typehints(v, subtypehints[1], **kwargs)
if type(typehint) in typed_dict_meta_types:
if typehint.__total__:
if hasattr(typehint, "__required_keys__"):
required_keys = set(typehint.__required_keys__)
# The standard library TypedDict below Python 3.11 does not store runtime
# information about optional and required keys when using Required or NotRequired.
# Thus, capture explicitly Required keys
required_keys.update(
{k for k, v in typehint.__annotations__.items() if get_typehint_origin(v) in required_types}
)
# The standard library TypedDict in Python 3.8 does not store runtime information
# about which (if any) keys are optional. See https://bugs.python.org/issue38834.
# Thus, fall back to totality and explicitly Required keys
elif typehint.__total__:
required_keys = {
k for k, v in typehint.__annotations__.items() if get_typehint_origin(v) not in not_required_types
}
Expand Down
32 changes: 32 additions & 0 deletions jsonargparse_tests/test_typehints.py
Original file line number Diff line number Diff line change
Expand Up @@ -679,6 +679,38 @@ def test_invalid_inherited_unpack_typeddict(parser, init_args):
parser.parse_args([f"--testclass={json.dumps(test_config)}"])


@pytest.mark.skipif(sys.version_info < (3, 9), reason="Python 3.8 lacked runtime inspection of TypedDict required keys")
def test_typeddict_totality_inheritance(parser):

class BottomDict(TypedDict, total=True):
a: int

class MiddleDict(BottomDict, total=False):
b: int

class TopDict(MiddleDict, total=True):
c: int

parser.add_argument("--middledict", type=MiddleDict, required=False)
parser.add_argument("--topdict", type=TopDict, required=False)
assert {"a": 1} == parser.parse_args(["--middledict={'a': 1}"])["middledict"]
assert {"a": 1, "b": 2} == parser.parse_args(["--middledict={'a': 1, 'b': 2}"])["middledict"]
with pytest.raises(ArgumentError) as ctx:
parser.parse_args(["--middledict={}"])
ctx.match("Missing required keys")
with pytest.raises(ArgumentError) as ctx:
parser.parse_args(['--middledict={"b": 2}'])
ctx.match("Missing required keys")
assert {"a": 1, "c": 2} == parser.parse_args(["--topdict={'a': 1, 'c': 2}"])["topdict"]
assert {"a": 1, "b": 2, "c": 3} == parser.parse_args(["--topdict={'a': 1, 'b': 2, 'c': 3}"])["topdict"]
with pytest.raises(ArgumentError) as ctx:
parser.parse_args(['--topdict={"a": 1, "b": 2}'])
ctx.match("Missing required keys")
with pytest.raises(ArgumentError) as ctx:
parser.parse_args(['--topdict={"b":2, "c": 3}'])
ctx.match("Missing required keys")


def test_mapping_proxy_type(parser):
parser.add_argument("--mapping", type=MappingProxyType)
cfg = parser.parse_args(['--mapping={"x":1}'])
Expand Down

0 comments on commit fd1b8d7

Please sign in to comment.