• Working with paths

    From =?UTF-8?B?UGV0ZXIgU2zDrcW+aWs=?=@21:1/5 to All on Sun Jul 16 15:58:07 2023
    Hello,

    I finally had a look at the pathlib module. (Should have done it long ago,
    but anyway...). Having in mind the replies from my older thread (File
    system path annotations), what is the best way to support all possible path types?

    def doit(path: str | bytes | os.PathLike):
    match path:
    case str() as path:
    print("string")

    case bytes() as path:
    print("bytes")

    case os.PathLike() as path:
    print("os.PathLike")

    Should I branch on the individual types or is there a more elegant way?

    Peter

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Kushal Kumaran@21:1/5 to peter.slizik@gmail.com on Sun Jul 16 10:20:19 2023
    On Sun, Jul 16 2023 at 03:58:07 PM, Peter Slížik <peter.slizik@gmail.com> wrote:
    Hello,

    I finally had a look at the pathlib module. (Should have done it long ago, but anyway...). Having in mind the replies from my older thread (File
    system path annotations), what is the best way to support all possible path types?

    def doit(path: str | bytes | os.PathLike):
    match path:
    case str() as path:
    print("string")

    case bytes() as path:
    print("bytes")

    case os.PathLike() as path:
    print("os.PathLike")

    Should I branch on the individual types or is there a more elegant way?


    Depends on what you need to do with the path. The best way, imo, is to
    simply use pathlib.Path and ignore the existence of other path
    representations. If input is coming from elsewhere, convert it to
    pathlib.Path as early as possible. In the main body of your code, it
    should be able to rely on all paths being Path objects.

    --
    regards,
    kushal

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)