#๐ `ast.unparse` keeps adding unwanted line breaks to any new nodes from my `NodeTransformer`
17 messages ยท Page 1 of 1 (latest)
@halcyon gulch
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.
are you saying unparse returns syntactically incorrect code, or code that does something other than the ast tree would suggest?
Well, in this case, it was syntactically incorrect.
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.
Can we see some example?
do you have sample code that demonstrates the problem? i'm interested in this, even if you already have a workaround
@velvet bloom Do you have the example that you used to reproduce this?
!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))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | a =
002 | 1
003 | b =
004 | 1
005 | Module(
006 | body=[
007 | Assign(
008 | targets=[
009 | Name(id='a', ctx=Store())],
010 | value=Expr(
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/NYYDKIDH7YATYKZ6IR45ZZ2MME
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))
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | Module(
002 | body=[
003 | Assign(
004 | targets=[
005 | Name(id='a', ctx=Store())],
006 | value=Constant(value=1))],
007 | type_ignores=[])
also fwiw instead of ast.parse(...).body[0].value you should probably just do ast.parse(..., mode='eval').value
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.