I was watching Miguel Grinberg’s talk on Pycon 2017 Asynchronous Python for the Complete Beginner last night. And tried a code snippet on my computer which is not really connected to the talk or async programming.

from time import sleep


def hello() -> None:
    print("Hello", end=" ")
    sleep(3)
    print("World!")


if __name__ == "__main__":
    hello()

What do you think will happen if we run the code? Terminal print’s Hello first, then after three seconds we see World! appear, right? Actually, no.

We see the code is sleeping for 3 seconds and then Hello World! appear in the terminal. This happens because Python print function is buffered. It doesn’t show anything in terminal until it find a newline (\n is the default value for end in print function) or the buffer get’s filled up or we force the function to flush (write in terminal from the buffer).

from time import sleep


def hello() -> None:
    print("Hello", end=" ", flush=True)
    sleep(3)
    print("World!")


if __name__ == "__main__":
    hello()

This code will show Hello first and World! after three seconds as expected.

But what if we don’t want to change our code? We can run the code with -u flag like python -u filename.py. We can also set an enviroment variable to bypass this. If we set PYTHONUNBUFFERED to 1 with export PYTHONUNBUFFERED=1 then we can run the code as we normally do and it’ll behave as expected.

This is just random things that I probably never use in real life, but I found it interesting and thought I’d share.