Created
July 13, 2020 17:46
-
-
Save blaylockbk/758cfee8d910190dfbdd32b203f7b0bd to your computer and use it in GitHub Desktop.
When you have a function that insists on printing something, but you don't want it to print anything, do this...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Based on https://stackoverflow.com/a/46129367/2383070 | |
import os | |
import contextlib | |
def test_print(a): | |
print(f'2 * {a} =') | |
return 2*a | |
# Do not print the print statement in the function: | |
with open(os.devnull, "w") as f, contextlib.redirect_stdout(f): | |
result = test_print(4) | |
print(result) | |
print() | |
# This is the raw function, and it does print the function statements | |
result = test_print(4) | |
print(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
First call to function prints just 8 (becuase it is called after the "with" block).
Second call to function prints statements from the function and 8.