pythonoutput-buffering

Why does print argument flush default to False?


I am using print to log the execution of my python scripts.

I use flush = True everywhere because otherwise the print statements sometimes do not occur where they were placed.

I was wondering why the default is flush = False. Can anyone explain?

Thanks!


Solution

  • By not forcing the flush by default, you leave that decision to the underlying object you're writing to. For sys.stdin / stderr this would default to line buffered _io.TextIOWrapper which is usually what you would expect and want on an interactive console. When you swap your output for a file, the default of not forcing a flush with each print/write seems reasonable. Conversely, forcing flush after each print overrides buffering/flushing behavior of the underlying object.

    The obvious caveat being when you for instance run your script through tee, process' own stdout isn't writing directly to the terminal.


    I've poked around a bit more to see if there is any textual evidence regarding the motivation. Adding flush keyword is documented in issue 13761. Apparently suggestion to default to True for stdout was made back in 2012, and dismissed (see towards the bottom of the discussion). I guess this is where one could apply The Zen of Python: "Special cases aren't special enough to break the rules." (No speacial treatment just because we're writing to sys.stdout. ;)

    There is also a link into the mailing list where BDFL himself states:

    I would be fine with adding a new keyword argument to print() in 3.3 to force a flush, as long as it defaults to off.