Pythonic implementation of quiet / verbose flag for functions
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Puzzle4
--
Chapters
00:00 Pythonic Implementation Of Quiet / Verbose Flag For Functions
00:38 Accepted Answer Score 8
01:07 Answer 2 Score 10
02:23 Answer 3 Score 0
02:32 Thank you
--
Full question
https://stackoverflow.com/questions/4147...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #variables #pep8
#avk47
ANSWER 1
Score 10
If you don't want to rely on a logging library, I think your solution is already pythonic enough. It may be a little bit more pythonic to write:
def simple_addition(a, b, silent=True):
res = a + b
if not silent:
print('The answer is %i' % res)
return res
As stated in PEP 8, Other Recommendations, single-line if statements are okay, but discouraged.
There are other possibilities.
Using or
Using the or operator to encode a condition is arguably not pythonic
but personally I think it reads nice: "silent or...", "quiet or...". See below:
def simple_addition(a, b, silent=True):
res = a + b
silent or print('The answer is %i' % res)
return res
The or operator does short-circuit, so print and its arguments are only evaluated when silent is False like when using an if statement.
A disadvantage is that mypy type checking will fail if silent is bound to a boolean type:
$ cat > add.py
def simple_addition(a, b, silent: bool = True):
res = a + b
silent or print('The answer is %i' % res)
return res
^D
$ mypy add.py
add.py:3: error: "print" does not return a value
noop ternary
We could also do this:
def noop(*args, **kwargs):
pass
def simple_addition(a, b, silent=True):
_print = noop if silent else print
res = a + b
_print('The answer is %i' % res)
return res
...but it feels rather unpythonic.
ACCEPTED ANSWER
Score 8
Basically you can use the logging module which gives you the ability to set the Level of logging you want, and the logger will save/print/export (based on your config) the logged values.
import logging
logging.warning('Watch out!') # will print a message to the console
logging.info('I told you so') # will not print anything
You can set the level of your logger using:
logging.basicConfig(level=logging.INFO)
And there are many more options there.
ANSWER 3
Score 0
I have tended to go with:
def simple_addition(a, b, verbose=True):
res = a + b
print('The answer is %i' % res) if verbose else None
return res