I want to create a function signature where an undefined
value and None
are distinct from each other.
So e.g.:
undefined = object()
def update(id: str, title: str = undefined, description: str):
data = {
"title": title,
"description": description,
}
# remove undefined key-value pairs from data
for key in data.keys():
if data[key] is undefined:
del data[key]
# send data to the server for further processing
Obviously this way I get conflicting types and the following error: Incompatible default for argument "description" (default has type "object", argument has type "str")
From the above example it can be seen that passing None
is completely valid as it will be replaced as the null
value of JSON while if undefined
is passed then the value won't be considered in the data.
I've tried to define undefined types like:
UndefinedStr = typing.Union[str, undefined]
But I got the following error: Variable "undefined" is not valid as a type
I guess that's because undefined
is an instance. So as a workaround I could do:
class Undefined:
pass
undefined = Undefined()
UndefinedStr = Union[str, Undefined]
This solution works, but to me feels a bit too broad.
So my question what is the best way to type hint this undefined use-case?
UPDATE:
Please don't focus on the fact that in the example the type of the title
argument is str
, the main intention behind this question is to find a universal type hint for a sentinel object that could be used in union with any other type.
In the meantime I've seen some progress on this specific issue within PEP-0661, so seemingly this has become a broader topic to discuss.
So far the best proposal is provided by PEP-661. Let's check that out and monitor it for a possible implementation.