Skip to content
Araz Shah
Menu
  • Home
  • About me
  • Contact me
  • CV
  • Online Courses
    • Apply Now !
    • In-Depth
    • Courses
      • Concepts
      • Python Course
      • GIS Developer Course
    • Price
Menu

own expression compiler in Python

Posted on September 10, 2023September 10, 2023 by admin

Writing your own expression compiler in Python can be a challenging but rewarding task. An expression compiler takes an input expression in some form (e.g., mathematical, logical, or a custom domain-specific language) and generates executable code or performs computations based on that expression. Here’s a simplified example of how you might write a basic expression compiler in Python:

import ast

class ExpressionCompiler:
    def __init__(self):
        self.variables = {}

    def compile_expression(self, expression):
        try:
            # Parse the expression into an abstract syntax tree (AST)
            parsed_expression = ast.parse(expression, mode='eval')

            # Visit the AST to perform operations
            result = self.visit(parsed_expression.body)

            return result
        except Exception as e:
            return f"Error: {e}"

    def visit(self, node):
        if isinstance(node, ast.BinOp):
            left = self.visit(node.left)
            right = self.visit(node.right)
            operator = node.op

            if isinstance(operator, ast.Add):
                return left + right
            elif isinstance(operator, ast.Sub):
                return left - right
            elif isinstance(operator, ast.Mult):
                return left * right
            elif isinstance(operator, ast.Div):
                return left / right
            else:
                raise ValueError(f"Unsupported operator: {operator}")

        elif isinstance(node, ast.Name):
            variable_name = node.id
            if variable_name in self.variables:
                return self.variables[variable_name]
            else:
                raise ValueError(f"Undefined variable: {variable_name}")

        elif isinstance(node, ast.Num):
            return node.n

        else:
            raise ValueError(f"Unsupported node type: {type(node)}")

    def set_variable(self, name, value):
        self.variables[name] = value

# Example usage:
if __name__ == "__main__":
    compiler = ExpressionCompiler()
    expression = "x + 2 * y"

    compiler.set_variable("x", 5)
    compiler.set_variable("y", 3)

    result = compiler.compile_expression(expression)
    print(result)

This simplified example can handle basic arithmetic expressions, but you can extend it to support more complex expressions, functions, and additional features as needed.

Keep in mind that building a full-featured expression compiler for a specific domain or language can be much more complex, and you might need to delve into parsing, semantic analysis, and code generation. You may also want to consider using existing parsing libraries like pyparsing or antlr if your requirements become more complex.

Category: python, Tutorials

Post navigation

← highest level of education
visualize time series data in a Django web application →

Recent Posts

  • Geospatial Risk Assessment: A Python Approach
  • Analyzing Employee Arrival Patterns and Delays Using Geospatial Data
  • Real-Time GPS Tracking on a Web Map using FastAPI & Leaflet
  • How to Create a Simple WebGIS with FastAPI, PostGIS, and Leaflet.js
  • Graph Coloring: How Many Colors Do You Need?

Archives

  • May 2025
  • February 2025
  • January 2025
  • December 2024
  • November 2024
  • September 2024
  • April 2024
  • March 2024
  • February 2024
  • December 2023
  • October 2023
  • September 2023
  • August 2023
  • April 2023

Categories

  • Courses
  • Events
  • GIS
  • Linux
  • News
  • programming
  • python
  • Tutorials
  • Videos
  • May 2025
  • February 2025
  • January 2025
  • December 2024
  • November 2024
  • September 2024
  • April 2024
  • March 2024
  • February 2024
  • December 2023
  • October 2023
  • September 2023
  • August 2023
  • April 2023
  • Courses
  • Events
  • GIS
  • Linux
  • News
  • programming
  • python
  • Tutorials
  • Videos

Araz Shahkarami

I’m a software enthusiast with a deep love for crafting robust and efficient solutions. My journey into the world of programming began several years ago when I was introduced to the world of code. Since then, I’ve been on an exhilarating ride of learning, problem-solving, and continuous improvement.

© 2025 Araz Shah | Powered by Minimalist Blog WordPress Theme