Skip to content

bpo-30441: Fix bug when modifying os.environ while iterating over it #2409

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jul 1, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion Lib/os.py
Original file line number Diff line number Diff line change
Expand Up @@ -697,7 +697,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 @@ -835,6 +835,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 @@ -1087,6 +1087,7 @@ Fredrik Nehr
Tony Nelson
Trent Nelson
Andrew Nester
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