summaryrefslogtreecommitdiff
path: root/python/vyos/utils/dict.py
diff options
context:
space:
mode:
authorChristian Breunig <christian@breunig.cc>2023-07-15 21:54:12 +0200
committerChristian Breunig <christian@breunig.cc>2023-07-15 21:54:20 +0200
commitea3cacea57592154a93da753e915a3d39761773d (patch)
tree33d657f4f84d3fd6139ae08634e5dea031de9324 /python/vyos/utils/dict.py
parent5f77ccf91eb402c548fc91b2e080a4b2b86f4181 (diff)
downloadvyos-1x-ea3cacea57592154a93da753e915a3d39761773d.tar.gz
vyos-1x-ea3cacea57592154a93da753e915a3d39761773d.zip
T5195: move individual helper functions to vyos.utils module
* FixedDict can be found in vyos.utils.dict.FixedDict * Move vyos.authutils to vyos.utils.auth
Diffstat (limited to 'python/vyos/utils/dict.py')
-rw-r--r--python/vyos/utils/dict.py37
1 files changed, 36 insertions, 1 deletions
diff --git a/python/vyos/utils/dict.py b/python/vyos/utils/dict.py
index 66fe6dad3..9484eacdd 100644
--- a/python/vyos/utils/dict.py
+++ b/python/vyos/utils/dict.py
@@ -13,7 +13,6 @@
# You should have received a copy of the GNU Lesser General Public
# License along with this library. If not, see <http://www.gnu.org/licenses/>.
-
def colon_separated_to_dict(data_string, uniquekeys=False):
""" Converts a string containing newline-separated entries
of colon-separated key-value pairs into a dict.
@@ -270,3 +269,39 @@ def check_mutually_exclusive_options(d, keys, required=False):
if required and (len(present_keys) < 1):
raise ValueError(f"At least one of the following options is required: {orig_keys}")
+
+class FixedDict(dict):
+ """
+ FixedDict: A dictionnary not allowing new keys to be created after initialisation.
+
+ >>> f = FixedDict(**{'count':1})
+ >>> f['count'] = 2
+ >>> f['king'] = 3
+ File "...", line ..., in __setitem__
+ raise ConfigError(f'Option "{k}" has no defined default')
+ """
+
+ from vyos import ConfigError
+
+ def __init__(self, **options):
+ self._allowed = options.keys()
+ super().__init__(**options)
+
+ def __setitem__(self, k, v):
+ """
+ __setitem__ is a builtin which is called by python when setting dict values:
+ >>> d = dict()
+ >>> d['key'] = 'value'
+ >>> d
+ {'key': 'value'}
+
+ is syntaxic sugar for
+
+ >>> d = dict()
+ >>> d.__setitem__('key','value')
+ >>> d
+ {'key': 'value'}
+ """
+ if k not in self._allowed:
+ raise ConfigError(f'Option "{k}" has no defined default')
+ super().__setitem__(k, v)