1

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)
Lampen
  • 75
  • 8
  • Just hint as `def joinPaths(basePath: str, *paths: str) -> str:`, It's not optionnal, which means : value or None, here you have `str` and the `*` operator does the rest – azro Feb 20 '21 at 14:27
  • I added the following line of code before the function: `PathLike = TypeVar("PathLike", str, Path, None)` and changed `*paths -> *paths : Union[str, os.PathLike]` Which fixed it – Lampen Feb 20 '21 at 14:29
  • str only is enough, if you pass only strings – azro Feb 20 '21 at 14:34

0 Answers0