99"""Contexts for *with* statement providing temporary directories
1010"""
1111import os
12- import shutil
13- from tempfile import mkdtemp , template
12+ import tempfile
13+ from contextlib import contextmanager
1414
15+ try :
16+ from contextlib import chdir as _chdir
17+ except ImportError : # PY310
1518
16- class TemporaryDirectory :
19+ @contextmanager
20+ def _chdir (path ):
21+ cwd = os .getcwd ()
22+ os .chdir (path )
23+ yield
24+ os .chdir (cwd )
25+
26+
27+ from .deprecated import deprecate_with_version
28+
29+
30+ class TemporaryDirectory (tempfile .TemporaryDirectory ):
1731 """Create and return a temporary directory. This has the same
1832 behavior as mkdtemp but can be used as a context manager.
1933
2034 Upon exiting the context, the directory and everything contained
2135 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
3236 """
3337
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
38+ @deprecate_with_version (
39+ 'Please use the standard library tempfile.TemporaryDirectory' ,
40+ '5.0' ,
41+ '7.0' ,
42+ )
43+ def __init__ (self , suffix = '' , prefix = tempfile .template , dir = None ):
44+ """
45+ Examples
46+ --------
47+ >>> import os
48+ >>> with TemporaryDirectory() as tmpdir:
49+ ... fname = os.path.join(tmpdir, 'example_file.txt')
50+ ... with open(fname, 'wt') as fobj:
51+ ... _ = fobj.write('a string\\ n')
52+ >>> os.path.exists(tmpdir)
53+ False
54+ """
55+ return super ().__init__ (suffix , prefix , dir )
4956
5057
51- class InTemporaryDirectory (TemporaryDirectory ):
58+ @contextmanager
59+ def InTemporaryDirectory ():
5260 """Create, return, and change directory to a temporary directory
5361
5462 Notes
@@ -60,28 +68,23 @@ class InTemporaryDirectory(TemporaryDirectory):
6068 Examples
6169 --------
6270 >>> import os
71+ >>> from pathlib import Path
6372 >>> my_cwd = os.getcwd()
6473 >>> with InTemporaryDirectory() as tmpdir:
65- ... _ = open ('test.txt', 'wt').write ('some text')
74+ ... _ = Path ('test.txt').write_text ('some text')
6675 ... assert os.path.isfile('test.txt')
6776 ... assert os.path.isfile(os.path.join(tmpdir, 'test.txt'))
6877 >>> os.path.exists(tmpdir)
6978 False
7079 >>> os.getcwd() == my_cwd
7180 True
7281 """
82+ with tempfile .TemporaryDirectory () as tmpdir , _chdir (tmpdir ):
83+ yield tmpdir
7384
74- def __enter__ (self ):
75- self ._pwd = os .getcwd ()
76- os .chdir (self .name )
77- return super ().__enter__ ()
78-
79- def __exit__ (self , exc , value , tb ):
80- os .chdir (self ._pwd )
81- return super ().__exit__ (exc , value , tb )
8285
83-
84- class InGivenDirectory :
86+ @ contextmanager
87+ def InGivenDirectory ( path = None ) :
8588 """Change directory to given directory for duration of ``with`` block
8689
8790 Useful when you want to use `InTemporaryDirectory` for the final test, but
@@ -103,27 +106,15 @@ class InGivenDirectory:
103106 You can then look at the temporary file outputs to debug what is happening,
104107 fix, and finally replace ``InGivenDirectory`` with ``InTemporaryDirectory``
105108 again.
106- """
107-
108- def __init__ (self , path = None ):
109- """Initialize directory context manager
110109
111- Parameters
112- ----------
113- path : None or str, optional
114- path to change directory to, for duration of ``with`` block.
115- Defaults to ``os.getcwd()`` if None
116- """
117- if path is None :
118- path = os .getcwd ()
119- self .path = os .path .abspath (path )
120-
121- def __enter__ (self ):
122- self ._pwd = os .path .abspath (os .getcwd ())
123- if not os .path .isdir (self .path ):
124- os .mkdir (self .path )
125- os .chdir (self .path )
126- return self .path
127-
128- def __exit__ (self , exc , value , tb ):
129- os .chdir (self ._pwd )
110+ Parameters
111+ ----------
112+ path : None or str, optional
113+ path to change directory to, for duration of ``with`` block.
114+ Defaults to ``os.getcwd()`` if None
115+ """
116+ if path is None :
117+ path = os .getcwd ()
118+ os .makedirs (path , exist_ok = True )
119+ with _chdir (path ):
120+ yield os .path .abspath (path )
0 commit comments