Skip to content

TemporaryFile gets closed somehow after text I/O but only when passed through function #130965

@kbolino

Description

@kbolino

Bug report

Bug description:

Issue

I cannot explain this difference in behavior. I have reduced this code to what I believe are the minimal elements necessary to demonstrate the issue. Notably, this is not reproducible without using TextIOWrapper, but that gets me no closer to an explanation.

First, no function call:

import io
import tempfile

with tempfile.TemporaryFile() as out_file:   
    out_writer = io.TextIOWrapper(out_file)
    out_writer.write("hello,world")
    out_writer.flush()
    out_file.seek(0)
    print(out_file.read())

Result:

b'hello,world'

Next, a function call is introduced, but otherwise the program should behave identically:

import io
import tempfile

def handle_file(out_file):
    out_writer = io.TextIOWrapper(out_file)
    out_writer.write("hello,world")
    out_writer.flush()

with tempfile.TemporaryFile() as out_file:
    handle_file(out_file)
    out_file.seek(0)
    print(out_file.read())

Result:

Traceback (most recent call last):
  File "/Users/.../tempfile_close_test.py", line 11, in <module>
    out_file.seek(0)
ValueError: seek of closed file

Yet, the file was not closed anywhere, and the code is functionally identical.

Environment

Tested with macOS Sequoia 15.3.1 (Darwin 24.3.0) on Apple Silicon (M4 MacBook Pro)

Reproduced with all of these Python versions:

  • 3.9.6 (system interpreter at /usr/bin/python3)
  • 3.10.16 (from homebrew)
  • 3.12.9 (from homebrew)
  • 3.13.2 (from homebrew)

CPython versions tested on:

3.13

Operating systems tested on:

macOS

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions