| name | use-class-for-state |
| description | For complex state: encapsulate multiple interacting variables, stateful algorithms, backtracking search state. |
use-class-for-state
When to Use
- Multiple related state variables
- State needs to be copied/restored
- Complex state transitions
- Backtracking algorithms
- State machine implementations
When NOT to Use
- Simple single value
- Stateless algorithm
- Closure is simpler
The Pattern
Encapsulate state in a class with methods for transitions.
class SearchState:
def __init__(self, initial):
self.position = initial
self.visited = set()
self.path = []
self.cost = 0
def copy(self):
"""Create copy for branching."""
new = SearchState.__new__(SearchState)
new.position = self.position
new.visited = set(self.visited)
new.path = list(self.path)
new.cost = self.cost
return new
def move(self, direction):
"""Apply move, update state."""
self.visited.add(self.position)
self.position = self.position + direction
self.path.append(direction)
self.cost += 1
Example (from pytudes)
class Panama:
"""State for palindrome search."""
def __init__(self, L='A man, a plan', R='a canal, Panama', dict=paldict):
self.left = []
self.right = []
self.diff = 0
self.stack = []
self.seen = {}
self.starttime = time.process_time()
self.dict = dict
def add(self, direction, word):
"""Add word to one side."""
if direction == 'left':
self.left.append(word)
self.diff += len(word)
else:
self.right.append(word)
self.diff -= len(word)
self.stack.append(('added', direction, None, word))
return self
def remove():
direction == :
.left.pop()
.diff -= (word)
:
.right.pop()
.diff += (word)
():
_ (steps):
.stack:
action, direction, substr, arg = .stack[-]
action == :
.remove(direction, arg)
action == :
arg:
word = arg.pop()
.add(direction, word)
.consider_candidates()
:
.stack.pop()
Key Principles
- Related state together: All variables in one place
- copy method: For branching in search
- Undo operations: Reverse of each forward step
- Stack for backtracking: Explicit decision history
- Methods for transitions: Encapsulate state changes