Design patterns are language-independent, but in the context of languages with first-class functions, it’s beneficial to rethink some patterns. The general idea is: you can replace instances of some participant class with simple functions, reducing a lot of boilerplate code.

In this post, I will refactor Strategy using functions objects.

Strategy is a good example of a design pattern that can be simpler in Python if you leverage functions as first-class objects.

Classic Strategy

A coarse explanation of Strategy is Strategy, and a clear example is needed.

Let’s consider an online store with three discount rules:

  • 5% discount for customers with 1000 or more fidelity points
  • 7% discount for orders with 10 or more distinct items
  • 10% discount for each LineItem with 20 or more units

The participants in this example are:

  • Context. Provides a service by delegating some computation to interchangeable components that implement alternative algorithms. The Order in this example is the context.
  • Strategy. The interface common to the components that implement different algorithms. In our example, it’s Promotion.
  • Concrete Strategy. One of the concrete subclasses of Strategy. LargeOrderPromo, BulkItemPromo, and FidelityPromo.
from abc import ABC, abstractmethod
from collections import namedtuple

Customer = namedtuple('Customer', 'name fidelity')

class LineItem:
    def __init__(self, product, quantity, price):
        self.product = product
        self.quantity = quantity
        self.price = price

    def total(self):
        return self.price * self.quantity

class Order: # Context
    def __init__(self, customer, cart, promotion=None):
        self.customer = customer
        self.cart = list(cart)
        self.promotion = promotion

    def total(self):
        if not hasattr(self, '__total'):
            self.__total = sum(item.total() for item in self.cart)
            return self.__total

    def due(self):
        discount = 0 if self.promotion is None else self.promotion.discount(self)

        return self.total() - discount

    def __repr__(self):
        fmt = '<Order total: {:.2f} due: {:.2f}>'
        return fmt.format(self.total(), self.due())

class Promotion(ABC): # the Strategy: an Abstract Base Class
    @abstractmethod
    def discount(self, order):
        """
        Return discount as a positive dollar amount
        """

class FidelityPromo(Promotion): # Concrete Strategy
    def discount(self, order):
        """
        5% discount for customers with 1000 or more fidelity points
        """
        return order.total() * 0.05 if order.customer.fidelity >= 1000 else 0

class BulkItemPromo(Promotion): # Concrete Strategy
    def discount(self, order):
        """
        10% discount for each LineItem with 20 or more units
        """
        discount = 0
        for item in order.cart:
            if item.quantity >= 20:
                discount += item.total() * 0.1

        return discount

class LargeOrderPromo(Promotion):
    def discount(self, order):
        """
        7% discount for orders with 10 or more distinct items
        """
        distinctItems = {item.product for item in order.cart}
        if len(distinctItems) >= 10:
            return order.total() * 0.07

        return 0

joe = Customer('John Doe', 0)
ann = Customer('Ann Smith', 1100)
cart = [LineItem('banana', 4, 0.5),
        LineItem('apple', 10, 1.5),
        LineItem('watermellon', 5, 5.0)]

print(Order(joe, cart, FidelityPromo()))
print(Order(ann, cart, FidelityPromo()))

bananaCart = [LineItem('banana', 30, 0.05), LineItem('apple', 10, 1.5)]
print(Order(joe, bananaCart, BulkItemPromo()))

longOrder = [LineItem(str(item), 1, 1.0) for item in range(10)]
print(Order(joe, longOrder, LargeOrderPromo()))

The above code works perfectly well, but same functionality can be implemented with less code in Python.

Functions-oriented Strategy

Each concrete strategy in our example is a class with a single method, which can be replaced with a simple function.

from abc import ABC, abstractmethod
from collections import namedtuple

Customer = namedtuple('Customer', 'name fidelity')

class LineItem:
    def __init__(self, product, quantity, price):
        self.product = product
        self.quantity = quantity
        self.price = price

    def total(self):
        return self.price * self.quantity

class Order: # Context
    def __init__(self, customer, cart, promotion=None):
        self.customer = customer
        self.cart = list(cart)
        self.promotion = promotion

    def total(self):
        if not hasattr(self, '__total'):
            self.__total = sum(item.total() for item in self.cart)
            return self.__total

    def due(self):
        discount = 0 if self.promotion is None else self.promotion(self)

        return self.total() - discount

    def __repr__(self):
        fmt = '<Order total: {:.2f} due: {:.2f}>'
        return fmt.format(self.total(), self.due())

def fidelityPromo(order):
    """
    5% discount for customers with 1000 or more fidelity points
    """
    return order.total() * 0.05 if order.customer.fidelity >= 1000 else 0

def bulkItemPromo(order):
    """
    10% discount for each LineItem with 20 or more units
    """
    discount = 0
    for item in order.cart:
        if item.quantity >= 20:
            discount += item.total() * 0.1

    return discount

def largeOrderPromo(order):
    """
    7% discount for orders with 10 or more distinct items
    """
    distinctItems = {item.product for item in order.cart}
    if len(distinctItems) >= 10:
        return order.total() * 0.07

    return 0

joe = Customer('John Doe', 0)
ann = Customer('Ann Smith', 1100)
cart = [LineItem('banana', 4, 0.5),
        LineItem('apple', 10, 1.5),
        LineItem('watermellon', 5, 5.0)]

print(Order(joe, cart, fidelityPromo))
print(Order(ann, cart, fidelityPromo))

bananaCart = [LineItem('banana', 30, 0.05), LineItem('apple', 10, 1.5)]
print(Order(joe, bananaCart, bulkItemPromo))

longOrder = [LineItem(str(item), 1, 1.0) for item in range(10)]
print(Order(joe, longOrder, largeOrderPromo))

There is no need to instantiate a new promotion object with each new order: the functions are ready to use.

Reference

Fluent Python