简体   繁体   中英

python, use try/except in dictionary to avoid errors

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM