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

if __debug__:
    try:
        from icecream import ic
        ic.configureOutput(includeContext=True)
    except ImportError:  # Graceful fallback if IceCream isn't installed.
        ic = lambda *a: None if not a else (a[0] if len(a) == 1 else a)  # noqa
else:
    ic = lambda *a: None if not a else (a[0] if len(a) == 1 else a)  # noqa

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.

def ic(*a):  # May be overridden later
    if not a:
        return None
    return a[0] if len(a) == 1 else a


if __debug__:
    try:
        from icecream import ic  # Override default
    except ImportError:
        pass  # Fallback to default
    else:
        ic.configureOutput(includeContext=True)

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