Debian Codegraph @

docs/dev/paths.rst

raw
1 Handling Paths
2 ==============
3
4 ``pathlib`` provides a clean, cross-platform API for working with filesystem
5 paths.
6
7 Use the ``.filepath`` property on ``Item`` and ``Album`` library objects to
8 access paths as ``pathlib.Path`` objects. This produces a readable, native
9 representation suitable for printing, logging, or further processing.
10
11 Normalize paths using ``Path(...).expanduser().resolve()``, which expands ``~``
12 and resolves symlinks.
13
14 Cross-platform differences—such as path separators, Unicode handling, and
15 long-path support (Windows) are automatically managed by ``pathlib``.
16
17 When storing paths in the database, however, convert them to bytes with
18 ``bytestring_path()``. Paths in Beets are currently stored as bytes, although
19 there are plans to eventually store ``pathlib.Path`` objects directly. To access
20 media file paths from library objects, use ``.path`` for the absolute path as
21 ``bytes`` or ``.filepath`` for the absolute path as a ``pathlib.Path``. The
22 database still stores these paths relative to the configured library root.
23
24 Legacy utilities
25 ----------------
26
27 Historically, Beets used custom utilities to ensure consistent behavior across
28 Linux, macOS, and Windows before ``pathlib`` became reliable:
29
30 - ``syspath()``: worked around Windows Unicode and long-path limitations by
31 converting to a system-safe string (adding the ``\\?\`` prefix where needed).
32 - ``normpath()``: normalized slashes and removed ``./`` or ``..`` parts but did
33 not expand ``~``.
34 - ``bytestring_path()``: converted paths to bytes for database storage (still
35 used for that purpose today).
36 - ``displayable_path()``: converted byte paths to Unicode for display or
37 logging.
38
39 These functions remain safe to use in legacy code, but new code should rely
40 solely on ``pathlib.Path``.
41
42 Examples
43 --------
44
45 Old style
46
47 .. code-block:: python
48
49 displayable_path(item.path)
50 normpath("~/Music/../Artist")
51 syspath(path)
52
53 New style
54
55 .. code-block:: python
56
57 item.filepath
58 Path("~/Music/../Artist").expanduser().resolve()
59 Path(path)
60
61 When storing paths in the database
62
63 .. code-block:: python
64
65 path_bytes = bytestring_path(Path("/some/path/to/file.mp3"))