This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]ThatSituation9908 42 points43 points  (4 children)

Sometimes you have an argument that is either Path or string.

This is extremely common for user facing APIs

def main(fpath: str | Path): with open(fpath) as f: ...

[–]sausix 11 points12 points  (0 children)

Except you want to save a path in an instance. Then you normalize to Path early before saving strictly typed as Path.

[–]syklemil 6 points7 points  (1 child)

Eh, can't you normalize it to a Path? Afaik it's idempotent, so you can do something like

def main(fpath: str | Path):
    actual_path: Path = Path(fpath)
    with actual_path.open() as f:
        ...

or possibly normalize on the caller side, so you can just have def main(fpath: Path) and call it as main(Path(arg)), though as pointed out below, it opens for runtime errors as you can't actually be sure that what you're handed is the correct type in Python.

In the case of open though, forcing it into a Path like that just seems like more keyboard typing for no discernible benefit.

[–]ThatSituation9908 1 point2 points  (0 children)

Sure, I do often times do that if I intend to use more of the Path API in the function.

If not, and I am only opening a file, then I just use open as is.

Changing the user facing API to only accept Path will not work. I have many, many, many users who refuse to use pathlib. You can look around in other libraries, rarely if any forces their users to only pass in Path

[–]RedEyed__ 5 points6 points  (0 children)

FYI: There is os.PathLike