1

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?

1
  • Can you explain how do you build the dictionary? Where are keyx and funx coming from? Commented Mar 8, 2021 at 10:23

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.