Set print flush=True to default?

Viewed 810

I am aware that you can flush after a print statement by setting flush=True like so:

print("Hello World!", flush=True)

However, for cases where you are doing many prints, it is cumbersome to manually set each print to flush=True. Is there a way to set the default to flush=True for Python 3.x? I am thinking of something similar to the print options numpy gives using numpy.set_printoptions.

2 Answers

You can use partial:

from functools import partial
print_flushed = partial(print, flush=True)
print_flushed("Hello world!")

From the documentation:

The partial() is used for partial function application which “freezes” some portion of a function’s arguments and/or keywords resulting in a new object with a simplified signature.

You can use something like this:

def decorator(func):
    printer = func
    def wrapped(*args):
        printer(*args, end=' *\n', flush=True)
    return wrapped

print = decorator(print)

for i in range(5):
    print(i)
0 *
1 *
2 *
3 *
4 *
Related