Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Application that prints to STDOUT and STDERR

A very simple function that print to the screen. How can we test this?

An even wors situation is when a function both does some (computational) work and prints to the screen, something not ideal from a design point of view. However even if the sole job of a function is to print to the screen, we still need a way to test it.

import sys

def welcome(to_out, to_err=None):
    print(f"STDOUT: {to_out}")
    if to_err:
        print(f"STDERR: {to_err}", file=sys.stderr)

We can write a separate program that uses this function and “eyeball” the result, but we can do better.

from greet import welcome

welcome("Jane", "Joe")
print('---')
welcome("Becky")

Output:

STDERR: Joe
STDOUT: Jane
---
STDOUT: Becky