I have a function that receives 3 parameters: a: dict[str, str]
, b:dict[str, str]
, and c: dict[str, str]
.
The values/keys of these parameters are “linked”. They are based on a existing protocol and some combinations are not possible.
The keys in b
and c
will differ depending on a certain key in a
.
I have all the possible states and their combinations typed out.
type combination1 = tuple[SomeTypeA, SomeTypeB, SomeTypeC]
type combination2 = tuple[SomeTypeA2, SomeTypeB2, SomeTypeC3]
...
def function(state: combination1 | combination1):
a, b, c = state
if a["type"] == "1":
_ = b["some_key"] # this works
_ = b["some_other_key"] # typehints say that this key doesn't exist
if a["type"] == "2":
_ = b["some_key"] # typehints say that this key doesn't exist
_ = b["some_other_key"] # this works
The above works without a problem but my function should have a signature of function(a, b, c) -> None
with 3 parameters instead of function(state) -> None
. The function is used as a callback by another package and expects this signature.
Using *args
the function would run but type hinting works for only one combination:
def function(*args: *combination1):
a, b, c = args
if a["type"] == "1":
_ = b["some_key"] # this works
_ = b["some_other_key"] # typehints say that this key doesn't exist
If the following was allowed then my issue would be fixed, but it isn’t.
def function(*args: *combination1 | *combination2):
a, b, c = args
if a["type"] == "1":
_ = b["some_key"] # this works
_ = b["some_other_key"] # typehints say that this key doesn't exist
This last piece of returns an invalid syntax error: “Unpack operator not allowed in type annotation”
Any ideas on how to solve this, preferably only with typehints without typing.TypeGuard
using custom logic?