ruk·si

🐍 Python
Command Pattern

Updated at 2018-11-21 02:22

Command pattern is storing actions to perform in a mutable collection.

Command pattern with first-class functions.

from typing import Callable

class MacroCommand:

    def __init__(self, *args: Callable):
        self.commands = list(args)

    def __call__(self):
        return [command() for command in self.commands]

from functools import partial

f1 = partial(sum, [1, 2])
f2 = partial(sum, [3, 4])
f3 = partial(sum, [5, 6])

mc = MacroCommand(f1, f2, f3)
assert mc() == [3, 7, 11]

Source

  • Python Tricks The Book, Dan Bader
  • Fluent Python, Luciano Ramalho