import sys

def ensure(test_function, do_function, comment = "", maxtries =3):
    """
    does someting and ensure that it is done.
    @param test_function is a function () => bool which must be successful
    @param do_function is a function () => None which has wanted side-effects
    @param comment a string to prepend, for warnings. Empty by default
    @param maxtries the maximum number of tries before an error is raised.
           default value: 3
    """
    for i in range(maxtries):
        do_function()
        if test_function():
            return
        sys.stdout.write(f"{comment} failed #{i}\n")
        sys.stdout.flush()
    raise Exception(f"{comment} failed after {maxtries} tries\n")

