[Python-checkins] cpython (3.2): configparser: preserve section order when using `__setitem__` (issue #16820)

lukasz.langa python-checkins at python.org
Tue Jan 1 23:51:24 CET 2013


http://hg.python.org/cpython/rev/6f0cee62f0c6
changeset:   81210:6f0cee62f0c6
branch:      3.2
parent:      81207:479fca0adbf6
user:        Łukasz Langa <lukasz at langa.pl>
date:        Tue Jan 01 23:45:33 2013 +0100
summary:
  configparser: preserve section order when using `__setitem__` (issue #16820)

files:
  Lib/configparser.py        |   3 ++-
  Lib/test/test_cfgparser.py |  26 ++++++++++++++++++++++++++
  2 files changed, 28 insertions(+), 1 deletions(-)


diff --git a/Lib/configparser.py b/Lib/configparser.py
--- a/Lib/configparser.py
+++ b/Lib/configparser.py
@@ -959,7 +959,8 @@
 
         # XXX this is not atomic if read_dict fails at any point. Then again,
         # no update method in configparser is atomic in this implementation.
-        self.remove_section(key)
+        if key in self._sections:
+            self._sections[key].clear()
         self.read_dict({key: value})
 
     def __delitem__(self, key):
diff --git a/Lib/test/test_cfgparser.py b/Lib/test/test_cfgparser.py
--- a/Lib/test/test_cfgparser.py
+++ b/Lib/test/test_cfgparser.py
@@ -797,6 +797,32 @@
         self.assertEqual(set(cf.sections()), set())
         self.assertEqual(set(cf[self.default_section].keys()), {'foo'})
 
+    def test_setitem(self):
+        cf = self.fromstring("""
+            [section1]
+            name1 {0[0]} value1
+            [section2]
+            name2 {0[0]} value2
+            [section3]
+            name3 {0[0]} value3
+        """.format(self.delimiters), defaults={"nameD": "valueD"})
+        self.assertEqual(set(cf['section1'].keys()), {'name1', 'named'})
+        self.assertEqual(set(cf['section2'].keys()), {'name2', 'named'})
+        self.assertEqual(set(cf['section3'].keys()), {'name3', 'named'})
+        self.assertEqual(cf['section1']['name1'], 'value1')
+        self.assertEqual(cf['section2']['name2'], 'value2')
+        self.assertEqual(cf['section3']['name3'], 'value3')
+        self.assertEqual(cf.sections(), ['section1', 'section2', 'section3'])
+        cf['section2'] = {'name22': 'value22'}
+        self.assertEqual(set(cf['section2'].keys()), {'name22', 'named'})
+        self.assertEqual(cf['section2']['name22'], 'value22')
+        self.assertNotIn('name2', cf['section2'])
+        self.assertEqual(cf.sections(), ['section1', 'section2', 'section3'])
+        cf['section3'] = {}
+        self.assertEqual(set(cf['section3'].keys()), {'named'})
+        self.assertNotIn('name3', cf['section3'])
+        self.assertEqual(cf.sections(), ['section1', 'section2', 'section3'])
+
 
 class StrictTestCase(BasicTestCase):
     config_class = configparser.RawConfigParser

-- 
Repository URL: http://hg.python.org/cpython


More information about the Python-checkins mailing list