pythonflush

Set print flush=True to default?


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.


Solution

  • 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.