Reputation: 11
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?
Upvotes: 1
Views: 63
Reputation: 10717
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.
Upvotes: 1
Reputation: 5992
You would have to either wrap the whole dictionary creation in a try/except block, or, if you can modify the functions, put the code parts of the functions that could raise errors in try/except blocks.
Upvotes: 0