Kaydet (Commit) 15ddc4d4 authored tarafından Zack M. Davis's avatar Zack M. Davis

non-hideous dictionary displays

The trailing comma-space that was previously output, while perfectly
legal in every way, is not what most human Python programmers would
write in most situations. We use the same slick idiom as the
`comma_list` method (iterating over the enumeration, but writing the
comma-space before the elements if the index is truthy, which zero is
not) to not put anything extra after the final key-value pair.
üst 250b3b3a
...@@ -407,8 +407,10 @@ class SourceGenerator(ExplicitNodeVisitor): ...@@ -407,8 +407,10 @@ class SourceGenerator(ExplicitNodeVisitor):
@enclose('{}') @enclose('{}')
def visit_Dict(self, node): def visit_Dict(self, node):
for key, value in zip(node.keys, node.values): for idx, (key, value) in enumerate(zip(node.keys, node.values)):
self.write(key, ': ', value, ', ') if idx:
self.write(', ')
self.write(key, ': ', value)
@enclose('()') @enclose('()')
def visit_BinOp(self, node): def visit_BinOp(self, node):
......
...@@ -31,6 +31,12 @@ class CodegenTestCase(unittest.TestCase): ...@@ -31,6 +31,12 @@ class CodegenTestCase(unittest.TestCase):
source = "from math import floor" source = "from math import floor"
self.assertAstSourceEqual(source) self.assertAstSourceEqual(source)
def test_dictionary_literals(self):
source = "{'a': 1, 'b': 2}"
self.assertAstSourceEqual(source)
another_source = "{'nested': ['structures', {'are': 'important'}]}"
self.assertAstSourceEqual(another_source)
def test_try_expect(self): def test_try_expect(self):
source = textwrap.dedent("""\ source = textwrap.dedent("""\
try: try:
...@@ -80,10 +86,8 @@ class CodegenTestCase(unittest.TestCase): ...@@ -80,10 +86,8 @@ class CodegenTestCase(unittest.TestCase):
self.assertRaises(SyntaxError, ast.parse, source) self.assertRaises(SyntaxError, ast.parse, source)
def test_multiple_unpackings(self): def test_multiple_unpackings(self):
# XXX TODO: no human Pythonista would write the contents of a
# dictionary literal with a trailing comma-space like that
source = textwrap.dedent("""\ source = textwrap.dedent("""\
my_function(*[1], *[2], **{'three': 3, }, **{'four': 'four', })""") my_function(*[1], *[2], **{'three': 3}, **{'four': 'four'})""")
if sys.version_info >= (3, 5): if sys.version_info >= (3, 5):
self.assertAstSourceEqual(source) self.assertAstSourceEqual(source)
else: else:
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment