Skip to content

Commit f50354a

Browse files
Reimplement tempfile._RandomNameSequence using a generator function. (#1075)
1 parent e8a6bb4 commit f50354a

2 files changed

Lines changed: 15 additions & 25 deletions

File tree

Lib/tempfile.py

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

135135

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."""
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."""
143141

144142
characters = "abcdefghijklmnopqrstuvwxyz0123456789_"
145-
146-
@property
147-
def rng(self):
143+
rng_pid = None
144+
while True:
148145
cur_pid = _os.getpid()
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)
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)
162151

163152
def _candidate_tempdir_list():
164153
"""Generate a list of candidate temporary directories which

Lib/test/test_tempfile.py

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

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

297298
def test_same_thing(self):
298299
# _get_candidate_names always returns the same object

0 commit comments

Comments
 (0)