The Strategy Pattern in Python: Interchangeable Behaviour with Functions and Classes

An examination of the Strategy pattern in Python, from strategy classes and protocols to functions, partial objects and dictionaries of strategies, with its pitfalls and the cases in which it is unnecessary.

A green python draped in tight folds over a thin branch, its head tucked inside a loop of its body against a soft green background.
Photo by Jadon Barnes on Unsplash

A function that decides how to compute a price, how to sort a list or how to compress a file often begins as a chain of if and elif branches, one per variant. Each new variant lengthens the chain and forces a change to code that already works. The Strategy pattern, catalogued in 1994 by Gamma, Helm, Johnson and Vlissides in Design Patterns, answers this problem by moving each variant into an interchangeable object that the main code receives and uses without knowing its details. The present article examines the classic form of the pattern and its far shorter Pythonic form, in which a plain function is the strategy; that brevity is the secret weapon that the language offers for this pattern.

The Problem: One Function, Many Variants

An online shop that applies different discounts to an order illustrates the situation. Each kind of customer receives a different rule, and the first version encodes every rule in the same function.

def final_price(total, customer_type):
    if customer_type == "regular":
        return total
    elif customer_type == "member":
        return total * 0.95
    elif customer_type == "clearance":
        return max(total - 20, 0)
    raise ValueError(f"unknown customer type: {customer_type}")

print(final_price(100, "member"))     # Output: 95.0
print(final_price(100, "clearance"))  # Output: 80

The function works, but it mixes two responsibilities: choosing a rule and applying it. A new promotion requires editing the function, the rules cannot be tested in isolation, and a rule cannot be supplied by another module, such as a plug-in that defines a seasonal campaign.

The Classic Form: Strategy Objects

In the classic form, every rule becomes a class with a common method, and the object that uses it, called the context, depends only on that method. Python 3.8 added typing.Protocol (PEP 544), which describes the common method without requiring inheritance, so any class with a compatible apply method qualifies.

from dataclasses import dataclass
from typing import Protocol

class Discount(Protocol):
    def apply(self, total: float) -> float: ...

class NoDiscount:
    def apply(self, total):
        return total

class Percentage:
    def __init__(self, percent):
        self.percent = percent

    def apply(self, total):
        return total * (1 - self.percent / 100)

class FixedAmount:
    def __init__(self, amount):
        self.amount = amount

    def apply(self, total):
        return max(total - self.amount, 0)

@dataclass
class Order:
    total: float
    discount: Discount

    def final_price(self):
        return round(self.discount.apply(self.total), 2)

for discount in (NoDiscount(), Percentage(5), FixedAmount(20)):
    print(type(discount).__name__, Order(100, discount).final_price())
# Output: NoDiscount 100
# Output: Percentage 95.0
# Output: FixedAmount 80

The class Order no longer contains any rule. A new promotion is a new class, written anywhere, and the context accepts it without modification, which satisfies the open/closed principle. An abstract base class built with abc.ABC and abstractmethod is the traditional alternative to Protocol: it forces explicit inheritance and fails at instantiation when the method is missing, whereas a protocol is checked only by static type checkers.

The Pythonic Form: Functions as Strategies

Every class above has a single method, and a class with a single method is, in practice, a function with extra ceremony. Python functions are first-class objects, as shown in the article devoted to decorators, so they can be stored in an attribute and called later. The same design therefore fits in a few lines.

from dataclasses import dataclass
from functools import partial
from typing import Callable

def no_discount(total):
    return total

def percentage(total, percent):
    return total * (1 - percent / 100)

def fixed_amount(total, amount):
    return max(total - amount, 0)

@dataclass
class Order:
    total: float
    discount: Callable[[float], float] = no_discount

    def final_price(self):
        return round(self.discount(self.total), 2)

print(Order(100).final_price())                                   # Output: 100
print(Order(100, partial(percentage, percent=5)).final_price())   # Output: 95.0
print(Order(100, lambda total: fixed_amount(total, 20)).final_price())  # Output: 80

The parameters that the classes stored in __init__ are now bound with functools.partial or captured by a lambda. The context only needs something callable with one argument, so a function, a partial object, a lambda or an instance of a class that defines __call__ are all valid strategies; the last option remains useful when a strategy must keep state between calls.

Choosing and Replacing Strategies at Runtime

Once the strategies are values, the if chain of the first example becomes a dictionary that maps a configuration key to a strategy. The selection is a lookup, and the strategy of an existing object can be replaced at any moment. Online role-playing games offer a familiar image of this replacement: many of them let a character switch its specialization, for example from protecting the group to healing it, so that its abilities change while the character keeps its name, its equipment and its progress. The order behaves in the same way, keeping its total while its discount changes.

from dataclasses import dataclass
from functools import partial

def no_discount(total):
    return total

def percentage(total, percent):
    return total * (1 - percent / 100)

def fixed_amount(total, amount):
    return max(total - amount, 0)

DISCOUNTS = {
    "regular": no_discount,
    "member": partial(percentage, percent=5),
    "clearance": partial(fixed_amount, amount=20),
}

@dataclass
class Order:
    total: float
    discount: object = no_discount

    def final_price(self):
        return round(self.discount(self.total), 2)

order = Order(100, DISCOUNTS["member"])
print(order.final_price())  # Output: 95.0

order.discount = DISCOUNTS["clearance"]
print(order.final_price())  # Output: 80

best = min(DISCOUNTS, key=lambda name: DISCOUNTS[name](order.total))
print(best)                 # Output: clearance

The comparison stops at this point, because games usually restrict the change of specialization to moments outside combat, whereas a strategy can be replaced between any two calls. The last line adds something that the if chain could not do: since the strategies are ordinary values, the program can iterate over them and choose the most favourable one for the customer.

Strategies in the Standard Library

The standard library applies this pattern constantly, under the name of a parameter rather than under the name of the pattern. The argument key of sorted, min and max, the replacement function of re.sub and the argument default of json.dumps are all strategies that the caller supplies.

words = ["pear", "Fig", "banana"]

print(sorted(words))                 # Output: ['Fig', 'banana', 'pear']
print(sorted(words, key=str.lower))  # Output: ['banana', 'Fig', 'pear']
print(sorted(words, key=len))        # Output: ['Fig', 'pear', 'banana']

The sorting algorithm is the same in the three calls; only the strategy that extracts the comparison key changes. Recognizing this shape in the standard library is the best guide for designing APIs of the same kind: a parameter that receives a function is usually clearer than a parameter that receives the name of a behaviour.

Pitfalls of the Strategy Pattern

The pattern is simple, but its Pythonic form has a few traps of its own. Four pitfalls are distinguished, which are the following:

  1. Functions stored on the class. A plain function assigned as a class attribute becomes a method, so calling it through self passes the instance as an extra argument. The reason lies in the descriptor protocol, examined in the article devoted to descriptors; staticmethod or an instance attribute avoids it.
  2. Late binding in loops. Lambdas created in a loop capture the loop variable, not its value at the time of creation, so all of them see the last value; functools.partial binds the value immediately.
  3. Classes for every rule. A hierarchy of single-method classes adds files and names without adding flexibility; functions are sufficient unless the strategy needs state or several related methods.
  4. A pattern where none is needed. Two stable variants that will never grow are clearer as a single if statement than as a set of interchangeable objects.

The first two pitfalls are reproduced in the following example.

from functools import partial

def double(total):
    return total * 2

class Pricing:
    strategy = double  # Stored on the class: becomes a method.

    def run(self, total):
        return self.strategy(total)

try:
    Pricing().run(10)
except TypeError as error:
    print(error)  # Output: double() takes 1 positional argument but 2 were given

class FixedPricing:
    strategy = staticmethod(double)

    def run(self, total):
        return self.strategy(total)

print(FixedPricing().run(10))  # Output: 20

def percentage(total, percent):
    return total * (1 - percent / 100)

late = [lambda total: percentage(total, p) for p in (5, 10, 15)]
bound = [partial(percentage, percent=p) for p in (5, 10, 15)]
print([strategy(100) for strategy in late])   # Output: [85.0, 85.0, 85.0]
print([strategy(100) for strategy in bound])  # Output: [95.0, 90.0, 85.0]

In the first class, Python turns double into a bound method, so self.strategy(10) becomes double(self, 10). In the list of lambdas, the three functions read the variable p only when they are called, after the loop has finished, so all of them apply a discount of 15 percent.

Choosing the Right Form

Consequently, the form of the pattern depends on what each strategy needs, and the following table summarizes the criteria.

Situation Recommended form
Two or three stable variants that will not grow A plain if statement
Stateless rules, possibly with fixed parameters Functions, with functools.partial for the parameters
Rules selected by configuration or by name A dictionary that maps names to functions
Rules that keep state between calls A class with __call__, or a closure
Strategies with several related operations Classes that follow a Protocol or an abstract base class
Behaviour that depends on the type of the argument functools.singledispatch instead of a strategy

The last row marks the boundary with a related tool. When the variant is determined by the type of a value rather than by a choice of the caller, a generic function, as described in the article devoted to singledispatch, selects the implementation automatically.

Conclusion

It is concluded that the Strategy pattern separates the choice of a behaviour from its use, so that a context such as an order can apply any rule that respects a common interface, and new rules can be added without modifying it. Python reduces the classic hierarchy of classes to its essence, because a function is already an interchangeable object, and the standard library applies that idea every time it accepts a key or a default. This magic carries two obligations: storing the functions where Python does not convert them into methods, and binding their parameters at the moment of creation. Structural pattern matching, introduced in Python 3.10, addresses the opposite situation, in which branching on the shape of the data is the clearest design, and it is developed in a future article of this series.