Search code examples
pythonresource-leak

Is using tempfile.mkstemp()[1] leaks open file handles?


I'm using tempfile.mkstemp()[1] in some class frequently. I'm doing some operations on the created file and then delete it.

I'm not using context manager with with or smth like that, just using the filename.

Obviously, tempfile.mkstemp() returns a tuple of opened file object and the filename. I'm only using filename and not even accessing file object, of course.

I'm wondering if that is causing leaking open file handler when execution is leaving particular method? Or is file object somehow silently closed?


Solution

  • Yes, you're leaking file handles.

    The handle is a numeric file descriptor. They're not unique and there's no way for the garbage collector to know when the reference is gone, so it can't close the file automatically.

    You could use os.fdopen() to create a Python file object that references this handle. When this is closed, the file handle will also be closed. You can use a context manager for this, or let it be closed automatically by GC.