Lets said I want to make a super simple function which joins a basepath together with n-paths. How would I type hint this function.
Here is an example:
import os.path
from os import path
from typing import Union, Tuple, Optional
def joinPaths(basePath : str, *paths : Optional[str]) -> str:
return os.path.join(basePath, *paths)
if __name__ == "__main__":
dataPath = joinPaths('DataFolder', 'subfolder', 'subsubfolder', 'text.txt')
print(dataPath)
Output:
"DataFolder\subfolder\subsubfolder\text.txt"
The ouput is correctly formatted for my needs.
I tried with the above code but 'mypy' gives
error: Argument 2 to "join" has incompatible type "*Tuple[Optional[str], ...]"; expected "Union[str, _PathLike[str]]"
I don't realy understand what this means and how to fix it
Edit Fixed it with the following
import os.path
from os import path
from typing import Union, Tuple, Optional, TypeVar
PathLike = TypeVar("PathLike", str, None)
def joinPaths(basePath : str, *paths : Union[str, os.PathLike]) -> str:
return os.path.join(basePath, *paths)
if __name__ == "__main__":
dataPath = joinPaths('DataFolder', 'subfolder', 'subsubfolder', 'text.txt')
print(dataPath)