Sub topic 12
Using Path with APIs that expect strings
This chapter assumes you can build and inspect Path objects (the / operator, name, suffix, parent) and have used open() or the os module before. It covers passing Path objects to code written for plain strings, and the cases where that fails.
Why this comes up
Much of Python predates pathlib. Older functions, third-party libraries, and serializers often expect a str. A Path is not a str, so you need to know when it is accepted as it is and when you must convert it.
The os.PathLike protocol
Python defines a protocol called os.PathLike. An object follows it if it has a __fspath__() method that returns a str or bytes path. Path follows this protocol. Since Python 3.6, most of the standard library accepts any such object wherever it accepts a path. This includes open(), the os functions, shutil, and os.path.
import os
import shutil
from pathlib import Path
src = Path("example.txt")
src.write_text("hi\n", encoding="utf-8")
with open(src, encoding="utf-8") as f: # open() accepts Path
print(f.read().strip()) # hi
print(os.path.getsize(src)) # 3
print(os.path.basename(src)) # example.txt (a str)
shutil.copy(src, Path("copy.txt"))Functions in os.path accept a Path but return plain strings. A Path in does not mean a Path out.
Converting explicitly: str() and os.fspath()
Some code needs a real string. You have two ways to get one:
str(p)always works for aPath. It uses the separator of the current operating system.os.fspath(p)calls__fspath__(). It returns astrorbytesas the object defines. If you pass it astr, it returns that string unchanged. If you pass it something that is not path-like, it raisesTypeError.
Prefer os.fspath() in code that accepts both strings and path objects. It rejects values such as integers, where str() would turn them into a meaningless path.
import json
import os
from pathlib import Path
p = Path("data") / "config.json"
print(os.fspath(p)) # data/config.json
print(os.fspath("a/b")) # a/b
try:
json.dumps({"path": p})
except TypeError as err:
print(err) # Object of type PosixPath is not JSON serializable
print(json.dumps({"path": str(p)})) # {"path": "data/config.json"}Accepting both types in your own functions
Annotate parameters as str | os.PathLike[str] and pass the value straight to the standard library. Wrap it in Path() only when you need Path methods. Path() accepts strings and path-like objects.
import os
from pathlib import Path
def count_lines(path: str | os.PathLike[str]) -> int:
p = Path(path)
with p.open(encoding="utf-8") as f:
return sum(1 for _ in f)
Path("lines.txt").write_text("a\nb\nc\n", encoding="utf-8")
print(count_lines("lines.txt")) # 3
print(count_lines(Path("lines.txt"))) # 3You can also make your own classes path-like:
import os
from pathlib import Path
class Dataset:
def __init__(self, root):
self.root = root
def __fspath__(self):
return os.fspath(self.root)
print(Path(Dataset("data"))) # dataWhen conversion is needed
Convert in these cases:
- A serializer such as
jsonor a database driver raisesTypeError. - A third-party library checks
isinstance(x, str). - You need string operations, such as
+concatenation.Path("a") + "b"raisesTypeError.
Exercise
A colleague's function runs json.dumps({"file": Path("logs") / "app.log"}) and fails with a TypeError. Give two ways to fix it, and say which is better if the JSON is read on both Windows and Linux.
Show answer
Convert the path before serializing, with str(path) or os.fspath(path). Use path.as_posix() for data shared across systems, because it always produces forward slashes, while str() produces backslashes on Windows.