Skip to content

Commit 63b5586

Browse files
committed
RF: Deprecate tmpdirs.TemporaryDirectory, duplicate of tempfile.TemporaryDirectory
Move examples into __init__ to suppress warnings during doctests
1 parent 9000943 commit 63b5586

File tree

1 file changed

+25
-30
lines changed

1 file changed

+25
-30
lines changed

nibabel/tmpdirs.py

Lines changed: 25 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -9,46 +9,40 @@
99
"""Contexts for *with* statement providing temporary directories
1010
"""
1111
import os
12-
import shutil
13-
from tempfile import mkdtemp, template
12+
import tempfile
1413

14+
from .deprecated import deprecate_with_version
1515

16-
class TemporaryDirectory:
16+
17+
class TemporaryDirectory(tempfile.TemporaryDirectory):
1718
"""Create and return a temporary directory. This has the same
1819
behavior as mkdtemp but can be used as a context manager.
1920
2021
Upon exiting the context, the directory and everything contained
2122
in it are removed.
22-
23-
Examples
24-
--------
25-
>>> import os
26-
>>> with TemporaryDirectory() as tmpdir:
27-
... fname = os.path.join(tmpdir, 'example_file.txt')
28-
... with open(fname, 'wt') as fobj:
29-
... _ = fobj.write('a string\\n')
30-
>>> os.path.exists(tmpdir)
31-
False
3223
"""
3324

34-
def __init__(self, suffix='', prefix=template, dir=None):
35-
self.name = mkdtemp(suffix, prefix, dir)
36-
self._closed = False
37-
38-
def __enter__(self):
39-
return self.name
40-
41-
def cleanup(self):
42-
if not self._closed:
43-
shutil.rmtree(self.name)
44-
self._closed = True
45-
46-
def __exit__(self, exc, value, tb):
47-
self.cleanup()
48-
return False
25+
@deprecate_with_version(
26+
'Please use the standard library tempfile.TemporaryDirectory',
27+
'5.0',
28+
'7.0',
29+
)
30+
def __init__(self, suffix='', prefix=tempfile.template, dir=None):
31+
"""
32+
Examples
33+
--------
34+
>>> import os
35+
>>> with TemporaryDirectory() as tmpdir:
36+
... fname = os.path.join(tmpdir, 'example_file.txt')
37+
... with open(fname, 'wt') as fobj:
38+
... _ = fobj.write('a string\\n')
39+
>>> os.path.exists(tmpdir)
40+
False
41+
"""
42+
return super().__init__(suffix, prefix, dir)
4943

5044

51-
class InTemporaryDirectory(TemporaryDirectory):
45+
class InTemporaryDirectory(tempfile.TemporaryDirectory):
5246
"""Create, return, and change directory to a temporary directory
5347
5448
Notes
@@ -60,9 +54,10 @@ class InTemporaryDirectory(TemporaryDirectory):
6054
Examples
6155
--------
6256
>>> import os
57+
>>> from pathlib import Path
6358
>>> my_cwd = os.getcwd()
6459
>>> with InTemporaryDirectory() as tmpdir:
65-
... _ = open('test.txt', 'wt').write('some text')
60+
... _ = Path('test.txt').write_text('some text')
6661
... assert os.path.isfile('test.txt')
6762
... assert os.path.isfile(os.path.join(tmpdir, 'test.txt'))
6863
>>> os.path.exists(tmpdir)

0 commit comments

Comments
 (0)