Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

That's annoying for sure. Though a different problem.

All the kw_only=True argument for dataclasses does is require that you pass any fields you want to provide as keyword arguments instead of positional arguments when instantiating a dataclass. So:

    obj = MyDataclass(a=1, b=2, c=3)
Instead of:

    obj = MyDataclass(1, 2, 3)  # This would be an error with kw_only=True
The problem you're describing in boto3 (and a lot of other API bindings, and a lot of more layered Python code) is that methods often take in **kwargs and pass them down to a common function that's handling them. From the caller's perspective, **kwargs is a black box with no details on what's in there. Without a docstring or an understanding of the call chain, it's not helpful.

Python sort of has a fix for this now, which is to use a TypedDict to define all the possible values in the **kwargs, like so:

    from typing import TypedDict, Unpack


    class MyFuncKwargs(TypedDict):
        arg1: str
        arg2: str
        arg3: int | None


    def my_outer_func(
        **kwargs: Unpack[MyFuncKwargs],
    ) -> None:
        _my_inner_func(**kwargs)


    def _my_inner_func(
        *,
        arg1: str,
        arg2: str,
        arg3: int | None,
    ) -> None:
        ...
By defining a TypedDict and typing **kwargs, the IDE and docs can do a better job of showing what arguments the function really takes, and validating them.

Also useful when the function is just a wrapper around serializing **kwargs to JSON for an API, or something.

But this feature is far from free to use. The more functions you have, the more of these you need to create and maintain.

Ideally, a function could type **kwargs as something like:

    def my_outer_func(
        **kwargs: KwargsOf[_my_inner_func],
    ) -> None:
        ...
And then the IDEs and other tooling can just reference that function. This would help make the problem go away for many of the cases where **kwargs is used and passed around.


TypedDicts are so underutilized in general. I'm using them a lot even for simpler scripts


I don't see a point in using them in new code when I could just use a dataclass (or Pydantic in certain contexts). I've only found them useful when interfacing with older code that uses dicts for structured data.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: