Op 19/06/2023 om 10:43 schreef Peter Slížik via Python-list:
Hello,

what is the preferred way of annotating file system paths?

This StackOverflow answer <https://stackoverflow.com/a/58541858/1062139>
(and a few others) recommend using the

str | os.PathLike

union.

However, byte arrays can be used as paths too, and including them
would make the annotation quite long.
You don't have to type out the whole thing every time. Define it somewhere:

PathLike = str | bytes | os.PathLike

and then you can use PathLike everywhere.
I also believe that str confirms to the PathLike definition. Please,
correct me if I'm wrong.
I don't think so: os.PathLike instances must have a __fspath__() method, which str and bytes don't have.
And finally - using paths in Python programs is so common, that one
would expect to have a special type (or type alias) in typing. Am I
missing something?
I agree there should be something like that. This StackOverflow answer (https://stackoverflow.com/a/68027757/59122) talks about something like that: _typeshed.AnyPath. It is used in the standard library, but apparently it doesn't exist at runtime and you need a trick to make it work. I would expect something better to exist, but as far as I can find out there isn't.

PEP 519 has a little section on the topic (https://peps.python.org/pep-0519/#provide-specific-type-hinting-support):

> Provide specific type hinting support
>
> There was some consideration to providing a generic typing.PathLike class which would allow for e.g. typing.PathLike[str] to specify a type hint for a path object which returned a string representation. > While potentially beneficial, the usefulness was deemed too small to bother adding the type hint class.
>
> This also removed any desire to have a class in the typing module which represented the union of all acceptable path-representing types as that can be represented with typing.Union[str, bytes, > os.PathLike] easily enough and the hope is users will slowly gravitate to path objects only.

--

"This planet has - or rather had - a problem, which was this: most of the
people living on it were unhappy for pretty much of the time. Many solutions
were suggested for this problem, but most of these were largely concerned with
the movement of small green pieces of paper, which was odd because on the whole
it wasn't the small green pieces of paper that were unhappy."
        -- Douglas Adams

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to