Builder Pattern in Python
Level 5598 keystrokes
This implements the Builder pattern with method chaining for constructing complex objects step by step.
Python code
# QueryBuilder assembles a SQL query string piece by piece1class QueryBuilder: # __init__ initializes empty builder state2 def __init__(self): # _table stores the table name3 self._table = "" # _columns stores selected columns4 self._columns = [] # _conditions stores WHERE conditions5 self._conditions = []6 # select method sets columns and returns self for chaining7 def select(self, *columns): # Convert variadic args to list8 self._columns = list(columns) # Return self enables method chaining9 return self10 # from_table method sets the table name11 def from_table(self, table): # Store the table name12 self._table = table # Return self for chaining13 return self14 # where method adds a condition15 def where(self, condition): # Append condition to list16 self._conditions.append(condition) # Return self for chaining17 return self18 # build method constructs the final query19 def build(self): # Join columns with comma or use * if empty20 cols = ", ".join(self._columns) or "*" # Start with SELECT FROM clause21 query = f"SELECT {cols} FROM {self._table}" # Add WHERE clause if conditions exist22 if self._conditions: # Join conditions with AND23 query += " WHERE " + " AND ".join(self._conditions) # Return the complete query string24 return query25 # Chain builder methods to construct query26query = QueryBuilder().select("name", "age").from_table("users").where("age > 18").build()# Print the generated SQL query27print(query)Output
SELECT name, age FROM users WHERE age > 18
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
"× 20.× 17_× 16(× 15)× 15=× 9:× 7,× 5[× 2]× 2