
08.04.21 23:31, Ethan Furman пише:
In issue14243 [1] there are two issues being tracked:
- the difference in opening shared files between posix and Windows - the behavior of closing the underlying file in the middle of NamedTemporaryFile's context management
I'd like to address and get feedback on the context management issue.
```python from tempfile import NamedTemporaryFile
with NamedTemporaryFile() as fp: fp.write(b'some data') fp = open(fp.name()) data = fp.read()
assert data == 'some_data' ```
These issues are usually solved by using TemporaryDirectory: with TemporaryDirectory() as td: filename = os.path.join(td, 'tempfile') with open(filename, 'wb') as fp: fp.write(b'some data') with open(filename, 'rb') as fp: data = fp.read() What if make NamedTemporaryFile a wrapper around TemporaryDirectory and always create a new temporary directory for file? @contextmanager def NamedTemporaryFile(): with TemporaryDirectory() as td: filename = os.path.join(td, 'tempfile') with open(filename, 'wb') as fp: yield fp