Variadic typing for kwargs, namedtuple

I have an API pattern where the caller of a function can name inputs on-the-fly (via kwargs) and those same names are accessible in the return object (typically namedtuple or dynamically created NamedTuple).

For example, a short-circuiting, async wait_any() intended for a heterogenous set of input functions, where return values of interest can be captured:

results = await wait_any(foo, bar_finished=bar, baz_status=baz)
if results.bar_finished: ...

In my organization, the utility of this pattern is proven over years, and it’s in heavy use. For an example function from an open source module, see trio_util.compose_values().

I would really love to add proper typing to these functions, such that the member types of the output object can be inferred. From my rudimentary understanding of Python typing, there are two obstacles:

  1. variadic typing on kwargs is not supported. PEP 646 says:

note that a type variable tuple may not be used as the type of **kwargs . (We do not yet know of a use case for this feature, so we prefer to leave the ground fresh for a potential future PEP.)

  1. namedtuple and NamedTuple do not support variadic typing. They do support generic typing as of Python 3.11, but I haven’t seen any discussion about variadic generics.

I’m not particularly tied to named tuples, but there doesn’t seem a better alternative (e.g. SimpleNamespace doesn’t support functional syntax).

1 Like

adding an obstacle:

  1. for a use case where the value types need some transformation (e.g. values are type Callable, but we want the return type), then it seems we need something like KeyType / ElementType / Map for TypedDict.