# HG changeset patch # User pslacerda # Date 1465678545 10800 # Sat Jun 11 17:55:45 2016 -0300 # Node ID c9e5e7a1be1d64032792e0923c8339fb043f5eb4 # Parent 77604a2f019b1412aa6cea2ad1a493afc6781536 Add support to sectionless files in configparser diff -r 77604a2f019b -r c9e5e7a1be1d Lib/configparser.py --- a/Lib/configparser.py Sat Jun 11 04:36:34 2016 -0400 +++ b/Lib/configparser.py Sat Jun 11 17:55:45 2016 -0300 @@ -917,7 +917,8 @@ def _write_section(self, fp, section_name, section_items, delimiter): """Write a single section to the specified `fp'.""" - fp.write("[{}]\n".format(section_name)) + if section_name: + fp.write("[{}]\n".format(section_name)) for key, value in section_items: value = self._interpolation.before_write(self, section_name, key, value) @@ -1006,7 +1007,6 @@ cursect = None # None, or a dictionary sectname = None optname = None - lineno = 0 indent_level = 0 e = None # None, or an exception for lineno, line in enumerate(fp, start=1): @@ -1073,10 +1073,12 @@ # So sections can't start with a continuation line optname = None # no section header in the file? - elif cursect is None: + elif cursect is None and self.default_section is not None: raise MissingSectionHeaderError(fpname, lineno, line) # an option line? else: + if cursect is None: + cursect = self._defaults mo = self._optcre.match(value) if mo: optname, vi, optval = mo.group('option', 'vi', 'value') diff -r 77604a2f019b -r c9e5e7a1be1d Lib/test/test_configparser.py --- a/Lib/test/test_configparser.py Sat Jun 11 04:36:34 2016 -0400 +++ b/Lib/test/test_configparser.py Sat Jun 11 17:55:45 2016 -0300 @@ -1084,6 +1084,28 @@ self.assertEqual(cf.get("global", "hosts allow"), "127.") self.assertEqual(cf.get("tmp", "echo command"), "cat %s; rm %s") + +class RawConfigParserTestUnnamedSection(CfgParserTestCaseClass, + unittest.TestCase): + config_class = configparser.RawConfigParser + default_section = None + + def test_unnamed(self): + filename = support.findfile('cfgparser.4') + cf = self.fromstring(textwrap.dedent(""" + PRETTY_NAME = sectionless configparser + FILE_NAME = Lib/configparser.py + """)) + cf.write(open(filename, 'w')) + + cf = self.newconfig() + cf.read(filename) + + eq = self.assertEqual + eq(cf.get(None, 'PRETTY_NAME'), 'sectionless configparser') + eq(cf.get(None, 'FILE_NAME'), 'Lib/configparser.py') + + class ConfigParserTestCaseExtendedInterpolation(BasicTestCase, unittest.TestCase): config_class = configparser.ConfigParser interpolation = configparser.ExtendedInterpolation()