bpo-42160: tempfile: Reduce overhead of pid check. (GH-22997)

The _RandomSequence class in tempfile used to check the current pid every time its rng property was used.
This commit replaces this code with `os.register_at_fork` to reduce the overhead.
This commit is contained in:
Eric W 2020-10-30 05:56:28 +01:00 committed by GitHub
parent 9129af6050
commit 8e409cebad
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 13 additions and 14 deletions

View File

@ -129,24 +129,22 @@ class _RandomNameSequence:
_RandomNameSequence is an iterator."""
characters = "abcdefghijklmnopqrstuvwxyz0123456789_"
@property
def rng(self):
cur_pid = _os.getpid()
if cur_pid != getattr(self, '_rng_pid', None):
self._rng = _Random()
self._rng_pid = cur_pid
return self._rng
def __init__(self, characters="abcdefghijklmnopqrstuvwxyz0123456789_", length=8, rng=None):
if rng is None:
rng = _Random()
if hasattr(_os, "fork"):
# prevent same state after fork
_os.register_at_fork(after_in_child=rng.seed)
self.rng = rng
self.characters = characters
self.length = length
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)
return ''.join(self.rng.choices(c, k=self.length))
def _candidate_tempdir_list():
"""Generate a list of candidate temporary directories which

View File

@ -153,8 +153,8 @@ class TestRandomNameSequence(BaseTestCase):
self.r = tempfile._RandomNameSequence()
super().setUp()
def test_get_six_char_str(self):
# _RandomNameSequence returns a six-character string
def test_get_eight_char_str(self):
# _RandomNameSequence returns a eight-character string
s = next(self.r)
self.nameCheck(s, '', '', '')

View File

@ -0,0 +1 @@
Replaced pid check in ``tempfile._RandomNameSequence`` with ``os.register_at_fork`` to reduce overhead.