Sub topic 12
Using Path with APIs that expect strings
This chapter assumes you can create Path objects, join them with /, and read and write files with Path methods, as covered in earlier chapters. It also assumes you know basic exception handling and type hints.
Most real programs mix pathlib with code that predates it. You will pass paths to the standard library, to third-party packages, to subprocesses, and to JSON files. This chapter covers which of those accept a Path directly, which need a conversion, and how to design your own functions so they accept either form.
The os.PathLike protocol
Since Python 3.6, the standard library has a convention called the path-like protocol. An object is path-like if it has a __fspath__() method that returns a str or bytes file system path. The abstract class os.PathLike describes this protocol.
pathlib.PurePath, and therefore Path, implements __fspath__(). A Path is not a subclass of str. It is an object that can hand out a string when asked. Functions that follow the convention call os.fspath() on their argument internally.
import os
from pathlib import Path
p = Path("data") / "report.csv"
print(str(p)) # data/report.csv
print(os.fspath(p)) # data/report.csv
print(type(os.fspath(p))) # <class 'str'>
print(os.fspath("already/a/string")) # already/a/string
try:
os.fspath(42)
except TypeError as exc:
print(exc) # expected str, bytes or os.PathLike object, not intos.fspath() returns strings and bytes unchanged. It calls __fspath__() on path-like objects and raises TypeError for anything else. That makes it stricter than str(), which converts any object to text. For example, str(42) gives "42", which is not a path anyone meant. Use os.fspath() when you want to reject non-paths. Use str() when you only need display text, such as in log messages.
What accepts a Path directly
Most of the standard library has accepted path-like arguments for years. You can pass a Path straight to these:
open()andio.open()- the
osfunctions, such asos.listdir,os.stat,os.remove, andos.walk - the
os.pathfunctions, such asos.path.join,os.path.exists, andos.path.getsize - the
shutilfunctions, such asshutil.copyandshutil.rmtree subprocessarguments, including items in the argument listsqlite3.connect(),zipfile.ZipFile(), andtarfile.open()
import os
import shutil
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)
src = base / "a.txt"
src.write_text("hi\n", encoding="utf-8")
with open(src, encoding="utf-8") as f:
print(f.read().strip()) # hi
print(os.path.getsize(src)) # 3
print(os.path.exists(src)) # True
shutil.copy(src, base / "copy.txt")
print(sorted(os.listdir(base))) # ['a.txt', 'copy.txt']Passing a Path to an older function does not make the function return a Path. The return type depends on the function. The next section covers this.
Return types are often plain strings
When you hand a Path to a function in os or os.path, you typically get strings back. The function converts the argument to a string at the start and works on strings from then on.
| Call | Accepts `Path` | Returns |
|---|---|---|
| `open(p)` | Yes | A file object |
| `os.listdir(p)` | Yes | A list of `str` names |
| `os.walk(p)` | Yes | Tuples of `str` |
| `os.path.join(p, "x")` | Yes | A `str` |
| `os.path.basename(p)` | Yes | A `str` |
| `shutil.copy(a, b)` | Yes | The destination, as a `str` or as the object you passed |
| `Path.iterdir()` | Not applicable | `Path` objects |
| `p.startswith("data")` | No, `Path` has no such method | `AttributeError` |
| `json.dumps({"p": p})` | No | `TypeError` |
If you need a Path again, wrap the result: Path(os.path.join(p, "x")). In new code, prefer the Path equivalent, such as p / "x", so the value stays a Path.
import os
from pathlib import Path
base = Path("project")
joined = os.path.join(base, "src")
print(type(joined).__name__) # str
print(type(Path(joined)).__name__) # PosixPath on POSIX systemsWhat does not work
A Path is not a string, so string operations fail. Three failures come up most often.
from pathlib import Path
p = Path("data") / "report.csv"
try:
print("backup/" + p)
except TypeError:
print("TypeError: cannot concatenate str and Path")
try:
p.startswith("data")
except AttributeError:
print("AttributeError: Path has no startswith")
print(Path("a") == "a") # FalseThe third line of output is the subtle one. A Path never compares equal to a string, even when str(path) matches. That affects dictionary keys, in tests on lists, and set operations. A dictionary keyed by strings will miss when you look up a Path, and no error is raised.
Fix these by converting at one clear point:
- Build paths with
/instead of+:Path("backup") / p.name. - Use
Pathattributes instead of string methods. Forstartswith, usep.parts[0] == "data"orp.is_relative_to("data"), which exists from Python 3.9. - Pick one type for keys and comparisons, and convert once, such as
Path(key)orstr(path).
Sorting has the same problem. sorted() on a list that mixes str and Path raises TypeError, because the two types do not support < against each other.
Converting for JSON and other serializers
json.dumps does not know Path. It raises TypeError: Object of type PosixPath is not JSON serializable. The standard fix is a default function that converts paths and rejects everything else.
import json
import os
from pathlib import Path
def encode(obj):
if isinstance(obj, os.PurePath):
return obj.as_posix()
raise TypeError(f"Cannot serialize {type(obj).__name__}")
config = {"input": Path("data") / "in.csv", "retries": 3}
print(json.dumps(config, default=encode))
# {"input": "data/in.csv", "retries": 3}This uses as_posix() instead of str(). On Windows, str() produces backslashes, which JSON then escapes as \\. With as_posix(), the file looks the same on every system, and Windows accepts forward slashes when you read it back. Use as_posix() for anything you store or send between machines. Use str() or os.fspath() for calls into the local operating system.
Bytes paths
os.fspath() can return bytes when a path-like object's __fspath__() returns bytes. Path itself works only with text: Path(b"data") raises TypeError. If you receive a bytes path, decode it with os.fsdecode() first. To go the other way, os.fsencode(p) gives bytes, using the file system encoding of the running system.
import os
from pathlib import Path
raw = b"data/report.csv"
p = Path(os.fsdecode(raw))
print(p) # data/report.csv
print(os.fsencode(p)) # b'data/report.csv'Making your own classes path-like
Any class can join the protocol by defining __fspath__(). Once it does, open(), os.path, and Path() all accept it.
import os
from pathlib import Path
class Artifact:
def __init__(self, run_id: int, name: str) -> None:
self.run_id = run_id
self.name = name
def __fspath__(self) -> str:
return f"/tmp/runs/{self.run_id}/{self.name}"
a = Artifact(7, "out.txt")
print(os.fspath(a)) # /tmp/runs/7/out.txt
print(Path(a).parent) # /tmp/runs/7
print(os.path.basename(a)) # out.txt
print(isinstance(a, os.PathLike)) # Trueisinstance(x, os.PathLike) works without inheriting from the class. os.PathLike checks for the presence of __fspath__ on the type. This also means a plain str is not an instance of os.PathLike, so a check for "something path-like" must also allow str explicitly.
Designing functions that accept both
For your own functions, accept str | os.PathLike[str] in the signature and convert to Path on the first line. Callers can then pass whatever they have, and the body works with one type only.
from __future__ import annotations
import os
import tempfile
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)
with tempfile.TemporaryDirectory() as tmp:
target = Path(tmp) / "log.txt"
target.write_text("a\nb\nc\n", encoding="utf-8")
print(count_lines(target)) # 3
print(count_lines(str(target))) # 3Path(path) costs little when path is already a Path, and it normalizes the value in either case. The from __future__ import annotations line lets the | syntax work in annotations on Python 3.7 and later. On Python 3.9 and later, os.PathLike[str] is also valid at runtime.
When you call a function that needs a plain string, convert at the call site, not earlier. Keep Path objects inside your code and produce a string only at the boundary:
import os
from pathlib import Path
def call_legacy_tool(path: Path) -> None:
legacy_api(os.fspath(path)) # one conversion, right where it is needed
def legacy_api(filename: str) -> None:
print("opening", filename)
call_legacy_tool(Path("data") / "in.csv") # opening data/in.csvNormalization when converting
Creating a Path can change how a path looks. Path("a//b/./c") becomes a/b/c, and Path("./x") becomes x. A trailing slash is dropped. Path("") becomes .. If a legacy system compares path strings literally, the converted string may not match the original text. Compare with Path objects on both sides, or normalize both sides with the same method.
Exercise
A function receives settings = {"log_dir": Path("logs")} and writes it with json.dumps(settings). It fails with a TypeError. Write the one-line fix that produces portable output, and explain why as_posix() is a better choice than str() here.
Show answer
Use json.dumps(settings, default=lambda o: o.as_posix() if isinstance(o, os.PurePath) else (_ for _ in ()).throw(TypeError(type(o).__name__))), or the clearer form with a named function: def encode(o): if isinstance(o, os.PurePath): return o.as_posix(); raise TypeError(...) then json.dumps(settings, default=encode). as_posix() always uses forward slashes, so the file is identical on Windows and POSIX systems. str() would write backslashes on Windows, which JSON escapes as \\ and which other systems would read as part of a file name.
Exercise
lookup = {"data/a.txt": 1} and key = Path("data") / "a.txt". Does key in lookup return True? How do you fix it?
Show answer
It returns False. A Path never equals a str, and the two hash differently, so the dictionary lookup misses without raising an error. Convert at the boundary: either os.fspath(key) in lookup, or better, build the dictionary with Path keys, for example {Path("data/a.txt"): 1}, so both sides use the same type.
Exercise
Write a function file_size(path) that accepts either a str or any path-like object and returns the size in bytes. Which type hint should the parameter have, and what should the first line of the body do?
Show answer
Use path: str | os.PathLike[str], with from __future__ import annotations for older Python versions. The first line is p = Path(path), and then return p.stat().st_size. Converting once at the top means the rest of the function works with a single type.