From 4f47f37280d774fb7ad935616c8391d0689a1f36 Mon Sep 17 00:00:00 2001 From: Daniil Baturin Date: Fri, 8 Sep 2017 04:06:29 +0200 Subject: Make the vyos.config.Config's return_value(s) and list_node functions behave like their Perl counterparts. Most scripts used to do something like my $foo = $config->returnValue("system foo"); if !defined($foo) { $foo = $defaultFooValue; } In most cases values do not exist because they are optional and simply not set. In a substantial minority of cases they don't exist but are mandatory, in this case it's probably a good practice to check if it exists first. In rare but frustrating cases returnValue returns undef because the path is wrong. It was tempting but as it turns out impractical to force the user to handle every undefined value as an error, but the cost of wrapping every return_value call in a try/except block is too high. Instead we should facilitate the most common case. For this, those functions now support an optional named argument default=None so an optional value with a sensible default can be handled like $foo = config.return_value("system foo", default="bar") --- python/vyos/config.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'python') diff --git a/python/vyos/config.py b/python/vyos/config.py index 85dd49e68..edee6b33e 100644 --- a/python/vyos/config.py +++ b/python/vyos/config.py @@ -95,7 +95,7 @@ class Config(object): except VyOSError: return False - def return_value(self, path): + def return_value(self, path, default=None): full_path = self._level + path if self.is_multi(path): raise VyOSError("Cannot use return_value on multi node: {0}".format(full_path)) @@ -106,9 +106,9 @@ class Config(object): out = self._run(self._make_command('returnValue', full_path)) return out except VyOSError: - raise VyOSError("Path doesn't exist: {0}".format(full_path)) + return(default) - def return_values(self, path): + def return_values(self, path, default=[]): full_path = self._level + path if not self.is_multi(path): raise VyOSError("Cannot use return_values on non-multi node: {0}".format(full_path)) @@ -119,9 +119,9 @@ class Config(object): out = self._run(self._make_command('returnValues', full_path)) return out except VyOSError: - raise VyOSError("Path doesn't exist: {0}".format(full_path)) + return(default) - def list_nodes(self, path): + def list_nodes(self, path, default=[]): full_path = self._level + path if self.is_tag(path): try: @@ -129,6 +129,6 @@ class Config(object): values = out.split() return list(map(lambda x: re.sub(r'^\'(.*)\'$', r'\1',x), values)) except VyOSError: - raise VyOSError("Path doesn't exist: {0}".format(full_path)) + return(default) else: raise VyOSError("Cannot use list_nodes on a non-tag node: {0}".format(full_path)) -- cgit v1.2.3