I'm trying to add type hints to a file system related library, where a lot of functions take a path that is either of str or bytes type. I can handle my own functions by using overloads, but I'm struggling to handle simple operations or standard library functions that are called inside with arguments of either type. Here is a simplified example:
@overload
def join_paths(s1: str, s2: str) -> str: ...
@overload
def join_paths(s1: bytes, s2: bytes) -> bytes: ...
def join_paths(s1: Union[str, bytes],
s2: Union[str, bytes]) -> Union[str, bytes]:
return s1 + s2
The overloads work fine if I want to call this function from elsewhere, but my problem is with the s1 + s2 statement, which causes mypy to issue the warnings:
example.py:74: error: Unsupported operand types for + ("str" and "bytes") [operator]
example.py:74: error: Unsupported operand types for + ("bytes" and "str") [operator]
What I want to express is that either both operands are of type str or both are of bytes type, similar to what is done to my own function using the overloads.
I don't have much experience with typing, so I may just miss the obvious solution, but so far I haven't found how to adapt this to avoid the warnings.