Python Design Patterns

Strategy Pattern in Python

Swap the algorithm at run time, such as a pricing rule, instead of writing a long if / elif chain.

  • Advanced
  • 2 min read
  • 1 runnable example
What you'll learn
  • Interchangeable algorithms
  • Passing functions as strategies
  • Composition over conditionals
Checkout(member_discount).total(15)
  • Checkout
    • regular_discount
    • member_discount→ 12.00

Plug in the algorithm

Strategy moves varying algorithms behind a common callable or interface and favors composition over conditionals.

Key points

  1. Each strategy is a function or class with the same signature.
  2. The context receives a strategy and calls it.
  3. Adding a new rule means adding a strategy, not editing an if chain.

When should you use it?

  • Solve recurring object-design problems with proven structures.
  • Decouple responsibilities so code is easier to extend and test.
  • Use shared design vocabulary when discussing architecture with a team.

Example code

Run code →
main.py
def regular_discount(total): return total
def member_discount(total): return total * 0.8


class Checkout:
    # Strategy: inject the algorithm that is allowed to vary.
    def __init__(self, discount_strategy):
        self.discount_strategy = discount_strategy

    def total(self, amount):
        # Delegate the varying algorithm to the strategy.
        return self.discount_strategy(amount)


checkout = Checkout(member_discount)
print(f"{checkout.total(15):.2f}")
Get a Run button for this example

Result of running the code

12.00

Code explanation

Checkout delegates discount calculation to the injected strategy function.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Replace the sample domain while preserving the pattern structure.
  2. Compare the pattern with a simpler implementation and explain the tradeoff.
  3. Write tests for each participant before adding another implementation.
Run in the Python compiler →

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges