How platformdirs Works

This page explains the internals that determine the paths you get: how the platform class is chosen, how each class is put together, how a path is assembled from its parts, and what is cached. It is useful when a path surprises you or when you want to subclass a platform class.

Choosing the Platform Class at Import

platformdirs/__init__.py picks the class once, when the package is first imported, and binds it to the name PlatformDirs (and AppDirs). The checks run in this order:

  1. Android app: sys.getandroidapilevel exists, or ANDROID_DATA=/data and ANDROID_ROOT=/system are both set; and neither SHELL nor PREFIX is set; and the app's package folder can be found. → platformdirs.android.Android
  2. sys.platform == "win32" → platformdirs.windows.Windows
  3. sys.platform == "darwin" → platformdirs.macos.MacOS
  4. sys.platform == "ios" → platformdirs.ios.IOS
  5. Everything else, including Linux, the BSDs, Cygwin and WebAssembly → platformdirs.unix.Unix

Because the choice happens at import, setting ANDROID_DATA or SHELL after import platformdirs changes nothing. The Android check is first so that an Android app (whose sys.platform is "android" on official builds, or "linux" on older python-for-android builds) is not treated as plain Linux.

Class Structure

PlatformDirsABC            api.py: constructor, *_path properties, iterators,
 |                                 place_*_file, find_*_file, validation
 +-- Windows               windows.py: Known Folders, author/Cache/Logs layout
 +-- Android               android.py: package folder, shared storage
 +-- IOS                   ios.py: app container
 +-- XDGMixin              _xdg.py: XDG_* variables, runtime directory checks
      +-- Unix             unix.py: XDGMixin + _UnixDefaults (XDG spec defaults,
      |                             user-dirs.dirs, root redirect)
      +-- MacOS            macos.py: XDGMixin + _MacOSDefaults (~/Library, Homebrew)
  • PlatformDirsABC declares the 27 *_dir properties as abstract and implements everything else on top of them. Each *_path property simply wraps its *_dir in pathlib.Path (for site directories, the first entry of the list).
  • For most properties, XDGMixin takes over only when the matching XDG variable is set to an absolute path, and otherwise defers to the platform defaults with super(). That is why Linux and macOS honor the same variables while having different defaults.
  • Unix adds the use_site_for_root redirect on top of the mixin.

Helper modules:

Module Role
_paths.py POSIX path checks and safe directory creation (see Directory Creation and Safety)
_runtime.py Runtime directory checks and the once-per-message RuntimeDirWarning
_android.py Finding the Android package folder (cached)
testing.py, pytest_plugin.py Testing Helpers
__main__.py The command line report

Assembling a Path

Every app directory is built the same way: a base folder, then optional parts.

Platform Pattern
Linux, macOS, iOS, Android <base>/<appname>/<version>
Windows <base>\<appauthor or appname>\<appname>[\Cache]\<version>

Rules applied in every class:

  • If appname is not set (or empty), neither the app name nor the version is appended, so user_data_dir(version="1.0") returns the bare base folder.
  • version is appended only together with appname.
  • On Windows, the author level is added only when appname is set; appauthor=None falls back to the app name and appauthor=False omits the level.
  • Opinion folders (log on Unix and Android, tmp for runtime on Android, Cache and Logs on Windows) are added only when opinion=True. The Windows Cache folder goes before the version; every other opinion folder goes after it.

Paths are joined with os.path.join, so they use the native separator. Windows bases additionally go through os.path.normpath.

Home Directory Resolution

On POSIX platforms, ~ is expanded from HOME. A relative HOME is treated as unset, and the home is then taken from the password database (pwd). If neither yields an absolute path, the property raises:

RuntimeError: could not determine the home directory for '~/.config', set an absolute HOME or XDG variable

On Windows, os.path.expanduser is used (it reads USERPROFILE, else HOMEDRIVE + HOMEPATH), but only user_projects_dir needs it; the other directories come from Known Folders.

Environment Variables Are Read Every Time

Properties are computed on every access. Changing XDG_CONFIG_HOME or WIN_PD_OVERRIDE_LOCAL_APPDATA in os.environ affects the next property read on an existing PlatformDirs object, with no need to recreate it. Only an absolute XDG value counts; a relative value is ignored as if unset, as the XDG specification requires.

What Is Cached

Almost nothing, so paths always reflect the current environment. The exceptions:

Cached Where Lifetime
The platform class platformdirs.PlatformDirs Chosen at import
The Windows folder resolver (ctypes, registry or environment) windows.py Chosen at import; the ctypes function is built once
The Android package folder and media folders from pyjnius _android.py, android.py First successful lookup, for the process
Runtime warnings already shown _runtime.py Each distinct message once per process

Lazy Imports

Each module lists its imports in a __lazy_modules__ variable. On Python versions that support lazy imports for listed modules, they are loaded only when first used, which keeps import platformdirs cheap. On other versions the variable is ignored and the imports run normally. Likewise, the pytest plugin imports platformdirs.testing only when a test requests the fixture.

Subclassing

You can extend a platform class by subclassing the one chosen for the current platform:

import os

from platformdirs import PlatformDirs


class MyDirs(PlatformDirs):
    @property
    def user_cache_dir(self) -> str:
        # Keep caches under the data directory instead.
        return os.path.join(self.user_data_dir, "cache")


dirs = MyDirs("SuperApp")
print(dirs.user_cache_path)        # follows the override
print(dirs.find_cache_file("x"))   # searches the overridden directory

Because *_path, the iterators and place_*/find_* are built on the *_dir properties (and iter_*_paths), overriding a property changes them too. Note that isolated_dirs patches only platformdirs.PlatformDirs itself, so properties defined on your subclass take precedence over the isolation.

See Also