Member-only story
Python’s Hidden Metaprogramming Trick: AST (Abstract Syntax Tree) Magic! 🔥
Most Python developers have never explored the world of AST (Abstract Syntax Tree) — but once you do, it will blow your mind. 🚀
What if I told you that you can analyze, modify, and even generate Python code dynamically like a compiler? 😲
Sounds crazy, right? Well, welcome to AST, one of the most powerful and underused features of Python!
🔹 1. What Is AST (Abstract Syntax Tree)?
Before Python executes your script, it parses your code into an Abstract Syntax Tree (AST) — a structured representation of your code’s syntax.
💡 Think of AST as Python’s way of understanding code before running it.
📌 Example:
Let’s take a simple Python expression and convert it into an AST tree.
import ast
expr = "3 + 5"
tree = ast.parse(expr, mode='eval')
print(ast.dump(tree, indent=2))
🔹 Output:
Expression(
body=BinOp(
left=Constant(value=3),
op=Add(),
right=Constant(value=5)
)
)
✅ Python has broken the expression into nodes:
BinOp
→ Binary Operation (+
)Constant(value=3)
→ Number 3