Skip to content

Commit

Permalink
encoder: Dump nested tables with their parent
Browse files Browse the repository at this point in the history
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 uiri#88
  • Loading branch information
bochecha committed Jan 6, 2020
1 parent f4f0b84 commit 1d453fa
Showing 1 changed file with 26 additions and 19 deletions.
45 changes: 26 additions & 19 deletions toml/encoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,28 +58,35 @@ 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

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)

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
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


Expand Down

0 comments on commit 1d453fa

Please sign in to comment.