@contextmanager<EOL>def ensure_clean(filename=None, return_filelike=False):
filename = filename or '<STR_LIT>'<EOL>fd = None<EOL>if return_filelike:<EOL><INDENT>f = tempfile.TemporaryFile(suffix=filename)<EOL>try:<EOL><INDENT>yield f<EOL><DEDENT>finally:<EOL><INDENT>f.close()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if len(os.path.dirname(filename)):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>try:<EOL><INDENT>fd, filename = tempfile.mkstemp(suffix=filename)<EOL><DEDENT>except UnicodeEncodeError:<EOL><INDENT>import pytest<EOL>pytest.skip('<STR_LIT>')<EOL><DEDENT>try:<EOL><INDENT>yield filename<EOL><DEDENT>finally:<EOL><INDENT>try:<EOL><INDENT>os.close(fd)<EOL><DEDENT>except Exception:<EOL><INDENT>print("<STR_LIT>"<EOL>.format(fdesc=fd, fname=filename))<EOL><DEDENT>try:<EOL><INDENT>if os.path.exists(filename):<EOL><INDENT>os.remove(filename)<EOL><DEDENT><DEDENT>except Exception as e:<EOL><INDENT>print("<STR_LIT>".format(error=e))<EOL><DEDENT><DEDENT><DEDENT>
Gets a temporary path and agrees to remove on close.

    Parameters
    ----------
    filename : str (optional)
        if None, creates a temporary file which is then removed when out of
        scope. if passed, creates temporary file with filename as ending.
    return_filelike : bool (default False)
        if True, returns a file-like which is *always* cleaned. Necessary for
        savefig and other functions which want to append extensions.