Skip to content

Instantly share code, notes, and snippets.

@blaylockbk
Created July 13, 2020 17:46
Show Gist options
  • Save blaylockbk/758cfee8d910190dfbdd32b203f7b0bd to your computer and use it in GitHub Desktop.
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...
## 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)
@blaylockbk
Copy link
Author

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.

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment