Returns a context object wrapping either the given file or
    stderr (if filename is None).  This makes dealing with log files
    more convenient.

def file_or_stderr(filename, *, mode="a", encoding="utf-8"):
    """Returns a context object wrapping either the given file or
    stderr (if filename is None).  This makes dealing with log files
    more convenient.
    """
    if filename is not None:
        return open(filename, mode, encoding=encoding)

    @contextmanager
    def stderr_wrapper():
        yield sys.stderr

    return stderr_wrapper()