Python Glossary Русский

Python 3.6+osfunction

os.fspath

os — path encoding

Return the path as str/bytes, calling __fspath__ if present (e.g. Path).

Syntax

os.fspath(path)

It implements the path protocol from PEP 519: a function that takes a path calls os.fspath and thus treats str, bytes and pathlib.Path alike. Defining __fspath__ makes your own class usable as a path. A number or None raises TypeError rather than becoming '1' or 'None', so it doubles as an argument check.

Examples

import os
import pathlib
print(os.fspath('a/b'))   # → a/b
print(os.fspath(b'a/b'))   # → b'a/b'
p = pathlib.PurePosixPath('/tmp/data.txt')
print(os.fspath(p))   # → /tmp/data.txt
print(os.path.basename(os.fspath(p)))   # → data.txt
print(os.fspath(5))   # → TypeError: expected str, bytes or os.PathLike object, not int

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy