I have a function whose return type varies based on the value of one of it’s arguments:
class ReturnType(Enum):
NONE = 1
SCALAR = 2
VECTOR = 3
@overload
def perform_query(
sql: str, return_type: Literal[ReturnType.NONE], log_query: bool = ...
) -> None: ...
@overload
def perform_query(
sql: str, return_type: Literal[ReturnType.SCALAR], log_query: bool = ...
) -> int | float | bool | str: ...
@overload
def perform_query(
sql: str, return_type: Literal[ReturnType.VECTOR], log_query: bool = ...
) -> list[int | float | bool | str]: ...
def perform_query(
sql: str, return_type: ReturnType, log_query: bool = False
):
pass
This is fine, but there’s a lot of boilerplate: only one parameter changes between overloads, but every other parameter must be written out identically each time.
This creates redundancy and isn’t very DRY. (Imagine if I wanted to rename an input parameter, or if my function had many input arguments.)
Is there a way to avoid restating the arguments which don’t change?