Use INI interpolation for a derived local path

INI interpolation can express a derived local path without repeating its base component. ConfigParser uses basic interpolation by default, so %(root)s/cache refers to the root option in the same section. The example reads a paths section where root is the relative local directory local-data; retrieving cache expands the reference to local-data/cache.

The assertions deliberately inspect both forms. get(..., raw=True) returns the stored template, while an ordinary get() returns the interpolated value. This distinction matters for diagnostics and for tools that need to preserve a template rather than consume its resolved setting. Interpolation is resolved when the value is retrieved, so referenced options do not need to appear earlier in the INI text.

A derived string is not automatically a usable filesystem location. This example does not create a directory, normalize separators, reject traversal components, or confirm that the path exists. It only demonstrates configuration substitution. A literal percent sign in basic interpolation must be written as %%, and malformed or missing references raise interpolation-related errors when the value is read. read_string() and this Python 3 example require Python 3.2+; no newer API is used. The official interpolation documentation describes the default syntax and on-demand resolution.

AI assistance disclosure: This article was drafted with AI assistance and should be adapted to the target platform's path rules.

import configparser

ini_text = "[paths]\nroot = local-data\ncache = %(root)s/cache\n"
parser = configparser.ConfigParser()
parser.read_string(ini_text)

raw_cache = parser.get("paths", "cache", raw=True)
cache_path = parser.get("paths", "cache")
assert raw_cache == "%(root)s/cache"
assert cache_path == "local-data/cache"

print("cache={0}".format(cache_path))
cache=local-data/cache

Comments

Popular posts from this blog

Compare Two Text Files in Python Without Modifying Them

Seven CSV Quality Checks to Run Before Importing Data

Explain why SQLite transactions cannot make an HTTP call atomic