libconf
libconf is a pure-Python reader/writer for configuration files in libconfig format, commonly used in C/C++ projects. Its interface is designed to be similar to Python's standard `json` module, providing `load()`, `loads()`, `dump()`, and `dumps()` methods. The library is currently at version 2.0.1 and appears to be actively maintained.
Warnings
- breaking Starting with version 2.0.0, `libconf` introduced output validation for `dump()` and `dumps()`. These functions will now raise exceptions if attempting to dump data that cannot be correctly read by a standard C libconfig implementation.
- gotcha Python integer values are dumped without an 'L' suffix if they fit within a C/C++ 32-bit integer range. For larger Python integers, an 'L' suffix is automatically appended. If you need to force an 'L' suffix for a number within the 32-bit range (e.g., for explicit 64-bit representation in libconfig), wrap the integer with `libconf.LibconfInt64`.
- gotcha libconfig distinguishes between 'lists' (enclosed by parentheses `()`, arbitrary values) and 'arrays' (enclosed by brackets `[]`, scalar values of the same type). `libconf` maps libconfig `()`-lists to Python `tuples` and libconfig `[]`-arrays to Python `lists`. This distinction is important when round-tripping data or ensuring compatibility with C libconfig.
- gotcha It is strongly recommended to use Unicode objects (Python 3 `str`) for all input strings or streams passed to `load()` and `loads()`, and for any strings within data structures passed to `dump()` and `dumps()`. `libconf` handles standard escape sequences (`\n`, `\r`, `\t`, `\xNN`).
Install
-
pip install libconf
Imports
- libconf
import libconf
- LibconfInt64
from libconf import LibconfInt64
- LibconfList
from libconf import LibconfList
- LibconfArray
from libconf import LibconfArray
Quickstart
import libconf
import io
# Example libconfig string
config_string = """
version = 2;
window : {
title = "My Application";
position = { x = 10; y = 20; w = 800; h = 600; };
};
capabilities = (
true,
1234567890123456789L,
[1, 2, 3]
);
"""
# Load configuration from a string
config = libconf.loads(config_string)
print("Loaded Config:", config)
print("Window Title:", config.window.title)
# Modify and dump configuration back to a string
config.window.title = "Updated App Title"
config.capabilities = ('new_list_item', 42)
# Demonstrate LibconfInt64 for explicit long suffix
from libconf import LibconfInt64
config['large_number_forced_L'] = LibconfInt64(123)
dumped_string = libconf.dumps(config, indent=2)
print("\nDumped Config:\n", dumped_string)