Skip to content
Advertisement

python if/else and try/except combination without redundancy

While playing around with icecream I programmed the following lines of code

JavaScript

As you can see I want to assign the (same) lambda expression to ic in both cases

  1. if not debugging the code or
  2. if importing icecream is not working

I was wondering if there is a (maybe pythonic) way to handle that idea without redundancy.

Advertisement

Answer

You could define a default, then override it later as needed. I would also add comments to make it clear.

JavaScript

By the way:

  • Named lambdas are bad practice. Use a def instead.
  • I rewrote the function to avoid a double-conditional-expression for better readability.
  • Try to put as little in a “try” clause as necessary, and use else to define what should happen if the try succeeds.

This is based on deceze‘s comment

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement