config2py.sync_store#
Synchronized key-value stores with automatic persistence.
Provides MutableMapping interfaces that automatically sync changes to their backing storage. Supports deferred sync via context manager for batch operations.
>>> import tempfile
>>> import json
>>>
>>> # Basic usage
>>> with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
... _ = f.write('{"key": "value"}')
... temp_file = f.name
>>>
>>> store = FileStore(temp_file)
>>> store['new_key'] = 'new_value' # Auto-syncs immediately
>>> assert 'new_key' in store
>>>
>>> # Batch operations with context manager
>>> with store:
... store['a'] = 1
... store['b'] = 2
... store['c'] = 3
... # No sync until context exit
>>>
>>> import os
>>> os.unlink(temp_file)
Functions
|
Register loader/dumper for a file extension. |
|
Get loader/dumper for a file based on extension. |
Classes
|
A MutableMapping that automatically syncs changes to backing storage. |
|
A SyncStore backed by a file with automatic format detection. |
|
A FileStore specialized for JSON files. |
- class config2py.sync_store.FileStore(filepath, *, key_path=None, loader=None, dumper=None, mode='r', dump_kwargs=None, create_file_content=None, create_key_path_content=None)[source]#
Bases:
SyncStoreA 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 onloader (
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)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.
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
- class config2py.sync_store.JsonStore(filepath, *, key_path=None, indent=2, ensure_ascii=False, **dump_kwargs)[source]#
Bases:
FileStoreA FileStore specialized for JSON files.
Pre-configured with json.loads/dumps and sensible defaults.
- Parameters:
- class config2py.sync_store.SyncStore(loader, dumper)[source]#
Bases:
MutableMappingA MutableMapping that automatically syncs changes to backing storage.
Supports deferred sync via context manager for efficient batch operations.
- Parameters:
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}