Typehints for functions that have variable signatures

https://lemmy.cafe/post/751680

Typehints for functions that have variable signatures - Lemmy Cafe

I know what I am asking is rather niche, but it has been bugging me for quite a while. Suppose I have the following function: python def foo(return_more: bool): .... if return_more: return data, more_data return data You can imagine it is a function that may return more data if given a flag. How should I typehint this function? When I use the function in both ways data = foo(False) data, more_data = foo(True) either the first or the 2nd statement would say that the function cannot be assigned due to wrong size of return tuple. Is having variable signature an anti-pattern? Is Python’s typehinting mechanism not powerful enough and thus I am forced to ignore this error?

def foo(return_more: bool) -> Union[Type1, Type2]:

You can also consider the new union tjat ws introduced with Pythoj .10, check PEP604 for details:

def foo(return_more: bool) -> Type1 | tuple[Type2,Type3]:

PEP 604 – Allow writing union types as X | Y | peps.python.org

Python Enhancement Proposals (PEPs)

Python >= 3.10 version:

def foo(return_more: bool) -> DataType | tuple[DataType, MoreDataType]: ...

But i would definitely avoid to do that. I would maybe do something like this instead:

def foo(return_more: bool) -> tuple[DataType, MoreDataType | None]: ... if return_more: return data, more_data return data, None

Or it data is a dict, just update it with more_data:

def foo(return_more: bool) -> dict[str, Any]: ... if return_more: return data.update(more_data) return data