简体   繁体   中英

Python typing: how to declare a variable that is either a path-like object (os.path) or a Path (pathlib)

I understand that module pathlib is new since Python 3.4 and I'm trying to use it as much as possible, but I have a lot of existing code with: "import os.path". I'm also trying to add typing to my code since a few weeks, but I'm still learning how to do it. I don't understand yet how to declare a variable with an ambiguous type - casu quo a variable which is either a so-called path-like object (os.path) or a Path (pathlib). Such a variable could then be used as input for eg an open statement. I tried this in a test module called test_typevar:

from pathlib import Path
from typing import TypeVar
from some_module import some_function

PathLike = TypeVar("PathLike", str, Path)
fpath: PathLike
line: str

# Now suppose fpath is returned by some code and it's either a Path or a path-like object:
fpath = some_function()
with open(fpath, "rt") as f:
    line = f.readline()
    ...

This is the error statement I'm getting:
error: Type variable "test_typevar.PathLike" is unbound
note: (Hint: Use "Generic[PathLike]" or "Protocol[PathLike]" base class to bind "PathLike" inside a class)
note: (Hint: Use "PathLike" in function signature to bind "PathLike" inside a function)

Can anybody explain things further?

Well you can simply use:

import pathlib
a = pathlib.PurePath("somepath")
a
returns: PureWindowsPath('somepath')

b = pathlib.Path("somepath")
b

returns: WindowsPath('somepath')

c = pathlib.PurePosixPath("somepath")
c
returns: PurePosixPath('somepath')

You can as well combine paths in brackes seperated with comma. Such as pathlib.Path(some path, next directory, finaly directory) and it will connets paths into one.

Know: PurePath is for windows, PurePosixPath is for UNIX and Path is for both, you can simply use Path or detect which OS you are on and then use proper PathType.

It will accept \\sss\\sss\\ path WINDOWS syntax and /sss/sss/ path UNIX syntax.

Edit: Path(..) should automaticly detect OS type so that's why you can see WindowsPath as return value (so it does not confuse you).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM