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
This commit is contained in:
Philipp Maier 2023-06-22 12:20:41 +02:00
parent 513de41913
commit 7209731730
1 changed files with 7 additions and 3 deletions

View File

@ -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