Skip to content

Totality of inherited TypedDict keys is not respected #596

@a-gardner1

Description

@a-gardner1

🐛 Bug report

One more TypedDict-related issue: totality of TypedDicts is not respected when inherited, which can lead to spurious expectations of required or optional arguments by the argument parser.

The problem is that the TypedDict.__required_keys__ attribute is ignored by jsonargparse. For additional context, see python/cpython#83015 and python/cpython#17214.

I have gone ahead an opened a PR (#597) with a suggested fix.

To reproduce

from jsonargparse import ArgumentParser
import pytest

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)
# the following should (but does not) raise an ArgumentError about missing required keys
with pytest.raises(ArgumentError) as ctx:
    parser.parse_args(['--middledict={}'])
ctx.match("Missing required keys")
with pytest.raises(ArgumentError) as ctx:
    assert {"b": 2} == parser.parse_args(["--middledict={'b': 2}"])["middledict"]
ctx.match("Missing required keys")
# the following should not (but does) raise an ArgumentError about missing required keys
assert {"a": 1, "c": 2} == parser.parse_args(["--topdict={'a': 1, 'c': 2}"])["topdict"]

Expected behavior

The assertions should evaluate to true.

Environment

  • jsonargparse version: 4.32.1
  • Python version: 3.11.6
  • How jsonargparse was installed: pip
  • OS: Ubuntu 20.04

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions