-
-
Notifications
You must be signed in to change notification settings - Fork 33.6k
Description
Python’s documentation for print() and stdout buffering does not clearly specify the behavior when newline (\n) characters occur inside a single print() call. Users coming from C (where line-buffered stdio flushes on newline) may expect a flush to occur at each newline within the printed string. However, Python does not guarantee this behavior.
This gap can lead to confusion, particularly when demonstrating buffering, interactive console output, or progress indicators.
Example demonstrating the confusion
from time import sleep
print("Hello\nWorld", end='')
sleep(3)
print("Hi there!")
Observed behavior
Both "Hello" and "World" appear immediately, before the sleep. "Hi there!" appears after 3 seconds.
Expected behavior (based on C-style line buffering)
"Hello" should appear first; "WorldHi there!" should appear after the 3-second delay.
Reason for confusion
In C (stdio) with line-buffered stdout:
printf("Hello\nWorld");
sleep(3);
printf("Hi there!");
The output is:
Hello
(World and Hi there! appear after sleep)
This is because newline triggers a flush automatically, even if it is mid-string.
Python does not document whether a newline within the printed string causes a flush.
The current behavior is implementation-dependent (TextIOWrapper buffering), not documented.
Proposed improvement
Add a sentence to the documentation for print() or for I/O buffering clarifying:
- Newline characters inside a single print() call do not necessarily trigger a flush
- flush=True explicitly forces flushing
- Python’s stdout buffering differs from C’s line-buffered stdout behavior
- The behavior is implementation-dependent and should not be relied upon for precise output timing
Why this matters
- Helps developers writing CLI tools
- Avoids confusing differences between Python and C
- Makes buffering expectations clearer
- Educates learners about stdout behavior
Suggested wording (for docs)
In Python, printing a string containing newline characters does not cause stdout to flush automatically. The flush behavior depends on the stream’s buffering mode and flush=True explicitly forces a flush. Unlike C’s stdio line buffering, Python does not guarantee that newline characters inside a single write operation will trigger an immediate flush.
Conclusion
This is not a bug, but a documentation clarity issue.
Clarifying this behavior will prevent misunderstandings and align expectations for users familiar with C-style buffering.
Linked PRs
Metadata
Metadata
Assignees
Labels
Projects
Status