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:
parent
513de41913
commit
dc428ee19d
8
utils.py
8
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:
|
||||
if safe_default != None:
|
||||
return safe_default
|
||||
else:
|
||||
raise ValueError('identifier (\"%s\") not in table %s' % (string, str(table)))
|
||||
return id
|
||||
|
|
Loading…
Reference in New Issue