What is the correct way in python to annotate a path with type hints?
10,874
I assume that typical path objects are either Path
s or str
s, as such you could use a Union
:
import pathlib
import typing
typing.Union[str, pathlib.Path]
Author by
Zacharias030
Updated on June 05, 2022Comments
-
Zacharias030 about 2 years
What is the proper way to annotate this simple utility function in python3 that reads from a file? It should accept
pathlib.Path
objects as well as any other common way of passing a path.def read_json(path: <TYPE HINT>): with open(path, 'rb') as f: data = json.load(f) return data
It seems to me as if this topic is in flux and I couldn't find a good place where this information was collected. I am interested in how to handle this in python 3.6, 3.7 and 3.8.
-
Martin Bonner supports Monica over 4 yearsIs there anywhere the standard functions are shown with type annotations? I couldn't find one, but "copy the annotation for
open
would be a good answer. -
Diogo over 3 years
open
usesfile: _OpenFile
as annotation, which is the unionUnion[AnyPath, int]
. -
maf88 over 3 yearsI use this
PathLike = TypeVar("PathLike", str, pathlib.Path, None)
.