omni-us / jsonargparse

Implement minimal boilerplate CLIs derived from type hints and parse from command line, config files and environment variables
https://jsonargparse.readthedocs.io
MIT License
314 stars 42 forks source link

Support of `TypedDict`s #457

Closed PierreGtch closed 4 months ago

PierreGtch commented 6 months ago

Hi, Thanks for this great library! Extremely useful!!

🚀 Feature request

The idea here would be to support arguments with type typing.TypedDict.

Motivation

This feature would be great when we want to get a dictionary instead of a namespace but still want to check the keys and types of its elements.

This could also allow checking the elements in **kwargs: https://peps.python.org/pep-0692/

Pitch

For example, if a function calls another function, we could then pass arguments to the second one very easily:

# script.py
from typing import TypedDict
from jsonargparse import CLI

def aux(a: int = 1):
    print(a)

AuxKwargs = TypedDict("AuxKwargs", aux.__annotation__)

def main(aux_kwargs: AuxKwargs):
    aux(**aux_kwargs)

CLI(main)

Then we would be able to call:

python script.py --aux_kwargs.a=2

Alternatives

Currently, the only alternative for such cases is to use the dict type, which prevents from checking the key names and types individually. In the above example, the current alternative is:

def main(aux_kwargs: dict):
    aux(**aux_kwargs)
mauvilsa commented 6 months ago

Thank you for the proposal! Indeed the support for TypedDict is missing and can be added.

This could also allow checking the elements in **kwargs: https://peps.python.org/pep-0692/

A small note about this. jsonargparse already supports **kwargs without the need of type hinting. It does this via source code introspection. See classes-methods-and-functions and ast-resolver.