Skip to content

Commit 1e62bf1

Browse files
authored
bpo-30030: Revert f50354a (tempfile) (#1187)
Revert f50354a: it introduced a regression in test_threadedtempfile.
1 parent 66bffd1 commit 1e62bf1

2 files changed

Lines changed: 25 additions & 15 deletions

File tree

Lib/tempfile.py

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -133,21 +133,32 @@ def _sanitize_params(prefix, suffix, dir):
133133
return prefix, suffix, dir, output_type
134134

135135

136-
def _RandomNameSequence():
137-
"""Generate an endless sequence of unpredictable strings which
138-
can safely be incorporated into file names. Each string is 8
139-
characters long. Multiple threads and forked processes can
140-
safely use the same instance at the same time."""
136+
class _RandomNameSequence:
137+
"""An instance of _RandomNameSequence generates an endless
138+
sequence of unpredictable strings which can safely be incorporated
139+
into file names. Each string is six characters long. Multiple
140+
threads can safely use the same instance at the same time.
141+
142+
_RandomNameSequence is an iterator."""
141143

142144
characters = "abcdefghijklmnopqrstuvwxyz0123456789_"
143-
rng_pid = None
144-
while True:
145+
146+
@property
147+
def rng(self):
145148
cur_pid = _os.getpid()
146-
if cur_pid != rng_pid:
147-
choose = _Random().choice
148-
rng_pid = cur_pid
149-
letters = [choose(characters) for dummy in range(8)]
150-
yield ''.join(letters)
149+
if cur_pid != getattr(self, '_rng_pid', None):
150+
self._rng = _Random()
151+
self._rng_pid = cur_pid
152+
return self._rng
153+
154+
def __iter__(self):
155+
return self
156+
157+
def __next__(self):
158+
c = self.characters
159+
choose = self.rng.choice
160+
letters = [choose(c) for dummy in range(8)]
161+
return ''.join(letters)
151162

152163
def _candidate_tempdir_list():
153164
"""Generate a list of candidate temporary directories which

Lib/test/test_tempfile.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
# tempfile.py unit tests.
2-
import collections.abc
32
import tempfile
43
import errno
54
import io
@@ -291,9 +290,9 @@ class TestGetCandidateNames(BaseTestCase):
291290
"""Test the internal function _get_candidate_names."""
292291

293292
def test_retval(self):
294-
# _get_candidate_names returns an iterator
293+
# _get_candidate_names returns a _RandomNameSequence object
295294
obj = tempfile._get_candidate_names()
296-
self.assertIsInstance(obj, collections.abc.Iterator)
295+
self.assertIsInstance(obj, tempfile._RandomNameSequence)
297296

298297
def test_same_thing(self):
299298
# _get_candidate_names always returns the same object

0 commit comments

Comments
 (0)