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 piece
1class QueryBuilder:
# __init__ initializes empty builder state
2 def __init__(self):
# _table stores the table name
3 self._table = ""
# _columns stores selected columns
4 self._columns = []
# _conditions stores WHERE conditions
5 self._conditions = []
6
# select method sets columns and returns self for chaining
7 def select(self, *columns):
# Convert variadic args to list
8 self._columns = list(columns)
# Return self enables method chaining
9 return self
10
# from_table method sets the table name
11 def from_table(self, table):
# Store the table name
12 self._table = table
# Return self for chaining
13 return self
14
# where method adds a condition
15 def where(self, condition):
# Append condition to list
16 self._conditions.append(condition)
# Return self for chaining
17 return self
18
# build method constructs the final query
19 def build(self):
# Join columns with comma or use * if empty
20 cols = ", ".join(self._columns) or "*"
# Start with SELECT FROM clause
21 query = f"SELECT {cols} FROM {self._table}"
# Add WHERE clause if conditions exist
22 if self._conditions:
# Join conditions with AND
23 query += " WHERE " + " AND ".join(self._conditions)
# Return the complete query string
24 return query
25
# Chain builder methods to construct query
26query = QueryBuilder().select("name", "age").from_table("users").where("age > 18").build()
# Print the generated SQL query
27print(query)

Output

SELECT name, age FROM users WHERE age > 18
Practice typing this code

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

More Python examples at level 5

← Python typing practice