def _write_constant(self, value):
if isinstance(value, (float, complex)):
- # Substitute overflowing decimal literal for AST infinities.
- self.write(repr(value).replace("inf", _INFSTR))
+ # Substitute overflowing decimal literal for AST infinities,
+ # and inf - inf for NaNs.
+ self.write(
+ repr(value)
+ .replace("inf", _INFSTR)
+ .replace("nan", f"({_INFSTR}-{_INFSTR})")
+ )
elif self._avoid_backslashes and isinstance(value, str):
self._write_str_avoiding_backslashes(value)
else:
self.traverse(node.orelse)
def visit_Set(self, node):
- if not node.elts:
- raise ValueError("Set node should have at least one item")
- with self.delimit("{", "}"):
- self.interleave(lambda: self.write(", "), self.traverse, node.elts)
+ if node.elts:
+ with self.delimit("{", "}"):
+ self.interleave(lambda: self.write(", "), self.traverse, node.elts)
+ else:
+ # `{}` would be interpreted as a dictionary literal, and
+ # `set` might be shadowed. Thus:
+ self.write('{*()}')
def visit_Dict(self, node):
def write_key_value_pair(k, v):
self.check_ast_roundtrip("1e1000j")
self.check_ast_roundtrip("-1e1000j")
+ def test_nan(self):
+ self.assertASTEqual(
+ ast.parse(ast.unparse(ast.Constant(value=float('nan')))),
+ ast.parse('1e1000 - 1e1000')
+ )
+
def test_min_int(self):
self.check_ast_roundtrip(str(-(2 ** 31)))
self.check_ast_roundtrip(str(-(2 ** 63)))
def test_set_literal(self):
self.check_ast_roundtrip("{'a', 'b', 'c'}")
+ def test_empty_set(self):
+ self.assertASTEqual(
+ ast.parse(ast.unparse(ast.Set(elts=[]))),
+ ast.parse('{*()}')
+ )
+
def test_set_comprehension(self):
self.check_ast_roundtrip("{x for x in range(5)}")
def test_invalid_fstring_backslash(self):
self.check_invalid(ast.FormattedValue(value=ast.Constant(value="\\\\")))
- def test_invalid_set(self):
- self.check_invalid(ast.Set(elts=[]))
-
def test_invalid_yield_from(self):
self.check_invalid(ast.YieldFrom(value=None))