Skip to content

Commit bebd2cf

Browse files
[3.6] bpo-30441: Fix bug when modifying os.environ while iterating over it (GH-2409). (#2556)
(cherry picked from commit 8a8d285)
1 parent 4132adb commit bebd2cf

File tree

4 files changed

+29
-1
lines changed

4 files changed

+29
-1
lines changed

Lib/os.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -685,7 +685,9 @@ def __delitem__(self, key):
685685
raise KeyError(key) from None
686686

687687
def __iter__(self):
688-
for key in self._data:
688+
# list() from dict object is an atomic operation
689+
keys = list(self._data)
690+
for key in keys:
689691
yield self.decodekey(key)
690692

691693
def __len__(self):

Lib/test/test_os.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -836,6 +836,30 @@ def test_key_type(self):
836836
self.assertIs(cm.exception.args[0], missing)
837837
self.assertTrue(cm.exception.__suppress_context__)
838838

839+
def _test_environ_iteration(self, collection):
840+
iterator = iter(collection)
841+
new_key = "__new_key__"
842+
843+
next(iterator) # start iteration over os.environ.items
844+
845+
# add a new key in os.environ mapping
846+
os.environ[new_key] = "test_environ_iteration"
847+
848+
try:
849+
next(iterator) # force iteration over modified mapping
850+
self.assertEqual(os.environ[new_key], "test_environ_iteration")
851+
finally:
852+
del os.environ[new_key]
853+
854+
def test_iter_error_when_changing_os_environ(self):
855+
self._test_environ_iteration(os.environ)
856+
857+
def test_iter_error_when_changing_os_environ_items(self):
858+
self._test_environ_iteration(os.environ.items())
859+
860+
def test_iter_error_when_changing_os_environ_values(self):
861+
self._test_environ_iteration(os.environ.values())
862+
839863

840864
class WalkTests(unittest.TestCase):
841865
"""Tests for os.walk()."""

Misc/ACKS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1077,6 +1077,7 @@ Vilmos Nebehaj
10771077
Fredrik Nehr
10781078
Tony Nelson
10791079
Trent Nelson
1080+
Osvaldo Santana Neto
10801081
Chad Netzer
10811082
Max Neunhöffer
10821083
Anthon van der Neut
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix bug when modifying os.environ while iterating over it

0 commit comments

Comments
 (0)