Skip to content

Commit d0dc586

Browse files
committed
gh-87646: Added .path to tempfile
Added `.path` attribute to generate pathlib's `Path` objects for NamedTemporaryFile and TemporaryDirectory
1 parent 080a596 commit d0dc586

File tree

3 files changed

+19
-0
lines changed

3 files changed

+19
-0
lines changed

Lib/tempfile.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
import warnings as _warnings
4141
import io as _io
4242
import os as _os
43+
from pathlib import Path as _Path
4344
import shutil as _shutil
4445
import errno as _errno
4546
from random import Random as _Random
@@ -467,6 +468,7 @@ class _TemporaryFileWrapper:
467468
def __init__(self, file, name, delete=True, delete_on_close=True):
468469
self.file = file
469470
self.name = name
471+
self.path = _Path(name)
470472
self._closer = _TemporaryFileCloser(file, name, delete,
471473
delete_on_close)
472474

@@ -864,6 +866,7 @@ class TemporaryDirectory:
864866
def __init__(self, suffix=None, prefix=None, dir=None,
865867
ignore_cleanup_errors=False, *, delete=True):
866868
self.name = mkdtemp(suffix, prefix, dir)
869+
self.path = _Path(self.name)
867870
self._ignore_cleanup_errors = ignore_cleanup_errors
868871
self._delete = delete
869872
self._finalizer = _weakref.finalize(

Lib/test/test_tempfile.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1147,6 +1147,12 @@ def test_unexpected_error(self):
11471147
mock_open().close.assert_called()
11481148
self.assertEqual(os.listdir(dir), [])
11491149

1150+
def test_path_method(self):
1151+
d = self.do_create()
1152+
path = d.path
1153+
self.assertTrue(issubclass(type(path), pathlib.Path), "unexpected return type")
1154+
self.assertEqual(str(path), d.name, ".path .name mismatch")
1155+
11501156
# How to test the mode and bufsize parameters?
11511157

11521158
class TestSpooledTemporaryFile(BaseTestCase):
@@ -1853,5 +1859,12 @@ def test_delete_false(self):
18531859
self.assertTrue(os.path.exists(working_dir))
18541860
shutil.rmtree(working_dir)
18551861

1862+
def test_path_method(self):
1863+
d = self.do_create()
1864+
path = d.path
1865+
self.assertTrue(issubclass(type(path), pathlib.Path), "unexpected return type")
1866+
self.assertEqual(str(path), d.name, ".path .name mismatch")
1867+
1868+
18561869
if __name__ == "__main__":
18571870
unittest.main()
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
`tempfile.NamedTemporaryFile` and `tempfile.TemporaryDirectory` includes a
2+
new ``.path`` attribute that provides the temporary file name as a
3+
`pathlib.Path` object

0 commit comments

Comments
 (0)