I have a dict like {'key1': fun1(...), 'key2': fun2(...), ...} and this functions could raise errors (undefined), is there a way to use try/except to create the dictionary?
-
Can you explain how do you build the dictionary? Where are keyx and funx coming from?alec_djinn– alec_djinn2021-03-08 10:23:43 +00:00Commented Mar 8, 2021 at 10:23
2 Answers
You could create a helper function like this:
def or_default(v, f, *args, **kw):
try:
return f(*args, **kw)
except:
return v
Then initialize your dictionary this way:
{'key1': or_default(42, fun1, ...), 'key2': or_default('something', fun2, ...), ...}
Essentially what we're doing here is decorating the functions to return a default value if they raise an exception. You can make this even simpler if you want to use the same default value for all the functions (say, None), just have or_default return that value in the except block and get rid of the v parameter.
The reason we have to do it in this way, using a function, is that try/except is not an expression in Python. Other languages do have that as an expression (Kotlin, basically every functional language that supports exceptions), so in those languages you would just use try/except directly.