{"id":18930,"date":"2022-01-25T10:21:29","date_gmt":"2022-01-25T04:51:29","guid":{"rendered":"http:\/\/www.pythonpool.com\/?p=18930"},"modified":"2022-01-25T10:22:38","modified_gmt":"2022-01-25T04:52:38","slug":"python-ast","status":"publish","type":"post","link":"https:\/\/www.pythonpool.com\/python-ast\/","title":{"rendered":"5 Amazing Python AST Module Examples"},"content":{"rendered":"\n<p>Python is one of the most powerful general-purpose programming language. Its simple syntax is easy to learn and execute. However, have you ever thought about how things work in Python? How does the interpreter run the code or execute them? How are codes interpreted by the system to produce desired results? Or, Who does all this for us? This article will discuss how things work in Python and a quick overview of them using Python ast. So, let&#8217;s start.<\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_74 counter-hierarchy ez-toc-counter ez-toc-transparent ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #990303;color:#990303\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #990303;color:#990303\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 eztoc-toggle-hide-by-default' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.pythonpool.com\/python-ast\/#What_is_AST\" >What is AST?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.pythonpool.com\/python-ast\/#AST_Module\" >AST Module<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.pythonpool.com\/python-ast\/#Example_1_Visualizing_an_AST_for_String\" >Example 1: Visualizing an AST for String<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.pythonpool.com\/python-ast\/#Example_2_Visualizing_AST_for_a_List\" >Example 2: Visualizing AST for a List<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.pythonpool.com\/python-ast\/#Example_3_Visualizing_Arithmetic_Operations_on_Python_AST\" >Example 3: Visualizing Arithmetic Operations on Python AST<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/www.pythonpool.com\/python-ast\/#Example_4_Handling_Multi-Operations_in_Python_AST\" >Example 4: Handling Multi-Operations in Python AST<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/www.pythonpool.com\/python-ast\/#Example_5_Comments_in_Python_AST\" >Example 5: Comments in Python AST<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/www.pythonpool.com\/python-ast\/#FAQs_on_Python_AST\" >FAQs on Python AST<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/www.pythonpool.com\/python-ast\/#Conclusion\" >Conclusion<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/www.pythonpool.com\/python-ast\/#Trending_Now\" >Trending Now<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\" id=\"h-what-is-ast\"><span class=\"ez-toc-section\" id=\"What_is_AST\"><\/span>What is AST?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p><strong>AST,<\/strong> also known as <strong>Abstract Syntax Tree, is a python tool that is used to directly interact with python code and modify them. How??, right. So, to understand that,<\/strong> we first need to see how things work when we run our code. Let&#8217;s see that. Before producing the output, it goes through a series of steps, i.e.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Step1:<\/strong> The code we have written is converted into group of chunks known as tokens. These tokens are created by the predefined instructions. <br><\/li><li><strong>Step2: <\/strong>These tokens are then arranged in the form of a tree known as <strong>AST. <\/strong> AST is th tree like structure in which tokens are arranged according to the Abstarct Grammar. The order of arrangements give meaning to the tree. <br><\/li><li><strong>Step3: <\/strong>Then the tree is converted into <span style=\"text-decoration: underline;\"><strong><a href=\"http:\/\/www.pythonpool.com\/python-int-to-binary\/\" target=\"_blank\" rel=\"noreferrer noopener\">binary<\/a><\/strong><\/span> code. This gives the ease of understanding the code to the machine.<br><\/li><li><strong>Step4: <\/strong>When <span style=\"text-decoration: underline;\"><strong><a href=\"http:\/\/www.pythonpool.com\/is-python-compiled-interpreted-or-both\/\" target=\"_blank\" rel=\"noreferrer noopener\">interpreter<\/a><\/strong><\/span> gets the instructtion in the form of byte code it runs those code and make system calls from the kernel and execute the program.<br><\/li><li><strong>Step5:<\/strong> It then return the output. <\/li><\/ul>\n\n\n\n<p>So, I hope this specifies the importance of AST and helps you understand the meaning of AST.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-ast-module\"><span class=\"ez-toc-section\" id=\"AST_Module\"><\/span>AST Module<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>So, Python has an inbuilt AST module that helps visualize processing at the backend, i.e., Abstract Syntax Grammar. The <strong>parse() function<\/strong> from the module is used to generate an abstract syntax tree for the code. To understand its structure, let&#8217;s see some of the code. <\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-example-1-visualizing-an-ast-for-string\"><span class=\"ez-toc-section\" id=\"Example_1_Visualizing_an_AST_for_String\"><\/span>Example 1: Visualizing an AST for String<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport ast  \n\n# Creating AST  \ncode = ast.parse(&quot;print('Welcome To PythonPool')&quot;)  \nprint(code)  \n# Printing AST\nprint(ast.dump(code))\n# Executing AST\nexec(compile(code, filename=&quot;&quot;, mode=&quot;exec&quot;))\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;_ast.Module object at 0x7f126e22a050&gt;\nModule(body=&#91;Expr(value=Call(func=Name(id='print', ctx=Load()), args=&#91;Str(s='Welcome To PythonPool')], keywords=&#91;]))])\nWelcome To PythonPool<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Explanation<\/strong><\/h4>\n\n\n\n<p>So, in the above example, we first created an AST for printing the string. After that, we printed the AST using the dump() function, which shows how the tree visualizes with much more information. Then we called compile() method and exec() method to execute the AST. From the output of the dump() method, we can clearly see how our code is distributed into different components before the actual execution. <\/p>\n\n\n\n<p>The dump() method is used to get a formatted string of the tree. It returns the formatted string, which contains information about the fields and values for the tree. This generally helps debug and get the idea of the distribution of components on the tree. <\/p>\n\n\n<div class=\"monsterinsights-inline-popular-posts monsterinsights-inline-popular-posts-golf monsterinsights-popular-posts-styled\" ><div class=\"monsterinsights-inline-popular-posts-text\"><span class=\"monsterinsights-inline-popular-posts-label\" >Popular now<\/span><span class=\"monsterinsights-inline-popular-posts-border\" ><\/span><span class=\"monsterinsights-inline-popular-posts-border-2\" ><\/span><div class=\"monsterinsights-inline-popular-posts-post\"><a class=\"monsterinsights-inline-popular-posts-title\"  href=\"https:\/\/www.pythonpool.com\/fixed-typeerror-cant-compare-datetime-datetime-to-datetime-date\/\">[Fixed] typeerror can&#8217;t compare datetime.datetime to datetime.date<\/a><\/div><\/div><\/div><p><\/p>\n\n\n<h3 class=\"wp-block-heading\" id=\"h-example-2-visualizing-ast-for-a-list\"><span class=\"ez-toc-section\" id=\"Example_2_Visualizing_AST_for_a_List\"><\/span>Example 2: Visualizing AST for a List<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>So, in the above example, we have seen how a string is interpreted by the parse() function. In this example, we will see how a List is interpreted by the AST.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport ast  \n\n# Creating AST\ncode = ast.parse(&quot;print(&#x5B;1,2,3,4,5])&quot;)  \n# Printing AST\nprint(ast.dump(code))\n# Executing AST\nexec(compile(code, filename=&quot;&quot;, mode=&quot;exec&quot;))\n<\/pre><\/div>\n\n\n<p> <strong>Output:<\/strong> <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Module(body=&#91;Expr(value=Call(func=Name(id='print', ctx=Load()), args=&#91;List(elts=&#91;Num(n=1), Num(n=2), Num(n=3), Num(n=4), Num(n=5)], ctx=Load())], keywords=&#91;]))])\n&#91;1, 2, 3, 4, 5]<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-example-3-visualizing-arithmetic-operations-on-python-ast\"><span class=\"ez-toc-section\" id=\"Example_3_Visualizing_Arithmetic_Operations_on_Python_AST\"><\/span>Example 3: Visualizing Arithmetic Operations on Python AST<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>So, in the above two examples, we have seen how <span style=\"text-decoration: underline;\"><strong><a href=\"http:\/\/www.pythonpool.com\/python-data-types\/\" target=\"_blank\" rel=\"noreferrer noopener\">datatypes<\/a><\/strong><\/span> are handled by AST. Now, let&#8217;s take an example to understand how an expression is evaluated by python AST. <\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport ast  \n\n# Creating AST\ncode = ast.parse(&quot;print(10+12)&quot;)  \n# Printing AST\nprint(ast.dump(code))\n# Executing AST\nexec(compile(code, filename=&quot;&quot;, mode=&quot;exec&quot;))\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Module(body=&#91;Expr(value=Call(func=Name(id='print', ctx=Load()), args=&#91;BinOp(left=Num(n=10), op=Add(), right=Num(n=12))], keywords=&#91;]))])\n22<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Explanation<\/strong><\/h4>\n\n\n\n<p>So, in the above example, we can see that expression trees tell that we have to perform the Add() operation on two numbers that are saved in binary form and then show the output. <\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-example-4-handling-multi-operations-in-python-ast\"><span class=\"ez-toc-section\" id=\"Example_4_Handling_Multi-Operations_in_Python_AST\"><\/span>Example 4: Handling Multi-Operations in Python AST<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>So, till now, we have seen how a single component is distributed in AST. This example will show what happens if we specify more than one operation and how it is handled and distributed in AST. Let&#8217;s see.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport ast  \n  \ntree_ast = ast.parse('''  \nlocation = &#x5B;'Agra', 'UP']  \nname = 'Taj Mahal'  \n\nprint('{} is located in {},{}'.format(name, location&#x5B;0],location&#x5B;1]))  \n''')  \n  \nprint(ast.dump(tree_ast))\n\nexec(compile(tree_ast, filename=&quot;&quot;, mode=&quot;exec&quot;))\n<\/pre><\/div>\n\n\n<p> <strong>Output:<\/strong> <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Module(body=&#91;Assign(targets=&#91;Name(id='location', ctx=Store())], value=List(elts=&#91;Str(s='Agra'), Str(s='UP')], ctx=Load())), Assign(targets=&#91;Name(id='name', ctx=Store())], value=Str(s='Taj Mahal')), Expr(value=Call(func=Name(id='print', ctx=Load()), args=&#91;Call(func=Attribute(value=Str(s='{} is located in {},{}'), attr='format', ctx=Load()), args=&#91;Name(id='name', ctx=Load()), Subscript(value=Name(id='location', ctx=Load()), slice=Index(value=Num(n=0)), ctx=Load()), Subscript(value=Name(id='location', ctx=Load()), slice=Index(value=Num(n=1)), ctx=Load())], keywords=&#91;])], keywords=&#91;]))])\nTaj Mahal is located in Agra,UP\n<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Explanation<\/strong><\/h4>\n\n\n\n<p>So, here you can see how the assignment operation is distributed in the tree, and then more than one component is distributed in the tree, taking different nodes. <\/p>\n\n\n<div class=\"monsterinsights-inline-popular-posts monsterinsights-inline-popular-posts-lima monsterinsights-popular-posts-styled\" ><div class=\"monsterinsights-inline-popular-posts-image\"><a href=\"https:\/\/www.pythonpool.com\/fixed-nameerror-name-unicode-is-not-defined\/\"><img decoding=\"async\" src=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-nameerror-name-Unicode-is-not-defined-300x157.webp\" srcset=\" https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-nameerror-name-Unicode-is-not-defined-300x157.webp 300w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-nameerror-name-Unicode-is-not-defined-1024x536.webp 1024w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-nameerror-name-Unicode-is-not-defined-768x402.webp 768w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-nameerror-name-Unicode-is-not-defined.webp 1200w \" alt=\"[Fixed] nameerror: name Unicode is not defined\" \/><\/a><\/div><div class=\"monsterinsights-inline-popular-posts-text\"><span class=\"monsterinsights-inline-popular-posts-label\" >Trending<\/span><div class=\"monsterinsights-inline-popular-posts-post\"><a class=\"monsterinsights-inline-popular-posts-title\"  href=\"https:\/\/www.pythonpool.com\/fixed-nameerror-name-unicode-is-not-defined\/\">[Fixed] nameerror: name Unicode is not defined<\/a><\/div><\/div><\/div><p><\/p>\n\n\n<h3 class=\"wp-block-heading\" id=\"h-example-5-comments-in-python-ast\"><span class=\"ez-toc-section\" id=\"Example_5_Comments_in_Python_AST\"><\/span>Example 5: Comments in Python AST<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport ast  \n\n# Creating AST  \ncode = ast.parse(&quot;# This is a comment&quot;)  \nprint(code)  \n# Printing AST\nprint(ast.dump(code))\n# Executing AST\nexec(compile(code, filename=&quot;&quot;, mode=&quot;exec&quot;))\n<\/pre><\/div>\n\n\n<p> <strong>Output:<\/strong> <\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;_ast.Module object at 0x7f569e710650&gt;\nModule(body=&#91;])<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Explanation<\/strong><\/h4>\n\n\n\n<p>So, as the above example shows, that body node contains nothing. It means that there is no subsequent node for that, and hence it is empty. The reason for that is <code>ast<\/code> the module doesn&#8217;t include comments.<\/p>\n\n\n<div class=\"monsterinsights-inline-popular-posts monsterinsights-inline-popular-posts-beta monsterinsights-popular-posts-styled\" ><div class=\"monsterinsights-inline-popular-posts-image\"><a href=\"https:\/\/www.pythonpool.com\/solved-runtimeerror-cuda-error-invalid-device-ordinal\/\"><img decoding=\"async\" src=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Solved-runtimeerror-cuda-error-invalid-device-ordinal-300x157.webp\" srcset=\" https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Solved-runtimeerror-cuda-error-invalid-device-ordinal-300x157.webp 300w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Solved-runtimeerror-cuda-error-invalid-device-ordinal-1024x536.webp 1024w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Solved-runtimeerror-cuda-error-invalid-device-ordinal-768x402.webp 768w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Solved-runtimeerror-cuda-error-invalid-device-ordinal.webp 1200w \" alt=\"[Solved] runtimeerror: cuda error: invalid device ordinal\" \/><\/a><\/div><div class=\"monsterinsights-inline-popular-posts-text\"><span class=\"monsterinsights-inline-popular-posts-label\" >Trending<\/span><div class=\"monsterinsights-inline-popular-posts-post\"><a class=\"monsterinsights-inline-popular-posts-title\"  href=\"https:\/\/www.pythonpool.com\/solved-runtimeerror-cuda-error-invalid-device-ordinal\/\">[Solved] runtimeerror: cuda error: invalid device ordinal<\/a><\/div><\/div><\/div><p><\/p>\n\n\n<h2 class=\"wp-block-heading\" id=\"h-faqs-on-python-ast\"><span class=\"ez-toc-section\" id=\"FAQs_on_Python_AST\"><\/span>FAQs on Python AST <span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<div class=\"schema-faq wp-block-yoast-faq-block\"><div class=\"schema-faq-section\" id=\"faq-question-1642929916778\"><strong class=\"schema-faq-question\">Q1) \u00a0Is there a python library (or package) to convert ast to java code?<\/strong> <p class=\"schema-faq-answer\">No, there is no such python library that will convert ast to<a href=\"https:\/\/en.wikipedia.org\/wiki\/Java_(programming_language)\" target=\"_blank\" rel=\"noreferrer noopener\"> java<\/a> code.<\/p> <\/div> <div class=\"schema-faq-section\" id=\"faq-question-1642930007346\"><strong class=\"schema-faq-question\">Q2) How do I recursively simplify a mathematical expression with ast in python 3?<\/strong> <p class=\"schema-faq-answer\">You can define your evaluator class. An example is given below.<br\/><br\/><code>import ast<br\/><br\/>class EvaluateExpression(ast.NodeTransformer):<br\/><br\/>\u00a0 \u00a0 # Defining operations for operators<br\/>\u00a0 \u00a0 ops = {<br\/>\u00a0 \u00a0 \u00a0 \u00a0 ast.Add: '+',<br\/>\u00a0 \u00a0 \u00a0 \u00a0 ast.Sub: '-',<br\/>\u00a0 \u00a0 \u00a0 \u00a0 ast.Mult: '*',<br\/>\u00a0 \u00a0 \u00a0 \u00a0 ast.Div: '\/',<br\/>\u00a0 \u00a0 }<br\/><br\/>\u00a0 \u00a0 def visit_BinOp(self, node):<br\/>\u00a0 \u00a0 \u00a0 \u00a0 self.generic_visit(node)<br\/>\u00a0 \u00a0 \u00a0 \u00a0 if isinstance(node.left, ast.Num) and isinstance(node.right, ast.Num):<br\/>\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 value = eval(f'{node.left.n} {self.ops[type(node.op)]} {node.right.n}')<br\/>\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 return ast.Num(n=value)<br\/>\u00a0 \u00a0 \u00a0 \u00a0 return node<br\/><br\/>tree = ast.parse('3+2+7+8')<br\/>tree = ast.fix_missing_locations(EvaluateExpression().visit(tree))<br\/>print(ast.dump(tree))<\/code><\/p> <\/div> <div class=\"schema-faq-section\" id=\"faq-question-1642930343928\"><strong class=\"schema-faq-question\">Q3) Is there any way to round trip a python ast through XML?<\/strong> <p class=\"schema-faq-answer\">You can use the RedBaron library to take inspiration for converting Python ast to XML.<\/p> <\/div> <\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-conclusion\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>So, today in this article, we have seen an AST and how it is created. Then we discussed the AST module provided by Python and how it helps in building the Syntax tree for our code. Then we tried visualizing the tree in different scenarios and different operations. This gave us an understanding of how a code actually works. I hope this article has helped you. Thank You.<\/p>\n\n\n<div class=\"monsterinsights-widget-popular-posts monsterinsights-widget-popular-posts-delta monsterinsights-popular-posts-styled monsterinsights-widget-popular-posts-columns-2\"><h2 class=\"monsterinsights-widget-popular-posts-widget-title\"><span class=\"ez-toc-section\" id=\"Trending_Now\"><\/span>Trending Now<span class=\"ez-toc-section-end\"><\/span><\/h2><ul class=\"monsterinsights-widget-popular-posts-list\"><li ><a href=\"https:\/\/www.pythonpool.com\/fixed-typeerror-cant-compare-datetime-datetime-to-datetime-date\/\"><div class=\"monsterinsights-widget-popular-posts-image\"><img decoding=\"async\" src=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/typeerror-cant-compare-datetime.datetime-to-datetime.date_-300x157.webp\" srcset=\" https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/typeerror-cant-compare-datetime.datetime-to-datetime.date_-300x157.webp 300w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/typeerror-cant-compare-datetime.datetime-to-datetime.date_-1024x536.webp 1024w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/typeerror-cant-compare-datetime.datetime-to-datetime.date_-768x402.webp 768w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/typeerror-cant-compare-datetime.datetime-to-datetime.date_.webp 1200w \" alt=\"[Fixed] typeerror can&#8217;t compare datetime.datetime to datetime.date\" \/><\/div><div class=\"monsterinsights-widget-popular-posts-text\"><span class=\"monsterinsights-widget-popular-posts-title\" >[Fixed] typeerror can&#8217;t compare datetime.datetime to datetime.date<\/span><div class=\"monsterinsights-widget-popular-posts-meta\" ><span class=\"monsterinsights-widget-popular-posts-author\">by Namrata Gulati<\/span><span>&#9679;<\/span><span class=\"monsterinsights-widget-popular-posts-date\">January 11, 2024<\/span><\/div><\/div><\/a><\/li><li ><a href=\"https:\/\/www.pythonpool.com\/fixed-nameerror-name-unicode-is-not-defined\/\"><div class=\"monsterinsights-widget-popular-posts-image\"><img decoding=\"async\" src=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-nameerror-name-Unicode-is-not-defined-300x157.webp\" srcset=\" https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-nameerror-name-Unicode-is-not-defined-300x157.webp 300w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-nameerror-name-Unicode-is-not-defined-1024x536.webp 1024w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-nameerror-name-Unicode-is-not-defined-768x402.webp 768w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-nameerror-name-Unicode-is-not-defined.webp 1200w \" alt=\"[Fixed] nameerror: name Unicode is not defined\" \/><\/div><div class=\"monsterinsights-widget-popular-posts-text\"><span class=\"monsterinsights-widget-popular-posts-title\" >[Fixed] nameerror: name Unicode is not defined<\/span><div class=\"monsterinsights-widget-popular-posts-meta\" ><span class=\"monsterinsights-widget-popular-posts-author\">by Namrata Gulati<\/span><span>&#9679;<\/span><span class=\"monsterinsights-widget-popular-posts-date\">January 2, 2024<\/span><\/div><\/div><\/a><\/li><li ><a href=\"https:\/\/www.pythonpool.com\/solved-runtimeerror-cuda-error-invalid-device-ordinal\/\"><div class=\"monsterinsights-widget-popular-posts-image\"><img decoding=\"async\" src=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Solved-runtimeerror-cuda-error-invalid-device-ordinal-300x157.webp\" srcset=\" https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Solved-runtimeerror-cuda-error-invalid-device-ordinal-300x157.webp 300w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Solved-runtimeerror-cuda-error-invalid-device-ordinal-1024x536.webp 1024w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Solved-runtimeerror-cuda-error-invalid-device-ordinal-768x402.webp 768w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Solved-runtimeerror-cuda-error-invalid-device-ordinal.webp 1200w \" alt=\"[Solved] runtimeerror: cuda error: invalid device ordinal\" \/><\/div><div class=\"monsterinsights-widget-popular-posts-text\"><span class=\"monsterinsights-widget-popular-posts-title\" >[Solved] runtimeerror: cuda error: invalid device ordinal<\/span><div class=\"monsterinsights-widget-popular-posts-meta\" ><span class=\"monsterinsights-widget-popular-posts-author\">by Namrata Gulati<\/span><span>&#9679;<\/span><span class=\"monsterinsights-widget-popular-posts-date\">January 2, 2024<\/span><\/div><\/div><\/a><\/li><li ><a href=\"https:\/\/www.pythonpool.com\/fixed-typeerror-type-numpy-ndarray-doesnt-define-__round__-method\/\"><div class=\"monsterinsights-widget-popular-posts-image\"><img decoding=\"async\" src=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-typeerror-type-numpy.ndarray-doesnt-define-__round__-method-300x157.webp\" srcset=\" https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-typeerror-type-numpy.ndarray-doesnt-define-__round__-method-300x157.webp 300w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-typeerror-type-numpy.ndarray-doesnt-define-__round__-method-1024x536.webp 1024w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-typeerror-type-numpy.ndarray-doesnt-define-__round__-method-768x402.webp 768w, https:\/\/www.pythonpool.com\/wp-content\/uploads\/2024\/01\/Fixed-typeerror-type-numpy.ndarray-doesnt-define-__round__-method.webp 1200w \" alt=\"[Fixed] typeerror: type numpy.ndarray doesn&#8217;t define __round__ method\" \/><\/div><div class=\"monsterinsights-widget-popular-posts-text\"><span class=\"monsterinsights-widget-popular-posts-title\" >[Fixed] typeerror: type numpy.ndarray doesn&#8217;t define __round__ method<\/span><div class=\"monsterinsights-widget-popular-posts-meta\" ><span class=\"monsterinsights-widget-popular-posts-author\">by Namrata Gulati<\/span><span>&#9679;<\/span><span class=\"monsterinsights-widget-popular-posts-date\">January 2, 2024<\/span><\/div><\/div><\/a><\/li><\/ul><\/div><p><\/p>","protected":false},"excerpt":{"rendered":"<p>Python is one of the most powerful general-purpose programming language. Its simple syntax is easy to learn and execute. However, have you ever thought about &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"5 Amazing Python AST Module Examples\" class=\"read-more button\" href=\"https:\/\/www.pythonpool.com\/python-ast\/#more-18930\" aria-label=\"More on 5 Amazing Python AST Module Examples\">Read more<\/a><\/p>\n","protected":false},"author":25,"featured_media":19379,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_mi_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[4345],"tags":[4757,4758,4763,4756,4759,4762,4760,4761],"class_list":["post-18930","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-module","tag-ast-library-python","tag-import-ast-python","tag-python-ast-example","tag-python-ast-examples","tag-python-ast-library","tag-python-ast-literal_eval","tag-python-ast-module","tag-python-ast-tutorial","infinite-scroll-item"],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v20.1 (Yoast SEO v25.0) - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>5 Amazing Python AST Module Examples - Python Pool<\/title>\n<meta name=\"description\" content=\"In this article, we will learn about Python AST and see how a code is executed by the system. Then we will see scenarios of AST working.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.pythonpool.com\/python-ast\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"5 Amazing Python AST Module Examples\" \/>\n<meta property=\"og:description\" content=\"Python is one of the most powerful general-purpose programming language. Its simple syntax is easy to learn and execute. However, have you ever thought\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.pythonpool.com\/python-ast\/\" \/>\n<meta property=\"og:site_name\" content=\"Python Pool\" \/>\n<meta property=\"article:published_time\" content=\"2022-01-25T04:51:29+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-01-25T04:52:38+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2022\/01\/python-ast.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"Rishav Raj\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@pythonpool\" \/>\n<meta name=\"twitter:site\" content=\"@pythonpool\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Rishav Raj\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/www.pythonpool.com\/python-ast\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/www.pythonpool.com\/python-ast\/\"},\"author\":{\"name\":\"Rishav Raj\",\"@id\":\"https:\/\/www.pythonpool.com\/#\/schema\/person\/025222e28182ecbb97e17f9f1bf15ac4\"},\"headline\":\"5 Amazing Python AST Module Examples\",\"datePublished\":\"2022-01-25T04:51:29+00:00\",\"dateModified\":\"2022-01-25T04:52:38+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/www.pythonpool.com\/python-ast\/\"},\"wordCount\":829,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/www.pythonpool.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/www.pythonpool.com\/python-ast\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2022\/01\/python-ast.webp\",\"keywords\":[\"ast library python\",\"import ast python\",\"python ast example\",\"python ast examples\",\"python ast library\",\"python ast literal_eval\",\"python ast module\",\"python ast tutorial\"],\"articleSection\":[\"Module\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/www.pythonpool.com\/python-ast\/#respond\"]}]},{\"@type\":[\"WebPage\",\"FAQPage\"],\"@id\":\"https:\/\/www.pythonpool.com\/python-ast\/\",\"url\":\"https:\/\/www.pythonpool.com\/python-ast\/\",\"name\":\"5 Amazing Python AST Module Examples - Python Pool\",\"isPartOf\":{\"@id\":\"https:\/\/www.pythonpool.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/www.pythonpool.com\/python-ast\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/www.pythonpool.com\/python-ast\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2022\/01\/python-ast.webp\",\"datePublished\":\"2022-01-25T04:51:29+00:00\",\"dateModified\":\"2022-01-25T04:52:38+00:00\",\"description\":\"In this article, we will learn about Python AST and see how a code is executed by the system. Then we will see scenarios of AST working.\",\"breadcrumb\":{\"@id\":\"https:\/\/www.pythonpool.com\/python-ast\/#breadcrumb\"},\"mainEntity\":[{\"@id\":\"https:\/\/www.pythonpool.com\/python-ast\/#faq-question-1642929916778\"},{\"@id\":\"https:\/\/www.pythonpool.com\/python-ast\/#faq-question-1642930007346\"},{\"@id\":\"https:\/\/www.pythonpool.com\/python-ast\/#faq-question-1642930343928\"}],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.pythonpool.com\/python-ast\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.pythonpool.com\/python-ast\/#primaryimage\",\"url\":\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2022\/01\/python-ast.webp\",\"contentUrl\":\"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2022\/01\/python-ast.webp\",\"width\":1200,\"height\":628,\"caption\":\"python ast\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.pythonpool.com\/python-ast\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.pythonpool.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"5 Amazing Python AST Module Examples\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.pythonpool.com\/#website\",\"url\":\"https:\/\/www.pythonpool.com\/\",\"name\":\"Python Pool\",\"description\":\"Your One-Stop Python Learning Destination\",\"publisher\":{\"@id\":\"https:\/\/www.pythonpool.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.pythonpool.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.pythonpool.com\/#organization\",\"name\":\"Python Pool\",\"url\":\"https:\/\/www.pythonpool.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.pythonpool.com\/#\/schema\/logo\/image\/\",\"url\":\"http:\/\/www.pythonpool.com\/wp-content\/uploads\/2020\/08\/aa.png\",\"contentUrl\":\"http:\/\/www.pythonpool.com\/wp-content\/uploads\/2020\/08\/aa.png\",\"width\":452,\"height\":185,\"caption\":\"Python Pool\"},\"image\":{\"@id\":\"https:\/\/www.pythonpool.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/pythonpool\",\"https:\/\/www.youtube.com\/c\/pythonpool\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.pythonpool.com\/#\/schema\/person\/025222e28182ecbb97e17f9f1bf15ac4\",\"name\":\"Rishav Raj\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.pythonpool.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/77d441cf39fc8183322bfc1dcaf04be5c1fd429574820606cccac81fd8e8749a?s=96&d=wavatar&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/77d441cf39fc8183322bfc1dcaf04be5c1fd429574820606cccac81fd8e8749a?s=96&d=wavatar&r=g\",\"caption\":\"Rishav Raj\"}},{\"@type\":\"Question\",\"@id\":\"https:\/\/www.pythonpool.com\/python-ast\/#faq-question-1642929916778\",\"position\":1,\"url\":\"https:\/\/www.pythonpool.com\/python-ast\/#faq-question-1642929916778\",\"name\":\"Q1) \u00a0Is there a python library (or package) to convert ast to java code?\",\"answerCount\":1,\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"No, there is no such python library that will convert ast to<a href=\\\"https:\/\/en.wikipedia.org\/wiki\/Java_(programming_language)\\\" target=\\\"_blank\\\" rel=\\\"noreferrer noopener\\\"> java<\/a> code.\",\"inLanguage\":\"en-US\"},\"inLanguage\":\"en-US\"},{\"@type\":\"Question\",\"@id\":\"https:\/\/www.pythonpool.com\/python-ast\/#faq-question-1642930007346\",\"position\":2,\"url\":\"https:\/\/www.pythonpool.com\/python-ast\/#faq-question-1642930007346\",\"name\":\"Q2) How do I recursively simplify a mathematical expression with ast in python 3?\",\"answerCount\":1,\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"You can define your evaluator class. An example is given below.<br\/><br\/>import ast<br\/><br\/>class EvaluateExpression(ast.NodeTransformer):<br\/><br\/>\u00a0 \u00a0 # Defining operations for operators<br\/>\u00a0 \u00a0 ops = {<br\/>\u00a0 \u00a0 \u00a0 \u00a0 ast.Add: '+',<br\/>\u00a0 \u00a0 \u00a0 \u00a0 ast.Sub: '-',<br\/>\u00a0 \u00a0 \u00a0 \u00a0 ast.Mult: '*',<br\/>\u00a0 \u00a0 \u00a0 \u00a0 ast.Div: '\/',<br\/>\u00a0 \u00a0 }<br\/><br\/>\u00a0 \u00a0 def visit_BinOp(self, node):<br\/>\u00a0 \u00a0 \u00a0 \u00a0 self.generic_visit(node)<br\/>\u00a0 \u00a0 \u00a0 \u00a0 if isinstance(node.left, ast.Num) and isinstance(node.right, ast.Num):<br\/>\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 value = eval(f'{node.left.n} {self.ops[type(node.op)]} {node.right.n}')<br\/>\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 return ast.Num(n=value)<br\/>\u00a0 \u00a0 \u00a0 \u00a0 return node<br\/><br\/>tree = ast.parse('3+2+7+8')<br\/>tree = ast.fix_missing_locations(EvaluateExpression().visit(tree))<br\/>print(ast.dump(tree))\",\"inLanguage\":\"en-US\"},\"inLanguage\":\"en-US\"},{\"@type\":\"Question\",\"@id\":\"https:\/\/www.pythonpool.com\/python-ast\/#faq-question-1642930343928\",\"position\":3,\"url\":\"https:\/\/www.pythonpool.com\/python-ast\/#faq-question-1642930343928\",\"name\":\"Q3) Is there any way to round trip a python ast through XML?\",\"answerCount\":1,\"acceptedAnswer\":{\"@type\":\"Answer\",\"text\":\"You can use the RedBaron library to take inspiration for converting Python ast to XML.\",\"inLanguage\":\"en-US\"},\"inLanguage\":\"en-US\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"5 Amazing Python AST Module Examples - Python Pool","description":"In this article, we will learn about Python AST and see how a code is executed by the system. Then we will see scenarios of AST working.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.pythonpool.com\/python-ast\/","og_locale":"en_US","og_type":"article","og_title":"5 Amazing Python AST Module Examples","og_description":"Python is one of the most powerful general-purpose programming language. Its simple syntax is easy to learn and execute. However, have you ever thought","og_url":"https:\/\/www.pythonpool.com\/python-ast\/","og_site_name":"Python Pool","article_published_time":"2022-01-25T04:51:29+00:00","article_modified_time":"2022-01-25T04:52:38+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2022\/01\/python-ast.webp","type":"image\/webp"}],"author":"Rishav Raj","twitter_card":"summary_large_image","twitter_creator":"@pythonpool","twitter_site":"@pythonpool","twitter_misc":{"Written by":"Rishav Raj","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.pythonpool.com\/python-ast\/#article","isPartOf":{"@id":"https:\/\/www.pythonpool.com\/python-ast\/"},"author":{"name":"Rishav Raj","@id":"https:\/\/www.pythonpool.com\/#\/schema\/person\/025222e28182ecbb97e17f9f1bf15ac4"},"headline":"5 Amazing Python AST Module Examples","datePublished":"2022-01-25T04:51:29+00:00","dateModified":"2022-01-25T04:52:38+00:00","mainEntityOfPage":{"@id":"https:\/\/www.pythonpool.com\/python-ast\/"},"wordCount":829,"commentCount":0,"publisher":{"@id":"https:\/\/www.pythonpool.com\/#organization"},"image":{"@id":"https:\/\/www.pythonpool.com\/python-ast\/#primaryimage"},"thumbnailUrl":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2022\/01\/python-ast.webp","keywords":["ast library python","import ast python","python ast example","python ast examples","python ast library","python ast literal_eval","python ast module","python ast tutorial"],"articleSection":["Module"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.pythonpool.com\/python-ast\/#respond"]}]},{"@type":["WebPage","FAQPage"],"@id":"https:\/\/www.pythonpool.com\/python-ast\/","url":"https:\/\/www.pythonpool.com\/python-ast\/","name":"5 Amazing Python AST Module Examples - Python Pool","isPartOf":{"@id":"https:\/\/www.pythonpool.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.pythonpool.com\/python-ast\/#primaryimage"},"image":{"@id":"https:\/\/www.pythonpool.com\/python-ast\/#primaryimage"},"thumbnailUrl":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2022\/01\/python-ast.webp","datePublished":"2022-01-25T04:51:29+00:00","dateModified":"2022-01-25T04:52:38+00:00","description":"In this article, we will learn about Python AST and see how a code is executed by the system. Then we will see scenarios of AST working.","breadcrumb":{"@id":"https:\/\/www.pythonpool.com\/python-ast\/#breadcrumb"},"mainEntity":[{"@id":"https:\/\/www.pythonpool.com\/python-ast\/#faq-question-1642929916778"},{"@id":"https:\/\/www.pythonpool.com\/python-ast\/#faq-question-1642930007346"},{"@id":"https:\/\/www.pythonpool.com\/python-ast\/#faq-question-1642930343928"}],"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.pythonpool.com\/python-ast\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.pythonpool.com\/python-ast\/#primaryimage","url":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2022\/01\/python-ast.webp","contentUrl":"https:\/\/www.pythonpool.com\/wp-content\/uploads\/2022\/01\/python-ast.webp","width":1200,"height":628,"caption":"python ast"},{"@type":"BreadcrumbList","@id":"https:\/\/www.pythonpool.com\/python-ast\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.pythonpool.com\/"},{"@type":"ListItem","position":2,"name":"5 Amazing Python AST Module Examples"}]},{"@type":"WebSite","@id":"https:\/\/www.pythonpool.com\/#website","url":"https:\/\/www.pythonpool.com\/","name":"Python Pool","description":"Your One-Stop Python Learning Destination","publisher":{"@id":"https:\/\/www.pythonpool.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.pythonpool.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.pythonpool.com\/#organization","name":"Python Pool","url":"https:\/\/www.pythonpool.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.pythonpool.com\/#\/schema\/logo\/image\/","url":"http:\/\/www.pythonpool.com\/wp-content\/uploads\/2020\/08\/aa.png","contentUrl":"http:\/\/www.pythonpool.com\/wp-content\/uploads\/2020\/08\/aa.png","width":452,"height":185,"caption":"Python Pool"},"image":{"@id":"https:\/\/www.pythonpool.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/pythonpool","https:\/\/www.youtube.com\/c\/pythonpool"]},{"@type":"Person","@id":"https:\/\/www.pythonpool.com\/#\/schema\/person\/025222e28182ecbb97e17f9f1bf15ac4","name":"Rishav Raj","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.pythonpool.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/77d441cf39fc8183322bfc1dcaf04be5c1fd429574820606cccac81fd8e8749a?s=96&d=wavatar&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/77d441cf39fc8183322bfc1dcaf04be5c1fd429574820606cccac81fd8e8749a?s=96&d=wavatar&r=g","caption":"Rishav Raj"}},{"@type":"Question","@id":"https:\/\/www.pythonpool.com\/python-ast\/#faq-question-1642929916778","position":1,"url":"https:\/\/www.pythonpool.com\/python-ast\/#faq-question-1642929916778","name":"Q1) \u00a0Is there a python library (or package) to convert ast to java code?","answerCount":1,"acceptedAnswer":{"@type":"Answer","text":"No, there is no such python library that will convert ast to<a href=\"https:\/\/en.wikipedia.org\/wiki\/Java_(programming_language)\" target=\"_blank\" rel=\"noreferrer noopener\"> java<\/a> code.","inLanguage":"en-US"},"inLanguage":"en-US"},{"@type":"Question","@id":"https:\/\/www.pythonpool.com\/python-ast\/#faq-question-1642930007346","position":2,"url":"https:\/\/www.pythonpool.com\/python-ast\/#faq-question-1642930007346","name":"Q2) How do I recursively simplify a mathematical expression with ast in python 3?","answerCount":1,"acceptedAnswer":{"@type":"Answer","text":"You can define your evaluator class. An example is given below.<br\/><br\/>import ast<br\/><br\/>class EvaluateExpression(ast.NodeTransformer):<br\/><br\/>\u00a0 \u00a0 # Defining operations for operators<br\/>\u00a0 \u00a0 ops = {<br\/>\u00a0 \u00a0 \u00a0 \u00a0 ast.Add: '+',<br\/>\u00a0 \u00a0 \u00a0 \u00a0 ast.Sub: '-',<br\/>\u00a0 \u00a0 \u00a0 \u00a0 ast.Mult: '*',<br\/>\u00a0 \u00a0 \u00a0 \u00a0 ast.Div: '\/',<br\/>\u00a0 \u00a0 }<br\/><br\/>\u00a0 \u00a0 def visit_BinOp(self, node):<br\/>\u00a0 \u00a0 \u00a0 \u00a0 self.generic_visit(node)<br\/>\u00a0 \u00a0 \u00a0 \u00a0 if isinstance(node.left, ast.Num) and isinstance(node.right, ast.Num):<br\/>\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 value = eval(f'{node.left.n} {self.ops[type(node.op)]} {node.right.n}')<br\/>\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 return ast.Num(n=value)<br\/>\u00a0 \u00a0 \u00a0 \u00a0 return node<br\/><br\/>tree = ast.parse('3+2+7+8')<br\/>tree = ast.fix_missing_locations(EvaluateExpression().visit(tree))<br\/>print(ast.dump(tree))","inLanguage":"en-US"},"inLanguage":"en-US"},{"@type":"Question","@id":"https:\/\/www.pythonpool.com\/python-ast\/#faq-question-1642930343928","position":3,"url":"https:\/\/www.pythonpool.com\/python-ast\/#faq-question-1642930343928","name":"Q3) Is there any way to round trip a python ast through XML?","answerCount":1,"acceptedAnswer":{"@type":"Answer","text":"You can use the RedBaron library to take inspiration for converting Python ast to XML.","inLanguage":"en-US"},"inLanguage":"en-US"}]}},"_links":{"self":[{"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/posts\/18930","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/users\/25"}],"replies":[{"embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/comments?post=18930"}],"version-history":[{"count":22,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/posts\/18930\/revisions"}],"predecessor-version":[{"id":19386,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/posts\/18930\/revisions\/19386"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/media\/19379"}],"wp:attachment":[{"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/media?parent=18930"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/categories?post=18930"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.pythonpool.com\/wp-json\/wp\/v2\/tags?post=18930"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}