Below is an example of a TypedDict:
class A(TypedDict):
a: int
b: int
How to specify only one of the two parameters need to be provided while maintaining the TypedDict/
i.e. if a is provided b is not required and vice versa.
I can put both marked as Optional or not required but then I run into exception since one of those two parameters is needed. I am trying to find the cleanest way of specifing.
I doubt that this can be done using TypedDict.
If you do not mind adding a dependency, you could do this using Pydantic.
It allows you to add testing logic at different stage of the validation of your data, and comes with some features better describe on the documentation.
Your issue could be solved with something like this:
from pydantic import BaseModel, root_validator
from typing import Optional
class A(BaseModel):
a: Optional[int] = None
b: Optional[int] = None
@root_validator(pre=True)
def check_exactly_one(cls, values):
a, b = values.get('a'), values.get('b')
if (a is None and b is None) or (a is not None and b is not None):
raise ValueError('Exactly one of "a" or "b" must be provided')
return values