From 6862d8d352cce2e693181509f6308c4db189b6c7 Mon Sep 17 00:00:00 2001 From: Mathieu Bridon Date: Mon, 6 Jan 2020 14:34:53 +0100 Subject: [PATCH] encoder: Dump nested tables with their parent MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Currently, we first print all tables at the top level, then all nested tables at the second level, etc… As a result, this: { 'table1': { 'foo': 1, 'nested': { 'bar': 2, }, }, 'table2': { 'baz': 3, }, } … gets printed as: [table1] foo = 1 [table2] baz = 3 [table1.nested] bar = 2 With this commit, we print the nested tables with their parent, so the same example from above will instead become: [table1] foo = 1 [table1.nested] bar = 2 [table2] baz = 3 Fixes #88 --- toml/encoder.py | 45 +++++++++++++++++++++++++-------------------- 1 file changed, 25 insertions(+), 20 deletions(-) diff --git a/toml/encoder.py b/toml/encoder.py index d9e557e..db7c918 100644 --- a/toml/encoder.py +++ b/toml/encoder.py @@ -58,28 +58,33 @@ def dumps(o, encoder=None): if encoder is None: encoder = TomlEncoder(o.__class__) addtoretval, sections = encoder.dump_sections(o, "") + sections = list(sections.items()) retval += addtoretval outer_objs = [id(o)] - while sections: - section_ids = [id(section) for section in sections] - for outer_obj in outer_objs: - if outer_obj in section_ids: - raise ValueError("Circular reference detected") - outer_objs += section_ids - newsections = encoder.get_empty_table() - for section in sections: - addtoretval, addtosections = encoder.dump_sections( - sections[section], section) - - if addtoretval or (not addtoretval and not addtosections): - if retval and retval[-2:] != "\n\n": - retval += "\n" - retval += "[" + section + "]\n" - if addtoretval: - retval += addtoretval - for s in addtosections: - newsections[section + "." + s] = addtosections[s] - sections = newsections + + while True: + try: + section, values = sections.pop(0) + except IndexError: + return retval + + section_id = id(section) + if section_id in outer_objs: + raise ValueError("Circular reference detected") + + outer_objs.append(section_id) + + addtoretval, addtosections = encoder.dump_sections(values, section) + if addtoretval or (not addtoretval and not addtosections): + if retval and retval[-2:] != "\n\n": + retval += "\n" + retval += "[" + section + "]\n" + if addtoretval: + retval += addtoretval + + for s in addtosections: + sections.insert(0, (section + "." + s, addtosections[s])) + return retval