how to compile ast node in 'eval' mode

  • Last Update :
  • Techknowledgy :

Change:

expr = ast.Expression(body = [tree])

to:

expr = ast.Expression(body = tree)

Suggestion : 2

Your last attempt is close, but the body anycodings_abstract-syntax-tree of ast.Expression should be a single anycodings_abstract-syntax-tree expression, not a list of expressions.,TypeError: expected Expression node, got anycodings_abstract-syntax-tree BinOp,TypeError: expected Expression node, got anycodings_abstract-syntax-tree Expr,TypeError: required field "lineno" missing anycodings_abstract-syntax-tree from expr

I want to create a code object that I would anycodings_abstract-syntax-tree be able to reuse with eval later on. I need anycodings_abstract-syntax-tree to do this based on some ast nodes I have anycodings_abstract-syntax-tree programmatically generated, therefore I anycodings_abstract-syntax-tree can't have code as a string passed to anycodings_abstract-syntax-tree compile function. How to construct a valid anycodings_abstract-syntax-tree ast node for compile? Below are couple of anycodings_abstract-syntax-tree things I have tried:

tree = ast.parse("2+2")
exe = compile(tree.body[0], filename = "", mode = "eval")

TypeError: expected Expression node, got anycodings_abstract-syntax-tree Expr

tree = ast.BinOp(left = ast.Num(n = 2), right = ast.Num(n = 2), op = ast.Add())
exe = compile(tree, filename = "", mode = "eval")

TypeError: expected Expression node, got anycodings_abstract-syntax-tree BinOp

tree = ast.BinOp(left = ast.Num(n = 2), right = ast.Num(n = 2), op = ast.Add())
expr = ast.Expression(body = [tree])
ast.fix_missing_locations(expr)
exe = compile(expr, filename = "", mode = "eval")

Change:

expr = ast.Expression(body = [tree])

to:

expr = ast.Expression(body = tree)

Suggestion : 3

An abstract syntax tree can be generated by passing ast.PyCF_ONLY_AST as a flag to the compile() built-in function, or using the parse() helper provided in this module. The result will be a tree of objects whose classes all inherit from ast.AST. An abstract syntax tree can be compiled into a Python code object using the built-in compile() function.,Apart from the node classes, the ast module defines these utility functions and classes for traversing abstract syntax trees:,Generates and returns an abstract syntax tree instead of returning a compiled code object.,The produced code string will not necessarily be equal to the original code that generated the ast.AST object (without any compiler optimizations, such as constant tuples/frozensets).

node = ast.UnaryOp()
node.op = ast.USub()
node.operand = ast.Constant()
node.operand.value = 5
node.operand.lineno = 0
node.operand.col_offset = 0
node.lineno = 0
node.col_offset = 0
node = ast.UnaryOp(ast.USub(), ast.Constant(5, lineno = 0, col_offset = 0),
   lineno = 0, col_offset = 0)
>>> print(ast.dump(ast.parse('123', mode = 'eval'), indent = 4))
Expression(
   body = Constant(value = 123))
>>> print(ast.dump(ast.parse('f"sin({a}) is {sin(a):.3}"', mode = 'eval'), indent = 4))
Expression(
   body = JoinedStr(
      values = [
         Constant(value = 'sin('),
         FormattedValue(
            value = Name(id = 'a', ctx = Load()),
            conversion = -1),
         Constant(value = ') is '),
         FormattedValue(
            value = Call(
               func = Name(id = 'sin', ctx = Load()),
               args = [
                  Name(id = 'a', ctx = Load())
               ],
               keywords = []),
            conversion = -1,
            format_spec = JoinedStr(
               values = [
                  Constant(value = '.3')
               ]))
      ]))
>>> print(ast.dump(ast.parse('[1, 2, 3]', mode = 'eval'), indent = 4))
Expression(
      body = List(
         elts = [
            Constant(value = 1),
            Constant(value = 2),
            Constant(value = 3)
         ],
         ctx = Load())) >>>
   print(ast.dump(ast.parse('(1, 2, 3)', mode = 'eval'), indent = 4))
Expression(
   body = Tuple(
      elts = [
         Constant(value = 1),
         Constant(value = 2),
         Constant(value = 3)
      ],
      ctx = Load()))

Suggestion : 4

To compile an AST, every node must have lineno and col_offset attributes. Nodes produced by parsing regular code already have these, but nodes you create programmatically don’t. There are a few helper functions for this:,ast.copy_location() copies lineno and col_offset from one node to another. Useful when you’re replacing a node.,Python code can be compiled in three modes. The root of the AST depends on the mode parameter you pass to ast.parse(), and it must correspond to the mode parameter when you call compile().,Meta also tries to decompile Python bytecode to an AST, but it appears to be unmaintained.

>>> tree = ast.parse("print('hello world')")
>>> tree
<_ast.Module object at 0x9e3df6c>
   >>> exec(compile(tree, filename="<ast>", mode="exec"))
      hello world

Suggestion : 5

We define a Python tuple (2,4,6) and send it to the ast.parse() method with mode='eval', which returns the result of the expression after evaluation, and store the result in tree.,We define a TupleVisitor class that extends from the parent class ast.NodeVisitor. We override the predefined visit_Constant and visit_Tuple methods in the parent class, which receive the Constant and Tuple nodes, respectively.,Then, we call the generic_visit() method, which invokes the propagation of visits on the children nodes of the input node.,The ast.dump() method returns a formatted string of the tree structure in tree.

import ast
from pprint
import pprint

class TupleVisitor(ast.NodeVisitor):

   def visit_Tuple(self, node):
   print('Node type: Tuple\nFields: ', node._fields)
ast.NodeVisitor.generic_visit(self, node)

def visit_Constant(self, node):
   print('Node type: Constant\nFields: ', node._fields)
ast.NodeVisitor.generic_visit(self, node)

visitor = TupleVisitor()
tree = ast.parse('(2,4,6)', mode = 'eval')
pprint(ast.dump(tree))
visitor.visit(tree)

Suggestion : 6

Python Design Patterns,eval - This mode is used to evaluate Python's expression and will return the result after evaluation.,The AST module allows us to evaluate the Python expression and return the result from the expression. Let's understand the following example.,It is used as a custom Python interpreter.

< _ast.Module object at 0x0000010B889A6AC0 >
   Hello Learner!Welcome to JavaTpoint
14
Expression(body = BinOp(left = Constant(value = 6, kind = None), op = Add(), right = Constant(value = 8, kind = None)))
Module(body = [Assign(targets = [Name(id = 'subjects', ctx = Store())], value = List(elts = [Constant(value = 'computer science', kind = None), Constant(value = 'alorithm', kind = None)], ctx = Load()), type_comment = None), Assign(targets = [Name(id = 'name', ctx = Store())], value = Constant(value = 'Ricky', kind = None), type_comment = None), For(target = Name(id = 'fruit', ctx = Store()), iter = Name(id = 'fruits', ctx = Load()), body = [Expr(value = Call(func = Name(id = 'print', ctx = Load()), args = [Call(func = Attribute(value = Constant(value = '{} learn {}', kind = None), attr = 'format', ctx = Load()), args = [Name(id = 'name', ctx = Load()), Name(id = 'subjects', ctx = Load())], keywords = [])], keywords = []))], orelse = [], type_comment = None)], type_ignores = [])
Welcome to the Javatpoint
{
   'from': ['pprint'],
   'import': ['ast']
}