From 720973173065f3be02e69339c8549def3870d718 Mon Sep 17 00:00:00 2001 From: Philipp Maier Date: Thu, 22 Jun 2023 12:20:41 +0200 Subject: [PATCH] utils: allow to use a safe default with str_to_id The input to str_to_id may originate from user input. It may be that the input is not found in the given table. In this case an exception is raised. This may be impractical in some cases. Let's add an optional safe default that is returned in case the string is not found, this can be used to either select default settings or to detect an error. Related: SYS#6473 --- utils.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/utils.py b/utils.py index 1185a0f..841c3fb 100644 --- a/utils.py +++ b/utils.py @@ -99,11 +99,15 @@ def id_to_str(table, nr): return dict_by_nr.get(nr) or '(invalid)' -# Convert a string back to its ID by looking it up in a given table -def str_to_id(table, string): +# Convert a string back to its ID by looking it up in a given table. In +# case the string is not found in the table, use a safe default (optional). +def str_to_id(table, string, safe_default = None): dict_by_name = dict([(name.upper(), nr) for nr, name in table]) id = dict_by_name.get(string.upper()) if id is None: - raise ValueError('identifier (\"%s\") not in table %s' % (string, str(table))) + if safe_default != None: + return safe_default + else: + raise ValueError('identifier (\"%s\") not in table %s' % (string, str(table))) return id