tempfile without flush or close

Python pattern

Be cautious when using $F.name without preceding it with .flush() or .close(), as it may result in an error. This is because the file referenced by $F.name might not exist at the time of use. To prevent issues, ensure that you either call .flush() to write any buffered data to the file or close the file with .close() before referencing $F.name.


Apply with the Grit CLI
grit apply tempfile_without_flush

Warning for tempfile without .flush() or .close()

BEFORE
def main_c():
    with tempfile.NamedTemporaryFile("w") as fout:
      debug_print(astr)
      fout.write(astr)
      debug_print('wrote file')
      # tempfile-without-flush
      cmd = [binary_name, fout.name, *[str(path) for path in targets]]


def main_d():
    fout = tempfile.NamedTemporaryFile('w')
    debug_print(astr)
    fout.write(astr)

    # tempfile-without-flush
    fout.name
    cmd = [binary_name, fout.name, *[str(path) for path in targets]]


def main_e():
    fout = tempfile.NamedTemporaryFile('w')
    debug_print(astr)
    fout.write(astr)

    print(fout.name)
    # tempfile-without-flush
    cmd = [binary_name, fout.name, *[str(path) for path in targets]]
AFTER
def main_c():
    with tempfile.NamedTemporaryFile("w") as fout:
      debug_print(astr)
      fout.write(astr)
      fout.close()
      debug_print('wrote file')
      # tempfile-without-flush
      cmd = [binary_name, fout.name, *[str(path) for path in targets]]


def main_d():
    fout = tempfile.NamedTemporaryFile('w')
    debug_print(astr)
    fout.write(astr)
    fout.close()

    # tempfile-without-flush
    fout.name
    cmd = [binary_name, fout.name, *[str(path) for path in targets]]


def main_e():
    fout = tempfile.NamedTemporaryFile('w')
    debug_print(astr)
    fout.write(astr)
    fout.close()

    print(fout.name)
    # tempfile-without-flush
    cmd = [binary_name, fout.name, *[str(path) for path in targets]]

Warning for tempfile with .flush() or .close()

PYTHON
import tempfile

import at
import tf


def main():
    with tempfile.NamedTemporaryFile("w") as fout:
        debug_print(astr)
        fout.write(astr)
        # tempfile-with-flush
        fout.flush()
        cmd = [binary_name, fout.name, *[str(path) for path in targets]]


def main_b():
    with tempfile.NamedTemporaryFile("w") as fout:
        debug_print(astr)
        fout.write(astr)
        # tempfile-with-flush
        fout.close()
        cmd = [binary_name, fout.name, *[str(path) for path in targets]]


def main_f():
    fout = tempfile.NamedTemporaryFile('w', delete=False)
    debug_print(astr)
    fout.close()

    # tempfile-with-flush
    print(fout.name)