While playing around with icecream I programmed the following lines of code
JavaScript
x
9
1
if __debug__:
2
try:
3
from icecream import ic
4
ic.configureOutput(includeContext=True)
5
except ImportError: # Graceful fallback if IceCream isn't installed.
6
ic = lambda *a: None if not a else (a[0] if len(a) == 1 else a) # noqa
7
else:
8
ic = lambda *a: None if not a else (a[0] if len(a) == 1 else a) # noqa
9
As you can see I want to assign the (same) lambda expression to ic
in both cases
- if not debugging the code or
- 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
1
14
14
1
def ic(*a): # May be overridden later
2
if not a:
3
return None
4
return a[0] if len(a) == 1 else a
5
6
7
if __debug__:
8
try:
9
from icecream import ic # Override default
10
except ImportError:
11
pass # Fallback to default
12
else:
13
ic.configureOutput(includeContext=True)
14
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 thetry
succeeds.