2447
2447
class Stack(object):
2448
2448
"""A stack of configurations where an option can be defined"""
2450
def __init__(self, sections_def, mutable_section_def=None):
2450
def __init__(self, sections_def, store=None, mutable_section_name=None):
2451
2451
"""Creates a stack of sections with an optional store for changes.
2453
2453
:param sections_def: A list of Section or callables that returns an
2454
2454
iterable of Section. This defines the Sections for the Stack and
2455
2455
can be called repeatedly if needed.
2457
:param mutable_section_def: A callable that returns a MutableSection
2458
where changes are recorded. This defines the MutableSection and can
2459
be called repeatedly.
2457
:param store: The optional Store where modifications will be
2458
recorded. If none is specified, no modifications can be done.
2460
:param mutable_section_name: The name of the MutableSection where
2461
changes are recorded. This requires the ``store`` parameter to be
2461
2464
self.sections_def = sections_def
2462
self.mutable_section_def = mutable_section_def
2466
self.mutable_section_name = mutable_section_name
2464
2468
def get(self, name):
2465
2469
"""Return the *first* option value found in the sections.
2488
2492
# No definition was found
2491
def set(self, name, value):
2492
"""Set a new value for the option.
2495
def _get_mutable_section(self):
2496
"""Get the MutableSection for the Stack.
2494
2498
This is where we guarantee that the mutable section is lazily loaded:
2495
this means we won't load the corresponding store before setting a value.
2499
this means we won't load the corresponding store before setting a value
2500
or deleting an option. In practice the store will often be loaded but
2501
this allows catching some programming errors.
2497
section = self.mutable_section_def()
2503
section = self.store.get_mutable_section(self.mutable_section_name)
2506
def set(self, name, value):
2507
"""Set a new value for the option."""
2508
section = self._get_mutable_section()
2498
2509
section.set(name, value)
2500
2511
def remove(self, name):
2501
"""Remove an existing option.
2503
This is where we guarantee that the mutable section is lazily loaded:
2504
this means we won't load the correspoding store before trying to delete
2505
an option. In practice the store will often be loaded but this allows
2506
catching some programming errors.
2508
section = self.mutable_section_def()
2512
"""Remove an existing option."""
2513
section = self._get_mutable_section()
2509
2514
section.remove(name)
2511
2516
def __repr__(self):