InsecureSignpost@kbin.socialtoPython@programming.dev•[Answered] Typehints for functions that have variable signatures
3·
1 year agoAgreed. I avoid having the shape of the return type be determined by arguments. Having the return type be generic is one thing. But this is different as here you are taking about returning 1 object or 2 objects.
In my opinion, it doesn’t. I’d rather have
foo()
anddetailed_foo()
overfoo(detailed: bool = False)
.Designing APIs can be hard at times. You have to shift your view to the person that will being using the code instead of the person implementing the code. There is also potential down side of returning a tuple or just a single thing if the single thing shares some of the same API as a tuple. Say the return type is
Union[str, tuple[str, str]
. Nowresult[0]
can either be the first string or the first character of the returned string depending on how the function was called. This could lead to the failure happening farther away from where the bug is, which makes debugging harder. That being said, if you do want to proceed this way,overload
withLiteral[True]
is the correct way to type this as mentioned in other comments.I also don’t think it’s overkill to extract functionality just for 2 functions. I often do that even when it is only used in one function. Maybe the number of lines to implement the block starts to make the primary function too long. Or the logic is a bit complicated, so it easier to give it a clearer name.