Skip to content

Commit

Permalink
[3.5] bpo-30441: Fix bug when modifying os.environ while iterating ov…
Browse files Browse the repository at this point in the history
…er it (GH-2409). (#2557)

(cherry picked from commit 8a8d285)
  • Loading branch information
serhiy-storchaka authored Jul 4, 2017
1 parent 0b12107 commit 1a3bc55
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 1 deletion.
4 changes: 3 additions & 1 deletion Lib/os.py
Original file line number Diff line number Diff line change
Expand Up @@ -741,7 +741,9 @@ def __delitem__(self, key):
raise KeyError(key) from None

def __iter__(self):
for key in self._data:
# list() from dict object is an atomic operation
keys = list(self._data)
for key in keys:
yield self.decodekey(key)

def __len__(self):
Expand Down
24 changes: 24 additions & 0 deletions Lib/test/test_os.py
Original file line number Diff line number Diff line change
Expand Up @@ -809,6 +809,30 @@ def test_key_type(self):
self.assertIs(cm.exception.args[0], missing)
self.assertTrue(cm.exception.__suppress_context__)

def _test_environ_iteration(self, collection):
iterator = iter(collection)
new_key = "__new_key__"

next(iterator) # start iteration over os.environ.items

# add a new key in os.environ mapping
os.environ[new_key] = "test_environ_iteration"

try:
next(iterator) # force iteration over modified mapping
self.assertEqual(os.environ[new_key], "test_environ_iteration")
finally:
del os.environ[new_key]

def test_iter_error_when_changing_os_environ(self):
self._test_environ_iteration(os.environ)

def test_iter_error_when_changing_os_environ_items(self):
self._test_environ_iteration(os.environ.items())

def test_iter_error_when_changing_os_environ_values(self):
self._test_environ_iteration(os.environ.values())


class WalkTests(unittest.TestCase):
"""Tests for os.walk()."""
Expand Down
1 change: 1 addition & 0 deletions Misc/ACKS
Original file line number Diff line number Diff line change
Expand Up @@ -1056,6 +1056,7 @@ Vilmos Nebehaj
Fredrik Nehr
Tony Nelson
Trent Nelson
Osvaldo Santana Neto
Chad Netzer
Max Neunhöffer
Anthon van der Neut
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix bug when modifying os.environ while iterating over it

0 comments on commit 1a3bc55

Please sign in to comment.