summaryrefslogtreecommitdiff
path: root/Lib/tempfile.py
diff options
context:
space:
mode:
authorSerhiy Storchaka <storchaka@gmail.com>2017-04-11 22:45:59 +0300
committerGitHub <noreply@github.com>2017-04-11 22:45:59 +0300
commitf50354adaaafebe95ad09d09b825804a686ea843 (patch)
tree0dc403f1d0b0557927df7857c4c666235c4a3321 /Lib/tempfile.py
parente8a6bb4f3936123f3eca0b6cea05e2875a2722bc (diff)
downloadcpython-git-f50354adaaafebe95ad09d09b825804a686ea843.tar.gz
Reimplement tempfile._RandomNameSequence using a generator function. (#1075)
Diffstat (limited to 'Lib/tempfile.py')
-rw-r--r--Lib/tempfile.py35
1 files changed, 12 insertions, 23 deletions
diff --git a/Lib/tempfile.py b/Lib/tempfile.py
index 61462357c7..6112208382 100644
--- a/Lib/tempfile.py
+++ b/Lib/tempfile.py
@@ -133,32 +133,21 @@ def _sanitize_params(prefix, suffix, dir):
return prefix, suffix, dir, output_type
-class _RandomNameSequence:
- """An instance of _RandomNameSequence generates an endless
- sequence of unpredictable strings which can safely be incorporated
- into file names. Each string is six characters long. Multiple
- threads can safely use the same instance at the same time.
-
- _RandomNameSequence is an iterator."""
+def _RandomNameSequence():
+ """Generate an endless sequence of unpredictable strings which
+ can safely be incorporated into file names. Each string is 8
+ characters long. Multiple threads and forked processes can
+ safely use the same instance at the same time."""
characters = "abcdefghijklmnopqrstuvwxyz0123456789_"
-
- @property
- def rng(self):
+ rng_pid = None
+ while True:
cur_pid = _os.getpid()
- if cur_pid != getattr(self, '_rng_pid', None):
- self._rng = _Random()
- self._rng_pid = cur_pid
- return self._rng
-
- def __iter__(self):
- return self
-
- def __next__(self):
- c = self.characters
- choose = self.rng.choice
- letters = [choose(c) for dummy in range(8)]
- return ''.join(letters)
+ if cur_pid != rng_pid:
+ choose = _Random().choice
+ rng_pid = cur_pid
+ letters = [choose(characters) for dummy in range(8)]
+ yield ''.join(letters)
def _candidate_tempdir_list():
"""Generate a list of candidate temporary directories which