[New-bugs-announce] [issue45833] NamedTemporaryFile deleted before enclosing context manager exit

Brian McCutchon report at bugs.python.org
Wed Nov 17 16:22:11 EST 2021


New submission from Brian McCutchon <bmccutchon at google.com>:

Consider the following code:

# Copyright 2021 Google LLC.
# SPDX-License-Identifier: Apache-2.0
import contextlib
import os

@contextlib.contextmanager
def my_tmp_file():
  with tempfile.NamedTemporaryFile('w') as f:
    yield f

os.stat(my_tmp_file().__enter__().name)  # File not found
os.stat(contextlib.ExitStack().enter_context(my_tmp_file()).name)  # Same

I would expect the file to still exist, as __exit__ has not been called and I can't see why the file would have been closed. Also, it performs as expected when using NamedTemporaryFile directly, but not when it is nested in another context manager. It also performs as expected when my_tmp_file() or contextlib.ExitStack() is used in a "with" statement.

----------
components: Library (Lib)
messages: 406494
nosy: Brian McCutchon
priority: normal
severity: normal
status: open
title: NamedTemporaryFile deleted before enclosing context manager exit
type: behavior
versions: Python 3.9

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue45833>
_______________________________________


More information about the New-bugs-announce mailing list