#๐Ÿ”’ `ast.unparse` keeps adding unwanted line breaks to any new nodes from my `NodeTransformer`

17 messages ยท Page 1 of 1 (latest)

halcyon gulch
#

I've tried:

  • ast.fix_missing_locations
  • ast.copy_location

and I have verified in my debugger that the location fields are identical to that of the node I am replacing.

Is there something I am missing?

tribal oliveBOT
#

@halcyon gulch

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

oblique slate
#

are you saying unparse returns syntactically incorrect code, or code that does something other than the ast tree would suggest?

halcyon gulch
#

I was transforming a Constant into an Expr. This seems like some possibly erroneous logic inside of python's internal _Unparser class.

#

I managed to work around it by adding .value to the Expr node and then copied the original node's location, and then returned it.

pine fractal
#

Can we see some example?

oblique slate
#

do you have sample code that demonstrates the problem? i'm interested in this, even if you already have a workaround

halcyon gulch
#

@velvet bloom Do you have the example that you used to reproduce this?

velvet bloom
#

!e

import ast
class Foo(ast.NodeTransformer):
    def visit_Constant(self, node):
        return ast.parse('1').body[0]
f = Foo()
g = f.visit(ast.parse('a=1\nb=2'))
print(ast.unparse(g))
print(ast.dump(g, indent=2))
tribal oliveBOT
velvet bloom
#

i don't think it's an error in python's unparser, or at least it's just unparse accepting something that isn't valid; Assign shouldn't have an Expr as a value to begin with

#

!e

import ast
print(ast.dump(ast.parse('a=1'), indent=2))
tribal oliveBOT
velvet bloom
#

also fwiw instead of ast.parse(...).body[0].value you should probably just do ast.parse(..., mode='eval').value

tribal oliveBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.