config2py#

Tools to read and write configurations from various sources and formats

Functions

extract_exports(exports, *[, on_missing])

Get a dict of {name: value} pairs from the name="value" pairs of unix export lines (that is, lines of the ``export NAME="VALUE" format

get_configs_local_store([config_src, ...])

Get the local store of configs.

simple_config_getter([configs_src, ...])

Make a simple config getter from a "central" config source specification.

config_getter([key, sources, default, ...])

Get a config value from a list of sources

get_config([key, sources, default, egress, ...])

Get a config value from a list of sources

user_gettable([save_to, prompt_template, ...])

Create a GettableContainer that asks the user for a value, optionally saving it.

sources_chainmap(sources[, val_is_valid, ...])

Create a ChainMap from a list of sources

ask_user_for_input(prompt[, default, ...])

Ask the user for input, optionally masking, validating and transforming the input.

get_app_config_folder([app_name, ...])

Retrieve or create the app directory specific to the given app name and folder kind.

get_app_data_folder([app_name, ...])

Retrieve or create the app directory specific to the given app name and folder kind.

get_app_folder([app_name, setup_callback, ...])

Retrieve or create the app directory specific to the given app name and folder kind.

get_configs_folder_for_app([app_name, ...])

Retrieve or create the configs directory specific to the given app name.

is_repl()

Determines if the Python interpreter is running in REPL.

parse_assignments_from_py_source(source_code, *)

Parse assignments from python source code.

process_path(*path[, ensure_dir_exists, ...])

Process a path string, ensuring it exists, and optionally expanding user.

ensure_seeded(target, package_name, ...[, ...])

Copy a bundled seed file to target if it does not already exist.

has_secret(text, *[, rules, word_start, ...])

Whether text looks like it holds a credential.

register_extension(ext, loader, dumper)

Register loader/dumper for a file extension.

Classes

ConfigStore([defaults, dict_type, ...])

Persister (read, write, delete) for ini configs.

ConfigReader([defaults, dict_type, ...])

A KvReader to read config files

Configs

AppData(app_name, *[, package_name, ...])

Per-user data directory facade for a Python application.

SecretRule(rule, pattern[, literals, ...])

A secret's shape: rule names it, pattern is its expression.

SyncStore(loader, dumper)

A MutableMapping that automatically syncs changes to backing storage.

FileStore(filepath, *[, key_path, loader, ...])

A SyncStore backed by a file with automatic format detection.

JsonStore(filepath, *[, key_path, indent, ...])

A FileStore specialized for JSON files.

Exceptions

Config2PyError

Base class for config2py errors.

Config2PyWarning

Warnings issued by config2py (e.g. permissions it could not tighten).

ConfigNotFound

Raised when a config file is not found.

InsecureConfigFolderWarning

A folder used to store config values (which may be secrets) is owned by another user or writable by others, who could plant a symlink or file there to redirect or read those values (see i2mint/config2py#45).

MissingConfigFileWarning

A path given as a config source is not an existing, readable file (it is missing, a folder, or unreadable), so it was read as empty (see i2mint/config2py#27 and /43).

class config2py.AppData(app_name, *, package_name=None, seed_data_dir='_seed_data')[source]#

Bases: object

Per-user data directory facade for a Python application.

Binds an application name (and optional Python package name) once and provides convenient access to:

  • resources — editable reference data seeded from the package on first access (~/.local/share/<app>/resources/).

  • config — user preference files, also seeded on first access (~/.config/<app>/).

  • artifact directories — runtime-generated data organised by kind (~/.local/share/<app>/artifacts/<kind>/).

Seed files are read via importlib.resources from <package_name>._seed_data.{resources,config}/.

Parameters:
  • app_name (str) – The application name used for the directory under the XDG root (e.g. "my_app" → ~/.local/share/my_app).

  • package_name (Optional[str]) – The top-level Python package that contains the _seed_data directory. Defaults to app_name.

  • seed_data_dir (str) – Name of the seed-data sub-package inside the Python package (default "_seed_data").

Example

>>> app = AppData("myapp", package_name="myapp")
>>> app.app_folder()
PosixPath('/Users/.../.local/share/myapp')
app_folder(*, folder_kind='data')[source]#

Return the app directory for folder_kind, creating it if needed.

Return type:

Path

get_artifact_dir(kind)[source]#

Return (and create) an artifact sub-directory for kind.

Return type:

Path

get_config(name)[source]#

Return a config file path, seeding from package data if missing.

Return type:

Path

get_resource(name)[source]#

Return a user resource path, seeding from package data if missing.

Return type:

Path

exception config2py.Config2PyError[source]#

Bases: Exception

Base class for config2py errors.

exception config2py.Config2PyWarning[source]#

Bases: UserWarning

Warnings issued by config2py (e.g. permissions it could not tighten).

exception config2py.ConfigNotFound[source]#

Bases: Config2PyError

Raised when a config file is not found.

class config2py.ConfigReader(defaults=None, dict_type=<class 'dict'>, allow_no_value=False, *, delimiters=('=', ': '), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section='DEFAULT', interpolation=<object object>, converters=<object object>)[source]#

Bases: ConfigStore

A KvReader to read config files

>>> from config2py.s_configparser import ConfigReader
>>>
>>> # from a (pretend) file
>>> from io import BytesIO, StringIO
>>> file_content_bytes = b'''
... [Paths]
... home_dir: /Users
... my_dir: %(home_dir)s/lumberjack
... my_pictures: %(my_dir)s/Pictures
...
... [Escape]
... gain: 80%%  # use a %% to escape the % sign (% is the only character that needs to be escaped)'''
>>> c = ConfigReader(file_content_bytes)  # get configs from the bytes
>>> list(c)
['DEFAULT', 'Paths', 'Escape']
>>> ######## From a (pretend) file (pointer) ########
>>> # Usually, you write your configs in a file and give ConfigReader the filepath, or open file pointer...
>>> pretend_file_pointer = StringIO(file_content_bytes.decode())
>>> c = ConfigReader(pretend_file_pointer)
>>> list(c)
['DEFAULT', 'Paths', 'Escape']
>>> c['Paths']  # gives you a configparser.Section object
<Section: Paths>
>>> # A configparser.Section is a mapping. Let's see the keys
>>> list(c['Paths'])
['home_dir', 'my_dir', 'my_pictures']

# >>> # here’s a quick way to see both keys and values. Note how the home_dir interpolation was performed! # >>> dict(c[‘Paths’]) # {‘home_dir’: ‘/Users’, ‘my_dir’: ‘/Users/lumberjack’, ‘my_pictures’: ‘/Users/lumberjack/Pictures’}

>>>
>>> ######## Get configs from a dict ########
>>> config_dict = {'section1': {'key1': 'value1'},
...                'section2': {'keyA': 'valueA', 'keyB': 'valueB'},
...                'section3': {'foo': 'x', 'bar': 'y','baz': 'z'}}
>>> c = ConfigReader(config_dict)
>>>
>>> assert list(c) == ['DEFAULT', 'section1', 'section2', 'section3']
>>> assert list(c['section3']) == ['foo', 'bar', 'baz']
>>>
>>> ######## Get configs from a string ########
>>> from config2py.s_configparser import _test_config_str
>>> c = ConfigReader(_test_config_str, allow_no_value=True)
>>> list(c)
['DEFAULT', 'Simple Values', 'All Values Are Strings', 'Multiline Values', 'No Values', 'You can use comments', 'Sections Can Be Indented']
>>> list(c['Simple Values'])
['key', 'spaces in keys', 'spaces in values', 'spaces around the delimiter', 'you can also use']

######## A filepath that doesn’t exist ########

A filepath (a single-line str, an os.PathLike, or several of them in a list or tuple) that is not an existing file reads as empty, as configparser does. So does one that is a folder or can’t be read (permission denied). on_missing says what else happens: "warn" (the default) issues a MissingConfigFileWarning, "raise" raises FileNotFoundError (or IsADirectoryError / PermissionError), and "ignore" does nothing (see i2mint/config2py#27 and /43).

>>> c = ConfigReader('no/such/file.ini', on_missing='ignore')
>>> list(c)
['DEFAULT']
>>> ConfigReader('no/such/file.ini', on_missing='raise')
Traceback (most recent call last):
  ...
FileNotFoundError: [Errno 2] No such config file: 'no/such/file.ini'
persist()[source]#

Disabled: ConfigReader is read-only.

Return type:

NoReturn

class config2py.ConfigStore(defaults=None, dict_type=<class 'dict'>, allow_no_value=False, *, delimiters=('=', ': '), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section='DEFAULT', interpolation=<object object>, converters=<object object>)[source]#

Bases: Store

Persister (read, write, delete) for ini configs.

You can read ini formated configurations with ConfigStore (though if you want to just read, you should use ConfigReader instead – since ConfigReader disables write and delete operations.

See ConfigReader for more examples of how to use ConfigStore. We’ll mainly focus on write and delete operations here.

>>> import os
>>> from config2py.s_configparser import ConfigStore, ConfigReader
>>> import tempfile
>>> temp_dir_path = tempfile.TemporaryDirectory().name
>>> if not os.path.exists(temp_dir_path):
...     os.makedirs(temp_dir_path)
>>> ini_filepath = os.path.join(temp_dir_path, 'config_store_test.ini')
>>> if os.path.isfile(ini_filepath):
...     os.remove(ini_filepath)
>>>
>>> os.path.isfile(ini_filepath)  # File doesn't exist
False
>>>
>>> s = ConfigStore(ini_filepath)
>>> list(s)  # There's always a default (by default empty)
['DEFAULT']
>>>
>>> os.path.isfile(ini_filepath)  # But the file still doesn't exist (the DEFAULT is virtual)
False
>>>
>>> # Now let's make a config
>>> s['nothing'] = {'special': 'about', 'number': 42}
>>> list(s)
['DEFAULT', 'nothing']
>>>
>>> os.path.isfile(ini_filepath)  # But NOW the file exists (ConfigStore will automatically write to file)
True
>>> s['add'] = {'more': 'sections'}
>>> list(s)
['DEFAULT', 'nothing', 'add']
>>> # and yes, that config can now be read
>>> config_reader = ConfigReader(ini_filepath)
>>> list(config_reader)
['DEFAULT', 'nothing', 'add']
>>>
>>> config_reader['nothing']
<Section: nothing>
>>>
>>> dict(config_reader['nothing'])  # note that 42 is now a string (that's the ini format for you!)
{'special': 'about', 'number': '42'}
>>> dict(config_reader['DEFAULT'])  # and DEFAULT is empty
{}

You can delete sections

>>> del s['add']

But you’ll need to refresh your reader to see the effect.

>>> list(config_reader)
['DEFAULT', 'nothing', 'add']
>>> config_reader = ConfigReader(ini_filepath)
>>> list(config_reader)
['DEFAULT', 'nothing']

You can use update to write several sections at the same time. Note that existing sections will be completely overwritten.

>>> s.update({'nothing': {'like': 'you'}, 'new_section': {'a': 'b', 'c': 'd'}})
>>> ConfigReader(ini_filepath).to_dict()
{'DEFAULT': {}, 'nothing': {'like': 'you'}, 'new_section': {'a': 'b', 'c': 'd'}}

Warning: On the other hand, updating a section will not persist the updates

Updates are automatically persisted at the top level, as shown in the example above. This means you can change a section entirely, but partial updates of a section will not be persisted.

You’ll see the updated section in the store.

>>> s['nothing'].update({'something': 'else'})
>>> dict(s['nothing'])
{'like': 'you', 'something': 'else'}

But it’s not automatically persisted

>>> dict(ConfigReader(ini_filepath)['nothing'])
{'like': 'you'}

… unless you ask for it explicitly

>>> s.persist()
>>> dict(ConfigReader(ini_filepath)['nothing'])
{'like': 'you', 'something': 'else'}

# TODO: Could make section updates auto-persistent by wrapping configparser.SectionProxy

For your convenience, the ConfigStore is also a context manager, that will, you guessed, persist stuff when (and only when) you exit it.

>>> ConfigReader(ini_filepath).to_dict()
{'DEFAULT': {}, 'nothing': {'like': 'you', 'something': 'else'}, 'new_section': {'a': 'b', 'c': 'd'}}
>>> with ConfigStore(ini_filepath) as s:
...     del s['new_section']  # that's usually immediately persisted. This time, it'll wait to be
...     del s['nothing']['something']  # delete the something field of nothing section
...     s['nothing'].update({'like': 'that', 'ever': 'happened'})  # update 'like' config and add an 'ever' one
>>> ConfigReader(ini_filepath).to_dict()
{'DEFAULT': {}, 'nothing': {'like': 'that', 'ever': 'happened'}}
class BasicInterpolation#

Bases: Interpolation

Interpolation as implemented in the classic ConfigParser.

The option values can contain format strings which refer to other values in the same section, or values in the special default section.

For example:

something: %(dir)s/whatever

would resolve the “%(dir)s” to the value of dir. All reference expansions are done late, on demand. If a user needs to use a bare % in a configuration file, she can escape it by writing %%. Other % usage is considered a user error and raises InterpolationSyntaxError.

class ExtendedInterpolation#

Bases: Interpolation

Advanced variant of interpolation, supports the syntax used by zc.buildout. Enables interpolation between sections.

get(k, default=None)[source]#

Needed because the Store.get didn’t catch the NoSectionError

Return type:

object

persist()[source]#

Persists the data (if not in a context manager). Persists means to call

to_dict()[source]#

Return the whole config as a {section: {key: value}} dict.

Return type:

dict[str, dict[str, str]]

config2py.Configs#

alias of SecureTextFiles

class config2py.FileStore(filepath, *, key_path=None, loader=None, dumper=None, mode='r', dump_kwargs=None, create_file_content=None, create_key_path_content=None, follow_symlinks=True)[source]#

Bases: SyncStore

A SyncStore backed by a file with automatic format detection.

Supports nested key paths for working with specific sections.

Parameters:
  • filepath (Union[str, Path]) – Path to file (supports ~ expansion)

  • key_path (Union[str, Tuple[str, ...], None]) – Optional nested path to operate on

  • loader (Optional[Callable[[str], dict]]) – Optional custom loader (auto-detected from extension if not provided)

  • dumper (Optional[Callable[[dict], str]]) – Optional custom dumper (auto-detected from extension if not provided)

  • mode (str) – File read mode (‘r’ for text, ‘rb’ for binary)

  • dump_kwargs (Optional[dict]) – Additional kwargs for dumper

  • create_file_content (Optional[Callable[[], dict]]) – Optional factory callable that returns initial dict content for missing files. If None, FileNotFoundError is raised for missing files.

  • create_key_path_content (Optional[Callable[[], Any]]) – Optional factory callable that returns initial content for missing key_path. If None, KeyError is raised for missing key paths.

  • follow_symlinks (bool) – If False, writing refuses (OSError) to go through a symlink at filepath (or a file with several hard links), instead of writing to its target (see i2mint/config2py#45). Default True, like open.

Example

>>> import tempfile
>>> import os
>>>
>>> # Basic usage with existing file
>>> with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
...     _ = f.write('{"section": {"key": "value"}}')
...     temp_file = f.name
>>>
>>> section = FileStore(temp_file, key_path='section')
>>> section['key']
'value'
>>> section['new'] = 'data'
>>> os.unlink(temp_file)
>>>
>>> # Auto-create missing file and key_path
>>> with tempfile.TemporaryDirectory() as tmpdir:
...     new_file = os.path.join(tmpdir, 'config.json')
...     store = FileStore(
...         new_file,
...         key_path='servers',
...         create_file_content=lambda: {},
...         create_key_path_content=lambda: {}
...     )
...     store['myserver'] = {'command': 'python'}
...     'myserver' in store
True
exception config2py.InsecureConfigFolderWarning[source]#

Bases: Config2PyWarning

A folder used to store config values (which may be secrets) is owned by another user or writable by others, who could plant a symlink or file there to redirect or read those values (see i2mint/config2py#45).

class config2py.JsonStore(filepath, *, key_path=None, indent=2, ensure_ascii=False, follow_symlinks=True, **dump_kwargs)[source]#

Bases: FileStore

A FileStore specialized for JSON files.

Pre-configured with json.loads/dumps and sensible defaults.

Parameters:
  • filepath (Union[str, Path]) – Path to JSON file

  • key_path (Union[str, Tuple[str, ...], None]) – Optional nested path to operate on

  • indent (int) – JSON indentation (default: 2)

  • follow_symlinks (bool) – See FileStore.

  • ensure_ascii (bool) – Whether to escape non-ASCII (default: False)

  • follow_symlinks – See FileStore.

  • **dump_kwargs – Additional kwargs for json.dumps

exception config2py.MissingConfigFileWarning[source]#

Bases: Config2PyWarning

A path given as a config source is not an existing, readable file (it is missing, a folder, or unreadable), so it was read as empty (see i2mint/config2py#27 and /43).

class config2py.SecretRule(rule, pattern, literals=(), word_start=True, wrappable=True, ignore_case=False)[source]#

Bases: object

A secret’s shape: rule names it, pattern is its expression.

Data only; the matching engine is the user’s (liaise scans message views with it, has_secret() a plain string). literals: strings one of which every match contains (in case-folded text, with ignore_case), a cheap pre-filter; empty: always scan. word_start: a match must start a word. wrappable: a hint for engines that also look for the rule in text with line breaks and markup removed (a token split by them): such a pattern must not fail after an unbounded repetition. has_secret() scans the text as given and ignores it.

may_match(text)[source]#

Whether text holds one of literals, or the rule has none.

Return type:

bool

search(text)[source]#

Whether the rule matches text.

Return type:

bool

class config2py.SyncStore(loader, dumper)[source]#

Bases: MutableMapping

A MutableMapping that automatically syncs changes to backing storage.

Supports deferred sync via context manager for efficient batch operations.

Parameters:
  • loader (Callable[[], dict]) – Function that returns the current data as a dict

  • dumper (Callable[[dict], None]) – Function that persists the data dict to storage

Example

>>> def my_loader():
...     return {'x': 1}
>>>
>>> data_holder = []
>>> def my_dumper(data):
...     data_holder.clear()
...     data_holder.append(data.copy())
>>>
>>> store = SyncStore(my_loader, my_dumper)
>>> store['y'] = 2  # Auto-syncs
>>> data_holder[0]
{'x': 1, 'y': 2}
>>>
>>> # Batch with context manager
>>> with store:
...     store['a'] = 1
...     store['b'] = 2
...     # Not synced yet
>>> data_holder[0]  # Now synced
{'x': 1, 'y': 2, 'a': 1, 'b': 2}
flush()[source]#

Sync data to backing storage if changes exist.

Return type:

None

config2py.ask_user_for_input(prompt, default='', *, mask_input=<function looks_like_secret>, masking_toggle_str=None, egress=<function identity>)[source]#

Ask the user for input, optionally masking, validating and transforming the input.

Parameters:
  • prompt (str) – Prompt to display to the user

  • default (str) – Default value to return if the user enters nothing

  • mask_input (bool | Callable[[str], bool]) – Whether to mask the user’s input: a bool, or a prompt -> bool predicate. The default, looks_like_secret, masks prompts that mention something secret-looking (API_KEY, TOKEN, PASSWORD, …) and echoes the others. When masking is decided by a predicate and stdin is piped (not a terminal), the response is read from stdin, as it was before this default existed. An explicit True always uses getpass.getpass, which reads the terminal even when stdin is piped.

  • masking_toggle_str (str) – String to toggle input masking. If None, no toggle is available. If not None (a common choice is the empty string) the user can enter this string to toggle input masking (so it can’t be an answer: a toggle string that is empty or equal to a non-empty default raises ValueError, since the default could not then be accepted).

  • egress (Callable) – Function to apply to the user’s response before returning it. This can be used to validate the response, for example.

Return type:

str

Returns:

The user’s response (or the default value if the user entered nothing)

config2py.ensure_seeded(target, package_name, seed_subpackage, filename, *, seed_data_dir='_seed_data')[source]#

Copy a bundled seed file to target if it does not already exist.

Reads the seed from importlib.resources.files( "{package_name}.{seed_data_dir}.{seed_subpackage}") / filename and writes its bytes to target. If target already exists, this is a no-op (user edits are preserved).

Parameters:
  • target (Union[str, Path]) – Destination path for the seeded file.

  • package_name (str) – Top-level Python package that ships the seed data.

  • seed_subpackage (str) – Subdirectory inside _seed_data (e.g. "resources" or "config").

  • filename (str) – Name of the seed file.

  • seed_data_dir (str) – Name of the seed-data directory inside package_name (default "_seed_data").

Return type:

Path

Returns:

The resolved target as a Path.

Example

>>> from config2py import ensure_seeded
>>> # ensure_seeded("/tmp/myfile.txt", "mypkg", "resources", "myfile.txt")
config2py.extract_exports(exports, *, on_missing='warn')[source]#

Get a dict of {name: value} pairs from the name="value" pairs of unix export lines (that is, lines of the ``export NAME="VALUE" format

Parameters:
  • exports – Filepath (str or os.PathLike) or string contents thereof

  • on_missing (str) – What to do when exports looks like a filepath (a single, non-blank line with no export in it) that is not an existing file: "warn" (the default) issues a MissingConfigFileWarning and returns {}, "raise" raises FileNotFoundError, "ignore" returns {} (see i2mint/config2py#27).

Return type:

dict

Returns:

A dict of extracted {name: value} pairs

>>> extract_exports('export KEY="secret"\nexport TOKEN="arbitrary"')
{'KEY': 'secret', 'TOKEN': 'arbitrary'}
>>> extract_exports('export KEY="secret"')  # a single line of content works too
{'KEY': 'secret'}

A mistyped path is not silently read as empty content:

>>> extract_exports('no/such/path/.env', on_missing='raise')
Traceback (most recent call last):
  ...
FileNotFoundError: [Errno 2] No such config file: 'no/such/path/.env'

Use case:#

You have access to environment variables through os.environ, but if you want to extract exports from only a specific file (env vars are often placed in different linked files), or the exports are defined in a string you hold, then this simple parser can be useful.

config2py.get_app_config_folder(app_name='config2py', *, setup_callback=<function _default_folder_setup>, ensure_exists=False, folder_kind='config')#

Retrieve or create the app directory specific to the given app name and folder kind.

The folder kind determines where the app’s files are stored. Here are concise explanations for each folder kind:

  • config: User preferences and settings files (e.g., API keys, theme preferences, editor settings). Files users might edit manually or that define how the app behaves.

  • data: Essential user-created content and application state (e.g., databases, saved games, user documents, session files). Data that should be backed up and persists across updates.

  • cache: Temporary, regeneratable files (e.g., downloaded images, compiled assets, web cache). Can be safely deleted to free space without losing user work.

  • state: Application state and logs that persist between sessions but aren’t critical user data (e.g., command history, undo history, recently opened files, log files). Unlike cache, shouldn’t be auto-deleted.

  • runtime: Temporary runtime files that only exist while the app runs (e.g., PID files, Unix sockets, lock files, named pipes). Typically cleared on logout/reboot.

  • TL;DR: config = settings, data = user files, cache = disposable, state = logs/history, runtime = process files.

Parameters:
  • app_name (str) – Name of the app for which the directory is needed.

  • setup_callback (Callable[[str], None]) – A callback function to initialize the directory. Default is _default_folder_setup.

  • ensure_exists (bool) – Whether to ensure the directory exists.

  • folder_kind (Literal['config', 'data', 'cache', 'state', 'runtime']) – Type of folder (‘config’, ‘data’, ‘cache’, ‘state’, or ‘runtime’). Default is ‘config’ for backward compatibility.

Returns:

Path to the app directory.

Return type:

str

By default, the app will be “config2py” and folder_kind will be “config”. The exact text of the path is platform-specific (~/.config/config2py under the XDG standards, %APPDATA%\config2py on Windows), so we assert the properties that hold everywhere: it is an absolute path named after the app, sitting directly inside the ‘config’ root directory.

>>> folder = get_app_folder()
>>> os.path.isabs(folder)
True
>>> os.path.basename(folder)
'config2py'
>>> os.path.dirname(folder) == get_app_rootdir('config')
True

You can specify a different app name and folder kind:

>>> get_app_folder('my_app', folder_kind='data')
'/Users/.../.local/share/my_app'
>>> get_app_folder('my_app', folder_kind='cache')
'/Users/.../.cache/my_app'

You can also specify a path relative to the app root directory:

>>> get_app_folder('another/app/subfolder', folder_kind='data')
'/Users/.../.local/share/another/app/subfolder'

If ensure_exists is True, the directory will be created and initialized with the setup_callback:

>>> path = get_app_folder('my_app', ensure_exists=True)
>>> os.path.exists(path)
True
config2py.get_app_data_folder(app_name='config2py', *, setup_callback=<function _default_folder_setup>, ensure_exists=False, folder_kind='data')#

Retrieve or create the app directory specific to the given app name and folder kind.

The folder kind determines where the app’s files are stored. Here are concise explanations for each folder kind:

  • config: User preferences and settings files (e.g., API keys, theme preferences, editor settings). Files users might edit manually or that define how the app behaves.

  • data: Essential user-created content and application state (e.g., databases, saved games, user documents, session files). Data that should be backed up and persists across updates.

  • cache: Temporary, regeneratable files (e.g., downloaded images, compiled assets, web cache). Can be safely deleted to free space without losing user work.

  • state: Application state and logs that persist between sessions but aren’t critical user data (e.g., command history, undo history, recently opened files, log files). Unlike cache, shouldn’t be auto-deleted.

  • runtime: Temporary runtime files that only exist while the app runs (e.g., PID files, Unix sockets, lock files, named pipes). Typically cleared on logout/reboot.

  • TL;DR: config = settings, data = user files, cache = disposable, state = logs/history, runtime = process files.

Parameters:
  • app_name (str) – Name of the app for which the directory is needed.

  • setup_callback (Callable[[str], None]) – A callback function to initialize the directory. Default is _default_folder_setup.

  • ensure_exists (bool) – Whether to ensure the directory exists.

  • folder_kind (Literal['config', 'data', 'cache', 'state', 'runtime']) – Type of folder (‘config’, ‘data’, ‘cache’, ‘state’, or ‘runtime’). Default is ‘config’ for backward compatibility.

Returns:

Path to the app directory.

Return type:

str

By default, the app will be “config2py” and folder_kind will be “config”. The exact text of the path is platform-specific (~/.config/config2py under the XDG standards, %APPDATA%\config2py on Windows), so we assert the properties that hold everywhere: it is an absolute path named after the app, sitting directly inside the ‘config’ root directory.

>>> folder = get_app_folder()
>>> os.path.isabs(folder)
True
>>> os.path.basename(folder)
'config2py'
>>> os.path.dirname(folder) == get_app_rootdir('config')
True

You can specify a different app name and folder kind:

>>> get_app_folder('my_app', folder_kind='data')
'/Users/.../.local/share/my_app'
>>> get_app_folder('my_app', folder_kind='cache')
'/Users/.../.cache/my_app'

You can also specify a path relative to the app root directory:

>>> get_app_folder('another/app/subfolder', folder_kind='data')
'/Users/.../.local/share/another/app/subfolder'

If ensure_exists is True, the directory will be created and initialized with the setup_callback:

>>> path = get_app_folder('my_app', ensure_exists=True)
>>> os.path.exists(path)
True
config2py.get_app_folder(app_name='config2py', *, setup_callback=<function _default_folder_setup>, ensure_exists=False, folder_kind='config')[source]#

Retrieve or create the app directory specific to the given app name and folder kind.

The folder kind determines where the app’s files are stored. Here are concise explanations for each folder kind:

  • config: User preferences and settings files (e.g., API keys, theme preferences, editor settings). Files users might edit manually or that define how the app behaves.

  • data: Essential user-created content and application state (e.g., databases, saved games, user documents, session files). Data that should be backed up and persists across updates.

  • cache: Temporary, regeneratable files (e.g., downloaded images, compiled assets, web cache). Can be safely deleted to free space without losing user work.

  • state: Application state and logs that persist between sessions but aren’t critical user data (e.g., command history, undo history, recently opened files, log files). Unlike cache, shouldn’t be auto-deleted.

  • runtime: Temporary runtime files that only exist while the app runs (e.g., PID files, Unix sockets, lock files, named pipes). Typically cleared on logout/reboot.

  • TL;DR: config = settings, data = user files, cache = disposable, state = logs/history, runtime = process files.

Parameters:
  • app_name (str) – Name of the app for which the directory is needed.

  • setup_callback (Callable[[str], None]) – A callback function to initialize the directory. Default is _default_folder_setup.

  • ensure_exists (bool) – Whether to ensure the directory exists.

  • folder_kind (Literal['config', 'data', 'cache', 'state', 'runtime']) – Type of folder (‘config’, ‘data’, ‘cache’, ‘state’, or ‘runtime’). Default is ‘config’ for backward compatibility.

Returns:

Path to the app directory.

Return type:

str

By default, the app will be “config2py” and folder_kind will be “config”. The exact text of the path is platform-specific (~/.config/config2py under the XDG standards, %APPDATA%\config2py on Windows), so we assert the properties that hold everywhere: it is an absolute path named after the app, sitting directly inside the ‘config’ root directory.

>>> folder = get_app_folder()
>>> os.path.isabs(folder)
True
>>> os.path.basename(folder)
'config2py'
>>> os.path.dirname(folder) == get_app_rootdir('config')
True

You can specify a different app name and folder kind:

>>> get_app_folder('my_app', folder_kind='data')
'/Users/.../.local/share/my_app'
>>> get_app_folder('my_app', folder_kind='cache')
'/Users/.../.cache/my_app'

You can also specify a path relative to the app root directory:

>>> get_app_folder('another/app/subfolder', folder_kind='data')
'/Users/.../.local/share/another/app/subfolder'

If ensure_exists is True, the directory will be created and initialized with the setup_callback:

>>> path = get_app_folder('my_app', ensure_exists=True)
>>> os.path.exists(path)
True
config2py.get_config(key=None, sources=None, *, default=Sentinel('no_default'), egress=None, val_is_valid=<function always_true>, config_not_found_exceptions=(<class 'KeyError'>, <class 'LookupError'>, <class 'FileNotFoundError'>, <class 'config2py.errors.ConfigNotFound'>))[source]#

Get a config value from a list of sources

A source can be a function or a GettableContainer. (A GettableContainer is anything that can be indexed with brackets: obj[k], like dict, list, str, etc..).

Let’s take two sources: a dict and a Callable.

>>> def func(k):
...     if k == 'foo':
...         return 'quux'
...     elif k == 'green':
...         return 'eggs'
...     else:
...         raise KeyError(k)
>>> dict_ = {'foo': 'bar', 'baz': 'qux'}
>>> sources = [func, dict_]

See that get_config go through the sources in the order they were listed, and returns the first value it finds (or manages to compute) for the key:

get_config finds 'foo' in the very first source (func):

>>> get_config('foo', sources)
'quux'

But baz makes func raise an error, so it goes to the next source: dict_. There, it finds 'baz' and returns its value:

>>> get_config('baz', sources)
'qux'

On the other hand, no one manages to find a config value for 'no_a_key', so get_config raises an error:

>>> get_config('no_a_key', sources)
Traceback (most recent call last):
...
config2py.errors.ConfigNotFound: Could not find config for key: no_a_key

But if you provide a default value, it will return that instead:

>>> get_config('no_a_key', sources, default='default')
'default'

You can also provide a function that will be called on the value before it is returned. This is useful if you want to do some post-processing on the value, or if you want to make sure that the value is of a certain type:

This “search the next source if the previous one fails” behavior only applies to errors that mean “not found”: the config_not_found_exceptions argument, which defaults to DFLT_CONFIG_NOT_FOUND_EXCEPTIONS (KeyError, LookupError, FileNotFoundError, ConfigNotFound). Any other error raised by a callable source (a network blip, a bug, a missing import, rejected credentials) propagates, rather than being hidden by a silent move to the next, possibly less trusted, source:

>>> def flaky(k):
...     raise RuntimeError("network blip")
>>> get_config('foo', [flaky, dict_])
Traceback (most recent call last):
...
RuntimeError: network blip

Pass config_not_found_exceptions=LEGACY_CONFIG_NOT_FOUND_EXCEPTIONS (that is, (Exception,), the default before config2py 0.1.80) to fall through on any error (see i2mint/config2py#25):

>>> get_config('foo', [flaky, dict_],
...            config_not_found_exceptions=LEGACY_CONFIG_NOT_FOUND_EXCEPTIONS)
'bar'

Further, your sources may return a value, but not one that you consider valid: For example, a sentinel like None. In this case you may want the search to continue. This is what the val_is_valid argument is for. It is a function that takes a value and returns a boolean. If it returns False, the search will continue. If it returns True, the search will stop and the value will be returned.

Finally, we have egress : Callable[[KT, TT], VT]. This is a function that takes a key and a value, and returns a value. It is called after the value has been found, and its return value is the one that is returned by get_config. This is useful if you want to do some post-processing on the value, or before you return the value, or if you want to do some caching.

>>> config_store = dict()
>>> def store_before_returning(k, v):
...    config_store[k] = v
...    return v
>>> get_config('foo', sources, egress=store_before_returning)
'quux'
>>> config_store
{'foo': 'quux'}

Note that a source can be a callable or a GettableContainer (most of the time, a Mapping (e.g. dict)). Here, you should be compelled to use the resources of dol (https://pypi.org/project/dol/) which will allow you to make Mapping objects for all sorts of data sources.

For more info, see: i2mint/config2py#4

config2py.get_configs_folder_for_app(app_name='config2py', *, configs_name='configs', app_dir_setup_callback=<function _default_folder_setup>, config_dir_setup_callback=<function _default_folder_setup>, ensure_exists=True)[source]#

Retrieve or create the configs directory specific to the given app name.

Parameters:
  • app_name (str) – Name of the app for which the configs directory is needed.

  • configs_name (str) – Name of the configs directory.

  • app_dir_setup_callback (Callable[[str], None]) – A callback function to initialize the app directory. Default is _default_folder_setup.

  • config_dir_setup_callback (Callable[[str], None]) – A callback function to initialize the configs directory. Default is _default_folder_setup.

  • ensure_exists (bool) – Whether to create (and set up) the directory. With False, only the path is computed: nothing is created or chmod-ed.

config2py.get_configs_local_store(config_src='/home/runner/.config/config2py/configs', *, configs_name='configs', follow_symlinks=True, on_unsafe_folder='warn', kind='auto')[source]#

Get the local store of configs.

Parameters:
  • config_src – A specification of the local config store. By default: If it’s a directory, it’s assumed to be a folder of text files. If it’s a file, it’s assumed to be an ini or cfg file. If it’s a string, it’s assumed to be an app name, from which to create a folder (a pathlib.Path is always a path).

  • follow_symlinks (bool) – Whether the store may write through a symlink at a value (or ini) file’s path. False refuses to (see i2mint/config2py#45).

  • on_unsafe_folder (str) – "warn" (default), "raise" or "ignore" when a folder store’s root (or, for an ini file, its folder; a sticky one like /tmp is fine) is owned by another user or writable by its group or by others (see SecureTextFiles).

  • kind (str) – How to read config_src: "auto" (default), "path" or "app". In "auto" mode, a pathlib.Path, an absolute path, or a string containing os.sep or os.altsep is a path, and any other string is an app name, even if a directory of that name exists in the current working directory (so as not to change where existing callers read and write; only an existing .ini/.cfg file of that name is used as a file). kind="path" makes a bare name such as "configs" mean that directory (or file); kind="app" makes any string an app name. See i2mint/config2py#28.

The default, DFLT_CONFIG_FOLDER, is config2py’s own configs folder. It is created here, on first use, rather than at import (see i2mint/config2py#26).

config2py.has_secret(text, *, rules=(SecretRule(rule='github-token', pattern='gh[pousr]_[A-Za-z0-9]{20, }', literals=('ghp_', 'gho_', 'ghu_', 'ghs_', 'ghr_'), word_start=True, wrappable=True, ignore_case=False), SecretRule(rule='github-fine-grained-token', pattern='github_pat_\\w{20, }', literals=('github_pat_', ), word_start=True, wrappable=True, ignore_case=False), SecretRule(rule='sk-api-key', pattern='sk-[\\w-]{20, }', literals=('sk-', ), word_start=True, wrappable=True, ignore_case=False), SecretRule(rule='aws-access-key', pattern='AKIA[0-9A-Z]{16}\\b', literals=('AKIA', ), word_start=True, wrappable=True, ignore_case=False), SecretRule(rule='hugging-face-token', pattern='hf_[A-Za-z0-9]{30, }', literals=('hf_', ), word_start=True, wrappable=True, ignore_case=False), SecretRule(rule='slack-token', pattern='xox[baprs]-[A-Za-z0-9-]{10, }', literals=('xoxb-', 'xoxa-', 'xoxp-', 'xoxr-', 'xoxs-'), word_start=True, wrappable=True, ignore_case=False), SecretRule(rule='private-key', pattern='-----BEGIN (?:(?:[A-Z0-9]{1, 16} ){0, 4}PRIVATE KEY|PGP PRIVATE KEY BLOCK)-----', literals=('-----BEGIN ', ), word_start=False, wrappable=False, ignore_case=False), SecretRule(rule='gitlab-token', pattern='glpat-[\\w-]{20}', literals=('glpat-', ), word_start=True, wrappable=True, ignore_case=False), SecretRule(rule='google-api-key', pattern='AIza[\\w-]{35}', literals=('AIza', ), word_start=True, wrappable=True, ignore_case=False), SecretRule(rule='npm-token', pattern='(?i:npm_[a-z0-9]{36})', literals=('npm_', ), word_start=True, wrappable=True, ignore_case=True), SecretRule(rule='pypi-token', pattern='pypi-AgEIcHlwaS5vcmc[\\w-]{50, 1000}', literals=('pypi-AgEIcHlwaS5vcmc', ), word_start=True, wrappable=True, ignore_case=False), SecretRule(rule='sendgrid-api-key', pattern='SG\\.[A-Za-z0-9=_.-]{66}', literals=('SG.', ), word_start=True, wrappable=True, ignore_case=False), SecretRule(rule='age-secret-key', pattern='AGE-SECRET-KEY-1[QPZRY9X8GF2TVDW0S3JN54KHCE6MUA7L]{58}', literals=('AGE-SECRET-KEY-1', ), word_start=True, wrappable=True, ignore_case=False), SecretRule(rule='telegram-bot-token', pattern='[0-9]{5, 16}: A[\\w-]{34}(?![\\w-])', literals=(':A', ), word_start=True, wrappable=True, ignore_case=False), SecretRule(rule='stripe-key', pattern='(?:sk|rk)_(?:test|live|prod)_[A-Za-z0-9]{10, 99}', literals=('k_test_', 'k_live_', 'k_prod_'), word_start=True, wrappable=True, ignore_case=False), SecretRule(rule='shopify-token', pattern='shpat_[a-fA-F0-9]{32}', literals=('shpat_', ), word_start=True, wrappable=True, ignore_case=False), SecretRule(rule='digitalocean-token', pattern='dop_v1_[a-f0-9]{64}', literals=('dop_v1_', ), word_start=True, wrappable=True, ignore_case=False), SecretRule(rule='slack-webhook', pattern='(?:https?://)?hooks\\.slack\\.com/(?:services|workflows|triggers)/[A-Za-z0-9+/]{43, 56}', literals=('hooks.slack.com/', ), word_start=True, wrappable=True, ignore_case=False), SecretRule(rule='slack-app-token', pattern='(?i:xapp-\\d-[A-Z0-9]{1, 64}-\\d{1, 16}-[a-z0-9]{1, 128})', literals=('xapp-', ), word_start=True, wrappable=True, ignore_case=True), SecretRule(rule='doppler-token', pattern='dp\\.pt\\.[A-Za-z0-9]{43}', literals=('dp.pt.', ), word_start=True, wrappable=True, ignore_case=False), SecretRule(rule='linear-api-key', pattern='lin_api_[A-Za-z0-9]{40}', literals=('lin_api_', ), word_start=True, wrappable=True, ignore_case=False), SecretRule(rule='hugging-face-org-token', pattern='api_org_[A-Za-z]{34}', literals=('api_org_', ), word_start=True, wrappable=True, ignore_case=False), SecretRule(rule='aws-access-key-id', pattern='(?:A3T[A-Z0-9]|ASIA|ABIA|ACCA)[A-Z2-7]{16}\\b', literals=('A3T', 'ASIA', 'ABIA', 'ACCA'), word_start=True, wrappable=True, ignore_case=False), SecretRule(rule='postman-api-key', pattern='PMAK-[A-Fa-f0-9]{24}-[A-Fa-f0-9]{34}', literals=('PMAK-', ), word_start=True, wrappable=True, ignore_case=False), SecretRule(rule='grafana-service-account-token', pattern='(?i:glsa_[a-z0-9]{32}_[a-f0-9]{8})', literals=('glsa_', ), word_start=True, wrappable=True, ignore_case=True), SecretRule(rule='perplexity-api-key', pattern='pplx-[A-Za-z0-9]{48}', literals=('pplx-', ), word_start=True, wrappable=True, ignore_case=False), SecretRule(rule='sentry-user-token', pattern='sntryu_[a-f0-9]{64}', literals=('sntryu_', ), word_start=True, wrappable=True, ignore_case=False), SecretRule(rule='pulumi-token', pattern='pul-[a-f0-9]{40}', literals=('pul-', ), word_start=True, wrappable=True, ignore_case=False), SecretRule(rule='vault-token', pattern='hvs\\.[\\w-]{90, 120}', literals=('hvs.', ), word_start=True, wrappable=True, ignore_case=False), SecretRule(rule='1password-service-account-token', pattern='ops_eyJ[A-Za-z0-9+/]{250, }={0, 3}', literals=('ops_eyJ', ), word_start=True, wrappable=True, ignore_case=False), SecretRule(rule='jwt', pattern='ey[A-Za-z0-9]{17, 4096}\\.ey[A-Za-z0-9/\\\\_-]{17, 4096}\\.(?: [A-Za-z0-9/\\\\_-]{10, 4096}={0, 2})?', literals=('.ey', ), word_start=True, wrappable=False, ignore_case=False), SecretRule(rule='azure-sas', pattern='[?&]sig=[A-Za-z0-9%+/=]{40, }', literals=('sig=', ), word_start=False, wrappable=True, ignore_case=False), SecretRule(rule='azure-storage-account-key', pattern='AccountKey=[A-Za-z0-9+/=]{80, 100}', literals=('AccountKey=', ), word_start=False, wrappable=True, ignore_case=False), SecretRule(rule='azure-connection-sas', pattern='SharedAccessSignature=[^;\\s]{20, }', literals=('SharedAccessSignature=', ), word_start=False, wrappable=True, ignore_case=False)), patterns=(re.compile('(?i)(?<![a-z0-9-])(?:proxy-)?(?:authorization|cookie|set-cookie)\\s*:', re.IGNORECASE), re.compile('(?i)\\b(?: bearer|basic)\\s+(? = [a-z0-9._~+/=-]{0, 512}(?-i: [A-Z0-9]))[a-z0-9._~+/ = -]{8, }', re.IGNORECASE), re.compile('(?i)(?<![a-z0-9])(?: [a-z0-9]{1, 32}[_.-]|[a-z][a-z0-9]{0, 31}(?=(?-i:[A-Z]))){0, 4}(?: pass(?:wor)?d|pass|pwd|secret|api[_-]?key|access[_-]?key|private[_-]?key|credentials?)(?:[_.-]?(?:id|key|token))?[\\, re.IGNORECASE), re.compile('(?i)(?<![a-z0-9])(?: [a-z0-9]{1, 32}[_.-]|[a-z][a-z0-9]{0, 31}(?=(?-i:[A-Z]))){0, 4}(?: token|session|sid|auth)(?:[_.-]?(?:id|key|token))?[\\"\']?\\s*[ = :]\\s*[\\"\']?(?=[^\\s\\"\', ;]{0, 512}\\d)[^\\s\\"\', re.IGNORECASE), re.compile('(?i)\\b[a-z][a-z0-9+.-]{0, 15}: //[^/\\s:@]{1, 64}: [^/\\s@]{1, 128}@', re.IGNORECASE), re.compile('-----BEGIN [A-Z ]*PRIVATE KEY-----'), re.compile('\\beyJ[a-zA-Z0-9_-]{8, }\\.[a-zA-Z0-9_-]{8, }'), re.compile('\\b(?: (?:sk|pk|rk)[-_](?:live[-_]|test[-_])?[a-zA-Z0-9]{8, }|sk-[a-zA-Z0-9_-]{20, }|gh[pousr]_[a-zA-Z0-9]{20, }|github_pat_[a-zA-Z0-9_]{20, }|whsec_[a-zA-Z0-9]{16, }|glpat-[a-zA-Z0-9_-]{16, }|AIza[a-zA-Z0-), re.compile('(?<![a-zA-Z0-9_-])(?=(?:[a-zA-Z_-]*\\d){4})(?![a-zA-Z0-9_]*-[a-zA-Z0-9_]*-[a-zA-Z0-9_]*-)[a-zA-Z0-9_-]{32, }')))[source]#

Whether text looks like it holds a credential.

True when a contextual pattern (SECRET_TEXT_PATTERNS: headers, key=value, URL credentials, JWTs, long opaque strings) or a distinctive-prefix rule (SECRET_RULES) matches. Both are keyword-only seams.

>>> [has_secret(t) for t in ("cursor (size=first, cursor=after)", "10000 results",
...                          "needs Cookie: sid=abc", "api_key=a1b2c3d4e5",
...                          "page via ?pageToken=", "Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0",
...                          "use glpat-" + "a" * 20)]
[False, False, True, True, False, True, True]
Return type:

bool

config2py.is_repl()[source]#

Determines if the Python interpreter is running in REPL.

To test: If you put it in a module.py, do a print of it in the module, and do python module.py it should print False. If you do python -i module.py, or call it from a python console or jupyter notebook, it should return True.

Returns:

True if running in a REPL, False otherwise.

Return type:

bool

is_repl returns True if any function in is_repl.repl_conditions (a set of no-argument callables) returns True. By default that set checks whether get_ipython is in globals, or whether __main__ has no __file__ attribute. Mutate is_repl.repl_conditions in place (e.g. is_repl.repl_conditions.add(fn)) to change the checks – rebinding the attribute to a new set has no effect, since is_repl reads the original set.

config2py.parse_assignments_from_py_source(source_code, *, name_filt=None, value_filt=<function _value_node_is_instance_of>)[source]#

Parse assignments from python source code.

>>> source_code = '''a = 1
... b = 'hello'
... c = [1, 2, 3]
... def func():
...     d = 4
... '''
>>> dict(parse_assignments_from_py_source(source_code))
{'a': 1, 'b': 'hello', 'c': [1, 2, 3], 'd': 4}
config2py.process_path(*path, ensure_dir_exists=False, assert_exists=False, ensure_endswith_slash=False, ensure_does_not_end_with_slash=False, expanduser=True, expandvars=True, abspath=True, rootdir='')[source]#

Process a path string, ensuring it exists, and optionally expanding user.

Parameters:
  • path (Iterable[str]) – The path to process. Can be multiple components of a path.

  • ensure_dir_exists (int | bool) – Whether to ensure the path exists.

  • assert_exists (bool) – Whether to assert that the path exists.

  • ensure_endswith_slash (bool) – Whether to ensure the path ends with a slash.

  • ensure_does_not_end_with_slash (bool) – Whether to ensure the path does not end with a slash.

  • expanduser (bool) – Whether to expand the user in the path.

  • expandvars (bool) – Whether to expand environment variables in the path.

  • abspath (bool) – Whether to convert the path to an absolute path.

  • rootdir (str) – The root directory to prepend to the path.

Returns:

The processed path.

Return type:

str

The result uses the running OS’s native separator, so these examples assert OS-independently (the literal forward-slash form is what you get on POSIX):

>>> import os
>>> process_path('a', 'b', 'c').endswith(os.path.join('a', 'b', 'c'))
True
>>> p = process_path(
...     'a', 'b', 'c', rootdir='root_dir',
...     ensure_endswith_slash=True, abspath=False, expanduser=False, expandvars=False,
... )
>>> p == os.path.join('root_dir', 'a', 'b', 'c') + os.sep
True
config2py.register_extension(ext, loader, dumper)[source]#

Register loader/dumper for a file extension.

Return type:

None

config2py.simple_config_getter(configs_src='/home/runner/.config/config2py/configs', *, first_look_in_env_vars=True, ask_user_if_key_not_found=None, config_store_factory=<function get_configs_local_store>)[source]#

Make a simple config getter from a “central” config source specification.

The purpose of this function is to implement a common pattern of getting configs: One that, by default (but optionally), looks in environment variables first, then in a central config store, created via a simple configs_src specification and then, if the key is not found in this “central” store, optionally (but not by default) asks the user for the value and stores it in the central config store.

Parameters:
  • configs_src (str) – A specification of the central config store. By default: If it’s a directory (with at least a slash), it’s assumed to be a folder of text files. If it’s a file, it’s assumed to be an ini or cfg file. If it’s a string, it’s assumed to be an app name, from which to create a folder

  • first_look_in_env_vars (bool) – Whether to look in environment variables first

  • ask_user_if_key_not_found (bool) – Whether to ask the user if the key is not found (and subsequently store the key in the central config store)

  • config_store_factory (Callable) – A function that takes a config source specification and returns the central config store

config2py.sources_chainmap(sources, val_is_valid=<function always_true>, config_not_found_exceptions=(<class 'KeyError'>, <class 'LookupError'>, <class 'FileNotFoundError'>, <class 'config2py.errors.ConfigNotFound'>))[source]#

Create a ChainMap from a list of sources

Return type:

ChainMap

config2py.user_gettable(save_to=None, *, prompt_template='Enter a value for {}: ', egress=None, user_asker=<function ask_user_for_input>, val_is_valid=<function is_not_empty>, config_not_found_exceptions=(<class 'KeyError'>, <class 'LookupError'>, <class 'FileNotFoundError'>, <class 'config2py.errors.ConfigNotFound'>, <class 'EOFError'>))[source]#

Create a GettableContainer that asks the user for a value, optionally saving it.

Parameters:
  • save_to (Union[MutableMapping, Callable[[KT, VT], Any], None]) – Where to save the user’s response: a MutableMapping (or anything with a __setitem__), or a (key, value) saver function. If None, the user’s response is not saved.

  • prompt_template (str) – A template string to prompt the user with. It should contain a placeholder for the key, e.g. "Enter a value for {}: ".

  • egress (Callable | None) – A function to apply to the user’s response before returning it. This can be used to validate the response, for example.

  • user_asker (Callable[[str], str]) – A function that asks the user for input. It should take a prompt string and return the user’s response.

  • val_is_valid (Callable[[VT], bool]) – A function that takes a value and returns a boolean. If it returns False, the user will be asked for a new value.

  • config_not_found_exceptions (tuple[type[Exception], ...]) – The exceptions that mean “the user gave no value”: the key is then treated as not found, and get_config moves on (or returns its default). Defaults to DFLT_USER_PROMPT_NOT_FOUND_EXCEPTIONS: the lookup errors plus EOFError. Any other error (from egress validation, say) propagates, with its own text.

When nobody can answer the prompt, the key is “not found” too: an EOFError or OSError raised by user_asker (stdin at end of file, unreadable, or captured by pytest), or a RuntimeError while sys.stdin is None (stdin closed), is re-raised as UserInputUnavailable, a ConfigNotFound.

Returns:

A GettableContainer that asks the user for a value, optionally saving it.

Example

>>> s = user_gettable()
>>> v = s['SOME_KEY']
'SOME_VAL'

This will trigger a prompt for the user to enter the value of SOME_KEY. When they do (say they entered ‘SOME_VAL’) it will return that value.

And if you specify a save_to store (usually a persistent MutableMapping made with the dol package) then it will save the value to that store for future use.

>>> d = dict(some='store')
>>> s = user_gettable(save_to=d)
>>> s['SOME_KEY']
'SOME_VAL'
>>> d
{'some': 'store', 'SOME_KEY': 'SOME_VAL'}

When saving isn’t a simple write (say you need to encrypt, or write to two places), save_to can be a (key, value) function instead:

>>> saved = []
>>> s = user_gettable(
...     save_to=lambda k, v: saved.append((k, v)),
...     user_asker=lambda prompt: 'SOME_VAL',
... )
>>> s['SOME_KEY']
'SOME_VAL'
>>> saved
[('SOME_KEY', 'SOME_VAL')]

Modules

s_configparser

Data Object Layer for configparser standard lib.

errors

Error classes for config2py.

tools

Various tools

base

Base for getting configs from various sources and formats

util

Utility functions for config2py.

secret_text

Value-level detection of credentials in free text.

sync_store

Synchronized key-value stores with automatic persistence.

codecs

Extension-based codec registries for configuration file parsing.