Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 299
Dobedani Avatar asked Dec 22 '25 01:12

Dobedani


1 Answers

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
like image 156
playing4time Avatar answered Dec 24 '25 21:12

playing4time



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!