mardi 6 avril 2021

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.

Aucun commentaire:

Enregistrer un commentaire