XDG

XDG Base Directory Specification helpers.

Each helper reads one XDG_* environment variable and falls back to the spec’s default when the variable is unset or empty. The single-path helpers also fall back when the variable holds a relative path. The *_DIRS helpers split the variable on colons and drop relative entries. xdg_runtime_dir has no default and returns None.

See the XDG Base Directory Specification for more information.

Helpers

We’ll start by defining a context manager that temporarily sets an environment variable to demonstrate the behaviour of each helper function:

from contextlib import contextmanager
@contextmanager
def env(variable, value):
    old = os.environ.get(variable, None)
    try:
        os.environ[variable] = value
        yield
    finally:
        if old is None: del os.environ[variable]
        else: os.environ[variable] = old

source

xdg_cache_home

def xdg_cache_home():

Path corresponding to XDG_CACHE_HOME

from fastcore.test import *
test_eq(xdg_cache_home(), Path.home()/'.cache')
with env('XDG_CACHE_HOME', '/home/fastai/.cache'):
    test_eq(xdg_cache_home(), Path('/home/fastai/.cache'))

source

xdg_config_dirs

def xdg_config_dirs():

Paths corresponding to XDG_CONFIG_DIRS

test_eq(xdg_config_dirs(), [Path('/etc/xdg')])
with env('XDG_CONFIG_DIRS', '/home/fastai/.xdg:/home/fastai/.config'):
    test_eq(xdg_config_dirs(), [Path('/home/fastai/.xdg'), Path('/home/fastai/.config')])

source

xdg_config_home

def xdg_config_home():

Path corresponding to XDG_CONFIG_HOME

test_eq(xdg_config_home(), Path.home()/'.config')
with env('XDG_CONFIG_HOME', '/home/fastai/.config'):
    test_eq(xdg_config_home(), Path('/home/fastai/.config'))

source

xdg_data_dirs

def xdg_data_dirs():

Paths corresponding to XDG_DATA_DIRS`


source

xdg_data_home

def xdg_data_home():

Path corresponding to XDG_DATA_HOME

test_eq(xdg_data_home(), Path.home()/'.local/share')
with env('XDG_DATA_HOME', '/home/fastai/.data'):
    test_eq(xdg_data_home(), Path('/home/fastai/.data'))

source

xdg_runtime_dir

def xdg_runtime_dir():

Path corresponding to XDG_RUNTIME_DIR


source

xdg_state_home

def xdg_state_home():

Path corresponding to XDG_STATE_HOME

test_eq(xdg_state_home(), Path.home()/'.local/state')
with env('XDG_STATE_HOME', '/home/fastai/.state'):
    test_eq(xdg_state_home(), Path('/home/fastai/.state'))

Copyright © 2016-2021 Scott Stevenson

Modifications copyright © 2022 onwards Jeremy Howard