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 e.g. 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?
If you look at the documentation for open(), it accepts any of {str, bytes, os.PathLike object} for its filename argument.
To declare a function that accepts any of these:
import os
def dosomething(fname_arg : str | bytes | os.PathLike):
fname = os.fspath(fname_arg)
# fname = str(fname_arg) # would also work
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With