Skip to content

Instantly share code, notes, and snippets.

@eloraburns
Created February 27, 2014 18:10
Show Gist options
  • Save eloraburns/9255557 to your computer and use it in GitHub Desktop.
Save eloraburns/9255557 to your computer and use it in GitHub Desktop.
Strategies, staticmethods, modules, OH MY
# http://en.wikipedia.org/wiki/Strategy_pattern
# class_strategy.py:
# class IntegerStrategy(object):
# @staticmethod
# def add(a, b):
# ...
# class FloatStrategy(object):
# @staticmethod
# def add(a, b):
# ...
# module_strategy/integer_strategy.py:
# def add(a, b):
# ...
# module_strategy/float_strategy.py:
# def add(a, b):
# ...
from class_strategy import IntegerStrategy, FloatStrategy, DecimalFloatStrategy
from module_strategy import integer_strategy, float_strategy, decimal_float_strategy
def f(x, strategy):
y = strategy.add(x, x)
# So do you like:
print f(1, IntegerStrategy)
# Or:
print f(1, integer_strategy)
@wolever
Copy link

wolever commented Feb 27, 2014

… but when you're doing this, you almost always want to have some state along with the strategy, and then you're just using a plain old class-with-methods.

For example, maybe you want to include overflow handling:

class IntegerStrategy(object):
    def __init__(self, overflow="warn"):
        self.overflow = overflow
    def add(self, a, b):
        res = a + b
        if res > sys.maxint:
            if self.overflow == "warn":
                warnings.warn("overflow during addition")
        return res

print f(1, IntegerStrategy())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment