platformdirs

repository·main·Indexed 19 days ago

https://github.com/tox-dev/platformdirs

A Python package for determining platform-specific standard directory locations for applications on macOS, Windows, Linux/Unix, and Android. It provides the PlatformDirs class and convenience functions to retrieve paths for application-specific data, configuration, cache, logs, and state, as well as standard user media directories like documents, downloads, and pictures. The library supports both user-specific writable directories and system-wide read-only site directories.

Tokens
17.9K
Snippets
50
Records
77
Agent score
71%

What's inside platformdirs

  1. What is platformdirs

    main
    platformdirs is a Python library used to determine platform-specific system directories. It allows developers to resolve the correct locations for user data, configuration, cache, or log directories across different operating systems, including macOS, Windows, Linux/Unix, and Android. It ensures your application follows platform conventions such as the XDG Base Directory Spec on Linux, ~/Library on macOS, and AppData on Windows.
  2. Configure Windows directory structure with appauthor

    main

    On Windows, platformdirs defaults to a two-level structure: AppData\Local\<appauthor>\<appname>. If appauthor is None, it defaults to the app name, resulting in a doubled path: AppData\Local\MyApp\MyApp.

    You can control this behavior using the appauthor parameter:

    • Explicit author: user_data_dir("MyApp", "AcmeCompany") $\rightarrow$ AppData\Local\AcmeCompany\MyApp.
    • Flat structure: user_data_dir("MyApp", appauthor=False) $\rightarrow$ AppData\Local\MyApp.
    • Default: user_data_dir("MyApp") $\rightarrow$ AppData\Local\MyApp\MyApp.

    Note: appauthor is ignored on non-Windows platforms.

    from platformdirs import user_data_dir
    
    # Explicit author -- AppData\Local\AcmeCompany\MyApp
    user_data_dir("MyApp", "AcmeCompany")
    
    # No author -- AppData\Local\MyApp (flat structure)
    user_data_dir("MyApp", appauthor=False)
    
    # Default (appauthor=None) -- AppData\Local\MyApp\MyApp
    user_data_dir("MyApp")
  3. Use user preference directories

    main

    Use user_preference_dir() when you need to follow Apple's conventions for storing preference files (historically .plist) in ~/Library/Preferences.

    Note on cross-platform behavior:

    • macOS: Distinguishes between user_data_dir (~/Library/Application Support/AppName) and user_preference_dir (~/Library/Preferences/AppName).
    • Linux, Windows, and Android: user_preference_dir is an alias for user_config_dir. For most cross-platform applications, user_config_dir is sufficient.
  4. Understand platform-specific user data and configuration directories

    main

    The platformdirs library auto-detects the current platform (Linux, macOS, Windows, or Android) to return standard directory paths. For most user-specific directories, the library appends the appname and/or appauthor to the base path.

    Common user-specific directory types include:

    • user_data_dir: For application data.
    • user_config_dir: For configuration files.
    • user_cache_dir: For temporary/cache files.
    • user_state_dir: For persistent state.
    • user_log_dir: For application logs.
    • user_runtime_dir: For runtime/temporary files.
    • user_preference_dir: For user preferences (Note: On macOS, this is distinct from user_config_dir).
  5. Understand application vs. user media directory types

    main

    The library distinguishes between two main categories of directories:

    Application Directories

    These are scoped to your specific application name and version. They include both user_* (per-user, writable) and site_* (system-wide, read-only) variants where applicable.

    • Data: Persistent data (user_data_dir, site_data_dir)
    • Config: Configuration files (user_config_dir, site_config_dir)
    • Preference: User preferences, distinct from config on macOS (user_preference_dir)
    • Cache: Regeneratable cached data (user_cache_dir, site_cache_dir)
    • State: Non-essential runtime state like window positions (user_state_dir, site_state_dir)
    • Logs: Log files (user_log_dir, site_log_dir)
    • Runtime: Runtime files like sockets and PIDs (user_runtime_dir, site_runtime_dir)

    User Media Directories

    These are standard user-facing folders that are NOT scoped to your application name.

    • Standard Folders: user_documents_dir, user_downloads_dir, user_pictures_dir, user_videos_dir, user_music_dir, user_desktop_dir, user_projects_dir
    • Specialty Folders: user_publicshare_dir, user_templates_dir, user_fonts_dir (writable font installation), user_bin_dir/site_bin_dir (executables), user_applications_dir/site_applications_dir
  6. Configure macOS directory behavior

    main

    On macOS, platformdirs defaults to ~/Library directories.

    • Data vs Config: Both user_data_dir and user_config_dir resolve to ~/Library/Application Support/AppName. To separate them, use subdirectories within that path.
    • XDG Overrides: If XDG_DATA_HOME, XDG_CONFIG_HOME, or XDG_CACHE_HOME environment variables are set, they take precedence over macOS defaults.
    • Homebrew: When Homebrew is installed, site_data_dir and site_cache_dir include the Homebrew prefix if multipath=True is passed.
  7. Configure Windows directory behavior

    main

    Windows directory resolution uses Shell Folder APIs. Key configuration options include:

    • appauthor: By default, platformdirs adds a parent directory for the author (e.g., AppData\Local\<Author>\<App>). To avoid this and get AppData\Local\<App>, pass appauthor=False.
    • roaming: Set roaming=True to switch from AppData\Local to AppData\Roaming (useful for preferences that should sync across a domain).
    • Environment Overrides: Use WIN_PD_OVERRIDE_* environment variables to redirect paths (e.g., for large ML models) without changing system-wide APPDATA variables.

    Handling Windows Store Python (MSIX) Sandboxing If running in a sandboxed environment, platformdirs returns the logical path. To share files with external processes, you must resolve the real on-disk path using os.path.realpath after creation.

    import os
    import platformdirs
    
    data_dir = platformdirs.user_data_dir(
        appname="MyApp", appauthor="Acme", ensure_exists=True
    )
    # Resolve the real path for external processes
    real_dir = os.path.realpath(data_dir)
  8. Configure Android directory behavior

    main

    On Android, platformdirs uses the app's private storage directories (e.g., /data/data/com.example.app).

    • Media Directories: Point to shared external storage under /storage/emulated/0/. Accessing these requires appropriate Android permissions.
    • Shell Environments: In environments like Termux or Pydroid (detected via the SHELL environment variable), platformdirs uses the Unix/XDG backend instead.
  9. Override directories using XDG environment variables

    main

    On Linux and macOS, platformdirs respects the XDG Base Directory Specification. Setting the following environment variables will override the default directory locations:

    • XDG_DATA_HOME: user data directory.
    • XDG_CONFIG_HOME: user config directory.
    • XDG_CACHE_HOME: user cache directory.
    • XDG_STATE_HOME: user state directory.
    • XDG_DATA_DIRS: system data directories (colon-separated).
    • XDG_CONFIG_DIRS: system config directories (colon-separated).
    • XDG_RUNTIME_DIR: user runtime directory.

    On Windows, you can use WIN_PD_OVERRIDE_* environment variables to override default paths.

    import os
    from platformdirs import user_config_dir
    
    # Override config directory via environment variable
    os.environ["XDG_CONFIG_HOME"] = "/Users/trentm/.config"
    print(user_config_dir("SuperApp"))  # '/Users/trentm/.config/SuperApp'
  10. How to choose the right directory type

    main

    Choosing a directory depends on two questions: Who owns the data? and Is the data essential?

    1. Ownership

    • App-internal data: Databases, caches, config files, and logs. These should be scoped to your app name using user_data_dir, user_config_dir, etc.
    • User-facing data: Files the user expects to browse directly (e.g., documents, music, photos). Use media directories like user_documents_dir or user_pictures_dir which are not scoped to your app name.

    2. Essentiality (for App-internal data)

    • Can it be deleted without loss?
      • Yes, and it speeds things up: Use cache (e.g., API responses, thumbnails).
      • Yes, but it's temporary for this session: Use runtime (e.g., sockets, PIDs).
      • No, but it's non-critical: Use state (e.g., window positions, recent files).
    • No, it is critical:
      • Settings/Options: Use config (or preference on macOS).
      • Log files: Use log.
      • Everything else: Use data (e.g., SQLite databases, user-created content).
  11. Distinguish between User and Site directories

    main

    Directories in platformdirs are categorized into User and Site variants.

    User directories (user_*_dir, user_*_path)

    • Per-user: Isolated for each user on the system.
    • Writable: Accessible by normal users without special permissions.
    • Default choice: Use these for standard application data.

    Site directories (site_*_dir, site_*_path)

    • System-wide: Shared across all users on the machine.
    • Read-only for users: Typically requires administrator/root privileges to write.
    • System defaults: Used for shared resources or by system package managers.

    Pattern: Hierarchical Configuration A common pattern is to check for a site-wide default configuration first, then allow a user-specific configuration to override it.

    from platformdirs import site_config_path, user_config_path
    
    # Check site config first (system defaults), then user config (overrides)
    site_cfg = site_config_path("MyApp") / "defaults.json"
    user_cfg = user_config_path("MyApp") / "config.json"
    
    if user_cfg.exists():
        config = user_cfg
    elif site_cfg.exists():
        config = site_cfg
    else:
        config = None
  12. Key features of platformdirs

    main

    The library provides several key capabilities for managing system paths:

    • Platform auto-detection: Works on macOS, Windows, Linux, FreeBSD, OpenBSD, and Android without manual configuration.
    • Convention compliance: Automatically follows platform standards (XDG, macOS Library, Windows AppData).
    • XDG variable support: Honors environment variables like XDG_DATA_HOME and XDG_CONFIG_HOME on Linux and macOS.
    • Flexible return types: Every directory lookup provides both a _dir (returning a str) and a _path (returning a pathlib.Path) variant.
    • Auto-creation: You can set ensure_exists=True to automatically create the directory on its first access.
    • Version isolation: Use the version parameter to maintain separate directories for different versions of your application.