Building an Internal Domain-Specific Language (DSL)
A Domain-Specific Language (DSL) offers expressive, tailored syntax for a focused problem domain. Python supports internal fluent DSLs using method chaining (`return self`) and operator overloading 🛠️.
class Query:
def __init__(self, table):
self.table = table
self.filters = []
def where(self, col, op, val):
self.filters.append((col, op, val))
return self # Return self for fluent chaining
def build(self):
sql = f"SELECT * FROM {self.table}"
if self.filters:
clauses = [f"{c} {op} {v!r}" for c, op, v in self.filters]
sql += " WHERE " + " AND ".join(clauses)
return sql
query = Query("users").where("age", ">=", 18).where("active", "=", True).build()
print(f"SQL: {query} 🛠️")
# 72. Building an Internal Domain-Specific Language (DSL) A Domain-Specific Language (DSL) offers expressive, tailored syntax for a focused problem domain. Python supports internal fluent DSLs using method chaining (`return self`) and operator overloading 🛠️. ```python class Query: def __init__(self, table): self.table = table self.filters = [] def where(self, col, op, val): self.filters.append((col, op, val)) return self # Return self for fluent chaining def build(self): sql = f"SELECT * FROM {self.table}" if self.filters: clauses = [f"{c} {op} {v!r}" for c, op, v in self.filters] sql += " WHERE " + " AND ".join(clauses) return sql query = Query("users").where("age", ">=", 18).where("active", "=", True).build() print(f"SQL: {query} 🛠️") ``` Popular Python libraries like SQLAlchemy, Peewee, and PyParsing use internal DSLs to represent SQL queries, HTML generators, and grammar rules natively in Python syntax 🚀! --- ### Question What architectural pattern allows internal Python DSLs to chain consecutive operations like `.where(...).limit(...)`? 🧠 - [ ] a. Fluent Interface (Method Chaining), where methods return `self` 🛠️ - [ ] b. Singleton Pattern, guaranteeing a single global instance - [ ] c. Factory Method Pattern, dynamically instantiating sub-classes - [ ] d. Flyweight Pattern, pooling identical string buffers --- ### Challenge Build a `Query` DSL class with `__init__(self, table)`, `where(self, col, val)` returning self, and `build()`. Test with `Query('orders').where('id', 101).build()` and print the output. 🎯 <details> <summary>Solution</summary> ```python class Query: def __init__(self, table): self.table = table self.col = None self.val = None def where(self, col, val): self.col = col self.val = val return self def build(self): if self.col: return f'SELECT * FROM {self.table} WHERE {self.col} = {self.val!r}' return f'SELECT * FROM {self.table}' print(Query('orders').where('id', 101).build()) ``` </details>