ch08, 09, 10: example files

This commit is contained in:
Luciano Ramalho
2020-06-11 14:58:15 -03:00
parent 42861b64d8
commit bf4a2be8b9
111 changed files with 4707 additions and 0 deletions

View File

@@ -0,0 +1,77 @@
Sample code for Chapter 10 - "Design patterns with first class functions"
From the book "Fluent Python" by Luciano Ramalho (O'Reilly, 2015)
http://shop.oreilly.com/product/0636920032519.do
Notes
=====
No issues on file with zero type hints
--------------------------------------
Running Mypy on ``classic_strategy.py`` from the first edition, with no
type hints::
$ mypy classic_strategy.py
Success: no issues found in 1 source file
Type inference at play
----------------------
When the ``Order.due`` method made first assignment to discount as ``discount = 0``,
Mypy complained::
mypy classic_strategy.py
classic_strategy.py:68: error: Incompatible types in assignment (expression has type "float", variable has type "int")
Found 1 error in 1 file (checked 1 source file)
To fix it, I made the first assigment as ``discount = 0``.
I never explicitly declared a type for ``discount``.
Mypy ignores functions with no annotations
------------------------------------------
Mypy did not raise any issues with this test case::
def test_bulk_item_promo_with_discount(customer_fidelity_0):
cart = [LineItem('banana', 30, .5),
LineItem('apple', 10, 1.5)]
order = Order(customer_fidelity_0, 10, BulkItemPromo())
assert order.total() == 30.0
assert order.due() == 28.5
The second argument to ``Order`` is declared as ``Sequence[LineItem]``.
Mypy only checks the body of a function the signature as at least one annotation,
like this::
def test_bulk_item_promo_with_discount(customer_fidelity_0) -> None:
cart = [LineItem('banana', 30, .5),
LineItem('apple', 10, 1.5)]
order = Order(customer_fidelity_0, 10, BulkItemPromo())
assert order.total() == 30.0
assert order.due() == 28.5
Now Mypy complains that "Argument 2 of Order has incompatible type".
However, even with the annotation in the test function signature,
Mypy did not find any problem when I mistyped the name of the ``cart`` argument.
Here, ``cart_plain`` should be ``cart``::
def test_bulk_item_promo_with_discount(customer_fidelity_0) -> None:
cart = [LineItem('banana', 30, .5),
LineItem('apple', 10, 1.5)]
order = Order(customer_fidelity_0, cart_plain, BulkItemPromo())
assert order.total() == 30.0
assert order.due() == 28.5
Hypotesis: ``cart_plain`` is a function decorated with ``@pytest.fixture``,
and at the top of the test file I told Mypy to ignore the Pytest import::
import pytest # type: ignore

View File

@@ -0,0 +1,113 @@
# classic_strategy.py
# Strategy pattern -- classic implementation
"""
# tag::CLASSIC_STRATEGY_TESTS[]
>>> joe = Customer('John Doe', 0) # <1>
>>> ann = Customer('Ann Smith', 1100)
>>> cart = [LineItem('banana', 4, .5), # <2>
... LineItem('apple', 10, 1.5),
... LineItem('watermellon', 5, 5.0)]
>>> Order(joe, cart, FidelityPromo()) # <3>
<Order total: 42.00 due: 42.00>
>>> Order(ann, cart, FidelityPromo()) # <4>
<Order total: 42.00 due: 39.90>
>>> banana_cart = [LineItem('banana', 30, .5), # <5>
... LineItem('apple', 10, 1.5)]
>>> Order(joe, banana_cart, BulkItemPromo()) # <6>
<Order total: 30.00 due: 28.50>
>>> big_cart = [LineItem(str(item_code), 1, 1.0) # <7>
... for item_code in range(10)]
>>> Order(joe, big_cart, LargeOrderPromo()) # <8>
<Order total: 10.00 due: 9.30>
>>> Order(joe, cart, LargeOrderPromo())
<Order total: 42.00 due: 42.00>
# end::CLASSIC_STRATEGY_TESTS[]
"""
# tag::CLASSIC_STRATEGY[]
from abc import ABC, abstractmethod
import typing
from typing import Sequence, Optional
class Customer(typing.NamedTuple):
name: str
fidelity: int
class LineItem:
def __init__(self, product: str, quantity: int, price: float):
self.product = product
self.quantity = quantity
self.price = price
def total(self):
return self.price * self.quantity
class Order: # the Context
def __init__(
self,
customer: Customer,
cart: Sequence[LineItem],
promotion: Optional['Promotion'] = None,
):
self.customer = customer
self.cart = list(cart)
self.promotion = promotion
def total(self) -> float:
if not hasattr(self, '__total'):
self.__total = sum(item.total() for item in self.cart)
return self.__total
def due(self) -> float:
if self.promotion is None:
discount = 0.0
else:
discount = 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: Order) -> float:
"""Return discount as a positive dollar amount"""
class FidelityPromo(Promotion): # first Concrete Strategy
"""5% discount for customers with 1000 or more fidelity points"""
def discount(self, order: Order) -> float:
return order.total() * 0.05 if order.customer.fidelity >= 1000 else 0
class BulkItemPromo(Promotion): # second Concrete Strategy
"""10% discount for each LineItem with 20 or more units"""
def discount(self, order: Order) -> float:
discount = 0
for item in order.cart:
if item.quantity >= 20:
discount += item.total() * 0.1
return discount
class LargeOrderPromo(Promotion): # third Concrete Strategy
"""7% discount for orders with 10 or more distinct items"""
def discount(self, order: Order) -> float:
distinct_items = {item.product for item in order.cart}
if len(distinct_items) >= 10:
return order.total() * 0.07
return 0
# end::CLASSIC_STRATEGY[]

View File

@@ -0,0 +1,63 @@
from typing import List
import pytest # type: ignore
from classic_strategy import Customer, LineItem, Order
from classic_strategy import FidelityPromo, BulkItemPromo, LargeOrderPromo
@pytest.fixture
def customer_fidelity_0() -> Customer:
return Customer('John Doe', 0)
@pytest.fixture
def customer_fidelity_1100() -> Customer:
return Customer('Ann Smith', 1100)
@pytest.fixture
def cart_plain() -> List[LineItem]:
return [
LineItem('banana', 4, 0.5),
LineItem('apple', 10, 1.5),
LineItem('watermellon', 5, 5.0),
]
def test_fidelity_promo_no_discount(customer_fidelity_0, cart_plain) -> None:
order = Order(customer_fidelity_0, cart_plain, FidelityPromo())
assert order.total() == 42.0
assert order.due() == 42.0
def test_fidelity_promo_with_discount(customer_fidelity_1100, cart_plain) -> None:
order = Order(customer_fidelity_1100, cart_plain, FidelityPromo())
assert order.total() == 42.0
assert order.due() == 39.9
def test_bulk_item_promo_no_discount(customer_fidelity_0, cart_plain) -> None:
order = Order(customer_fidelity_0, cart_plain, BulkItemPromo())
assert order.total() == 42.0
assert order.due() == 42.0
def test_bulk_item_promo_with_discount(customer_fidelity_0) -> None:
cart = [LineItem('banana', 30, 0.5), LineItem('apple', 10, 1.5)]
order = Order(customer_fidelity_0, cart, BulkItemPromo())
assert order.total() == 30.0
assert order.due() == 28.5
def test_large_order_promo_no_discount(customer_fidelity_0, cart_plain) -> None:
order = Order(customer_fidelity_0, cart_plain, LargeOrderPromo())
assert order.total() == 42.0
assert order.due() == 42.0
def test_large_order_promo_with_discount(customer_fidelity_0) -> None:
cart = [LineItem(str(item_code), 1, 1.0) for item_code in range(10)]
order = Order(customer_fidelity_0, cart, LargeOrderPromo())
assert order.total() == 10.0
assert order.due() == 9.3

View File

@@ -0,0 +1,110 @@
# classic_strategy.py
# Strategy pattern -- classic implementation
"""
# tag::CLASSIC_STRATEGY_TESTS[]
>>> joe = Customer('John Doe', 0) # <1>
>>> ann = Customer('Ann Smith', 1100)
>>> cart = [LineItem('banana', 4, .5), # <2>
... LineItem('apple', 10, 1.5),
... LineItem('watermellon', 5, 5.0)]
>>> Order(joe, cart, FidelityPromo()) # <3>
<Order total: 42.00 due: 42.00>
>>> Order(ann, cart, FidelityPromo()) # <4>
<Order total: 42.00 due: 39.90>
>>> banana_cart = [LineItem('banana', 30, .5), # <5>
... LineItem('apple', 10, 1.5)]
>>> Order(joe, banana_cart, BulkItemPromo()) # <6>
<Order total: 30.00 due: 28.50>
>>> long_order = [LineItem(str(item_code), 1, 1.0) # <7>
... for item_code in range(10)]
>>> Order(joe, long_order, LargeOrderPromo()) # <8>
<Order total: 10.00 due: 9.30>
>>> Order(joe, cart, LargeOrderPromo())
<Order total: 42.00 due: 42.00>
# end::CLASSIC_STRATEGY_TESTS[]
"""
# tag::CLASSIC_STRATEGY[]
from abc import ABC, abstractmethod
from collections import namedtuple
import typing
class Customer(typing.NamedTuple):
name: str
fidelity: int
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: # the 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):
if self.promotion is None:
discount = 0
else:
discount = 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): # first Concrete Strategy
"""5% discount for customers with 1000 or more fidelity points"""
def discount(self, order):
return order.total() * .05 if order.customer.fidelity >= 1000 else 0
class BulkItemPromo(Promotion): # second Concrete Strategy
"""10% discount for each LineItem with 20 or more units"""
def discount(self, order):
discount = 0
for item in order.cart:
if item.quantity >= 20:
discount += item.total() * .1
return discount
class LargeOrderPromo(Promotion): # third Concrete Strategy
"""7% discount for orders with 10 or more distinct items"""
def discount(self, order):
distinct_items = {item.product for item in order.cart}
if len(distinct_items) >= 10:
return order.total() * .07
return 0
# end::CLASSIC_STRATEGY[]

View File

@@ -0,0 +1,33 @@
from typing import (
List,
Optional,
Union,
)
class BulkItemPromo:
def discount(self, order: Order) -> Union[float, int]: ...
class FidelityPromo:
def discount(self, order: Order) -> Union[float, int]: ...
class LargeOrderPromo:
def discount(self, order: Order) -> Union[float, int]: ...
class LineItem:
def __init__(self, product: str, quantity: int, price: float) -> None: ...
def total(self) -> float: ...
class Order:
def __init__(
self,
customer: Customer,
cart: List[LineItem],
promotion: Optional[Union[BulkItemPromo, LargeOrderPromo, FidelityPromo]] = ...
) -> None: ...
def due(self) -> float: ...
def total(self) -> float: ...

View File

@@ -0,0 +1,63 @@
from typing import List
import pytest # type: ignore
from classic_strategy import Customer, LineItem, Order
from classic_strategy import FidelityPromo, BulkItemPromo, LargeOrderPromo
@pytest.fixture
def customer_fidelity_0() -> Customer:
return Customer('John Doe', 0)
@pytest.fixture
def customer_fidelity_1100() -> Customer:
return Customer('Ann Smith', 1100)
@pytest.fixture
def cart_plain() -> List[LineItem]:
return [LineItem('banana', 4, .5),
LineItem('apple', 10, 1.5),
LineItem('watermellon', 5, 5.0)]
def test_fidelity_promo_no_discount(customer_fidelity_0, cart_plain) -> None:
order = Order(customer_fidelity_0, cart_plain, FidelityPromo())
assert order.total() == 42.0
assert order.due() == 42.0
def test_fidelity_promo_with_discount(customer_fidelity_1100, cart_plain) -> None:
order = Order(customer_fidelity_1100, cart_plain, FidelityPromo())
assert order.total() == 42.0
assert order.due() == 39.9
def test_bulk_item_promo_no_discount(customer_fidelity_0, cart_plain) -> None:
order = Order(customer_fidelity_0, cart_plain, BulkItemPromo())
assert order.total() == 42.0
assert order.due() == 42.0
def test_bulk_item_promo_with_discount(customer_fidelity_0) -> None:
cart = [LineItem('banana', 30, .5),
LineItem('apple', 10, 1.5)]
order = Order(customer_fidelity_0, cart, BulkItemPromo())
assert order.total() == 30.0
assert order.due() == 28.5
def test_large_order_promo_no_discount(customer_fidelity_0, cart_plain) -> None:
order = Order(customer_fidelity_0, cart_plain, LargeOrderPromo())
assert order.total() == 42.0
assert order.due() == 42.0
def test_large_order_promo_with_discount(customer_fidelity_0) -> None:
cart = [LineItem(str(item_code), 1, 1.0)
for item_code in range(10)]
order = Order(customer_fidelity_0, cart, LargeOrderPromo())
assert order.total() == 10.0
assert order.due() == 9.3

View File

@@ -0,0 +1,2 @@
import pytest
pytest.main(['.'])

View File

@@ -0,0 +1,20 @@
def fidelity_promo(order):
"""5% discount for customers with 1000 or more fidelity points"""
return order.total() * 0.05 if order.customer.fidelity >= 1000 else 0
def bulk_item_promo(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 large_order_promo(order):
"""7% discount for orders with 10 or more distinct items"""
distinct_items = {item.product for item in order.cart}
if len(distinct_items) >= 10:
return order.total() * 0.07
return 0

View File

@@ -0,0 +1,116 @@
# classic_strategy.py
# Strategy pattern -- classic implementation
"""
# tag::CLASSIC_STRATEGY_TESTS[]
>>> joe = Customer('John Doe', 0) # <1>
>>> ann = Customer('Ann Smith', 1100)
>>> cart = [LineItem('banana', 4, .5), # <2>
... LineItem('apple', 10, 1.5),
... LineItem('watermellon', 5, 5.0)]
>>> Order(joe, cart, FidelityPromo()) # <3>
<Order total: 42.00 due: 42.00>
>>> Order(ann, cart, FidelityPromo()) # <4>
<Order total: 42.00 due: 39.90>
>>> banana_cart = [LineItem('banana', 30, .5), # <5>
... LineItem('apple', 10, 1.5)]
>>> Order(joe, banana_cart, BulkItemPromo()) # <6>
<Order total: 30.00 due: 28.50>
>>> long_order = [LineItem(str(item_code), 1, 1.0) # <7>
... for item_code in range(10)]
>>> Order(joe, long_order, LargeOrderPromo()) # <8>
<Order total: 10.00 due: 9.30>
>>> Order(joe, cart, LargeOrderPromo())
<Order total: 42.00 due: 42.00>
# end::CLASSIC_STRATEGY_TESTS[]
"""
# tag::CLASSIC_STRATEGY[]
from abc import ABC, abstractmethod
from collections import namedtuple
import typing
from pytypes import typelogged
class Customer(typing.NamedTuple):
name: str
fidelity: int
@typelogged
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
@typelogged
class Order: # the 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):
if self.promotion is None:
discount = 0
else:
discount = self.promotion.discount(self)
return self.total() - discount
def __repr__(self):
fmt = '<Order total: {:.2f} due: {:.2f}>'
return fmt.format(self.total(), self.due())
@typelogged
class Promotion(ABC): # the Strategy: an abstract base class
@abstractmethod
def discount(self, order):
"""Return discount as a positive dollar amount"""
@typelogged
class FidelityPromo(Promotion): # first Concrete Strategy
"""5% discount for customers with 1000 or more fidelity points"""
def discount(self, order):
return order.total() * .05 if order.customer.fidelity >= 1000 else 0
@typelogged
class BulkItemPromo(Promotion): # second Concrete Strategy
"""10% discount for each LineItem with 20 or more units"""
def discount(self, order):
discount = 0
for item in order.cart:
if item.quantity >= 20:
discount += item.total() * .1
return discount
@typelogged
class LargeOrderPromo(Promotion): # third Concrete Strategy
"""7% discount for orders with 10 or more distinct items"""
def discount(self, order):
distinct_items = {item.product for item in order.cart}
if len(distinct_items) >= 10:
return order.total() * .07
return 0
# end::CLASSIC_STRATEGY[]

View File

@@ -0,0 +1,63 @@
from typing import List
import pytest # type: ignore
from classic_strategy import Customer, LineItem, Order
from classic_strategy import FidelityPromo, BulkItemPromo, LargeOrderPromo
@pytest.fixture
def customer_fidelity_0() -> Customer:
return Customer('John Doe', 0)
@pytest.fixture
def customer_fidelity_1100() -> Customer:
return Customer('Ann Smith', 1100)
@pytest.fixture
def cart_plain() -> List[LineItem]:
return [LineItem('banana', 4, .5),
LineItem('apple', 10, 1.5),
LineItem('watermellon', 5, 5.0)]
def test_fidelity_promo_no_discount(customer_fidelity_0, cart_plain) -> None:
order = Order(customer_fidelity_0, cart_plain, FidelityPromo())
assert order.total() == 42.0
assert order.due() == 42.0
def test_fidelity_promo_with_discount(customer_fidelity_1100, cart_plain) -> None:
order = Order(customer_fidelity_1100, cart_plain, FidelityPromo())
assert order.total() == 42.0
assert order.due() == 39.9
def test_bulk_item_promo_no_discount(customer_fidelity_0, cart_plain) -> None:
order = Order(customer_fidelity_0, cart_plain, BulkItemPromo())
assert order.total() == 42.0
assert order.due() == 42.0
def test_bulk_item_promo_with_discount(customer_fidelity_0) -> None:
cart = [LineItem('banana', 30, .5),
LineItem('apple', 10, 1.5)]
order = Order(customer_fidelity_0, cart, BulkItemPromo())
assert order.total() == 30.0
assert order.due() == 28.5
def test_large_order_promo_no_discount(customer_fidelity_0, cart_plain) -> None:
order = Order(customer_fidelity_0, cart_plain, LargeOrderPromo())
assert order.total() == 42.0
assert order.due() == 42.0
def test_large_order_promo_with_discount(customer_fidelity_0) -> None:
cart = [LineItem(str(item_code), 1, 1.0)
for item_code in range(10)]
order = Order(customer_fidelity_0, cart, LargeOrderPromo())
assert order.total() == 10.0
assert order.due() == 9.3

View File

@@ -0,0 +1,48 @@
"""
Automatically generated stubfile of
/home/luciano/flupy/priv/2e-atlas/code/10-dp-1class-func/pytypes/classic_strategy.py
MD5-Checksum: a02fa3b98639f84a81b87d4f46007d51
This file was generated by pytypes.typelogger v1.0b5
at 2020-05-02T15:50:59.987984.
Type information is based on runtime observations while running
CPython 3.8.2 final 0
/home/luciano/flupy/venv-3.8/bin/python3
/home/luciano/flupy/venv-3.8/bin/pytest
WARNING:
If you edit this file, be aware that it was automatically generated.
Save your customized version to a distinct place;
this file might be overwritten without notice.
"""
from classic_strategy import Customer, Promotion
from typing import Union
class LineItem(object):
def __init__(self, product: str, quantity: int, price: float) -> None: ...
def total(self) -> float: ...
class Order(object):
def __init__(self, customer: Customer, cart: List[LineItem], promotion: Union[BulkItemPromo, FidelityPromo, LargeOrderPromo]) -> None: ...
def total(self) -> float: ...
def due(self) -> float: ...
class FidelityPromo(Promotion):
def discount(self, order: Order) -> float: ...
class BulkItemPromo(Promotion):
def discount(self, order: Order) -> float: ...
class LargeOrderPromo(Promotion):
def discount(self, order: Order) -> float: ...

View File

@@ -0,0 +1,13 @@
mypy==0.770
mypy-extensions==0.4.3
typed-ast==1.4.1
typing-extensions==3.7.4.1
attrs==19.3.0
more-itertools==8.2.0
packaging==20.3
pluggy==0.13.1
py==1.8.1
pyparsing==2.4.6
pytest==5.4.1
six==1.14.0
wcwidth==0.1.9

View File

@@ -0,0 +1,103 @@
# strategy.py
# Strategy pattern -- function-based implementation
"""
# tag::STRATEGY_TESTS[]
>>> joe = Customer('John Doe', 0) # <1>
>>> ann = Customer('Ann Smith', 1100)
>>> cart = [LineItem('banana', 4, .5),
... LineItem('apple', 10, 1.5),
... LineItem('watermellon', 5, 5.0)]
>>> Order(joe, cart, fidelity_promo) # <2>
<Order total: 42.00 due: 42.00>
>>> Order(ann, cart, fidelity_promo)
<Order total: 42.00 due: 39.90>
>>> banana_cart = [LineItem('banana', 30, .5),
... LineItem('apple', 10, 1.5)]
>>> Order(joe, banana_cart, bulk_item_promo) # <3>
<Order total: 30.00 due: 28.50>
>>> big_cart = [LineItem(str(item_code), 1, 1.0)
... for item_code in range(10)]
>>> Order(joe, big_cart, large_order_promo)
<Order total: 10.00 due: 9.30>
>>> Order(joe, cart, large_order_promo)
<Order total: 42.00 due: 42.00>
# end::STRATEGY_TESTS[]
"""
# tag::STRATEGY[]
import typing
from typing import Sequence, Optional, Callable
class Customer(typing.NamedTuple):
name: str
fidelity: int
class LineItem:
def __init__(self, product: str, quantity: int, price: float):
self.product = product
self.quantity = quantity
self.price = price
def total(self):
return self.price * self.quantity
class Order: # the Context
def __init__(
self,
customer: Customer,
cart: Sequence[LineItem],
promotion: Optional[Callable[['Order'], float]] = None,
) -> None:
self.customer = customer
self.cart = list(cart)
self.promotion = promotion
def total(self) -> float:
if not hasattr(self, '__total'):
self.__total = sum(item.total() for item in self.cart)
return self.__total
def due(self) -> float:
if self.promotion is None:
discount = 0.0
else:
discount = self.promotion(self) # <1>
return self.total() - discount
def __repr__(self):
fmt = '<Order total: {:.2f} due: {:.2f}>'
return fmt.format(self.total(), self.due())
# <2>
def fidelity_promo(order: Order) -> float: # <3>
"""5% discount for customers with 1000 or more fidelity points"""
return order.total() * 0.05 if order.customer.fidelity >= 1000 else 0
def bulk_item_promo(order: 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 large_order_promo(order: Order):
"""7% discount for orders with 10 or more distinct items"""
distinct_items = {item.product for item in order.cart}
if len(distinct_items) >= 10:
return order.total() * 0.07
return 0
# end::STRATEGY[]

View File

@@ -0,0 +1,42 @@
# strategy_best.py
# Strategy pattern -- function-based implementation
# selecting best promotion from static list of functions
"""
>>> joe = Customer('John Doe', 0)
>>> ann = Customer('Ann Smith', 1100)
>>> cart = [LineItem('banana', 4, .5),
... LineItem('apple', 10, 1.5),
... LineItem('watermellon', 5, 5.0)]
>>> banana_cart = [LineItem('banana', 30, .5),
... LineItem('apple', 10, 1.5)]
>>> big_cart = [LineItem(str(item_code), 1, 1.0)
... for item_code in range(10)]
# tag::STRATEGY_BEST_TESTS[]
>>> Order(joe, big_cart, best_promo) # <1>
<Order total: 10.00 due: 9.30>
>>> Order(joe, banana_cart, best_promo) # <2>
<Order total: 30.00 due: 28.50>
>>> Order(ann, cart, best_promo) # <3>
<Order total: 42.00 due: 39.90>
# end::STRATEGY_BEST_TESTS[]
"""
from strategy import Customer, LineItem, Order
from strategy import fidelity_promo, bulk_item_promo, large_order_promo
# tag::STRATEGY_BEST[]
promos = [fidelity_promo, bulk_item_promo, large_order_promo] # <1>
def best_promo(order) -> float: # <2>
"""Select best discount available
"""
return max(promo(order) for promo in promos) # <3>
# end::STRATEGY_BEST[]

View File

@@ -0,0 +1,113 @@
# strategy_best2.py
# Strategy pattern -- function-based implementation
# selecting best promotion from current module globals
"""
>>> joe = Customer('John Doe', 0)
>>> ann = Customer('Ann Smith', 1100)
>>> cart = [LineItem('banana', 4, .5),
... LineItem('apple', 10, 1.5),
... LineItem('watermellon', 5, 5.0)]
>>> Order(joe, cart, fidelity_promo)
<Order total: 42.00 due: 42.00>
>>> Order(ann, cart, fidelity_promo)
<Order total: 42.00 due: 39.90>
>>> banana_cart = [LineItem('banana', 30, .5),
... LineItem('apple', 10, 1.5)]
>>> Order(joe, banana_cart, bulk_item_promo)
<Order total: 30.00 due: 28.50>
>>> long_order = [LineItem(str(item_code), 1, 1.0)
... for item_code in range(10)]
>>> Order(joe, long_order, large_order_promo)
<Order total: 10.00 due: 9.30>
>>> Order(joe, cart, large_order_promo)
<Order total: 42.00 due: 42.00>
# tag::STRATEGY_BEST_TESTS[]
>>> Order(joe, long_order, best_promo)
<Order total: 10.00 due: 9.30>
>>> Order(joe, banana_cart, best_promo)
<Order total: 30.00 due: 28.50>
>>> Order(ann, cart, best_promo)
<Order total: 42.00 due: 39.90>
# end::STRATEGY_BEST_TESTS[]
"""
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: # the 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):
if self.promotion is None:
discount = 0
else:
discount = self.promotion(self)
return self.total() - discount
def __repr__(self):
fmt = '<Order total: {:.2f} due: {:.2f}>'
return fmt.format(self.total(), self.due())
def fidelity_promo(order):
"""5% discount for customers with 1000 or more fidelity points"""
return order.total() * 0.05 if order.customer.fidelity >= 1000 else 0
def bulk_item_promo(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 large_order_promo(order):
"""7% discount for orders with 10 or more distinct items"""
distinct_items = {item.product for item in order.cart}
if len(distinct_items) >= 10:
return order.total() * 0.07
return 0
# tag::STRATEGY_BEST2[]
promos = [
globals()[name]
for name in globals() # <1>
if name.endswith('_promo') and name != 'best_promo' # <2>
] # <3>
def best_promo(order):
"""Select best discount available
"""
return max(promo(order) for promo in promos) # <4>
# end::STRATEGY_BEST2[]

View File

@@ -0,0 +1,91 @@
# strategy_best3.py
# Strategy pattern -- function-based implementation
# selecting best promotion from imported module
"""
>>> from promotions import *
>>> joe = Customer('John Doe', 0)
>>> ann = Customer('Ann Smith', 1100)
>>> cart = [LineItem('banana', 4, .5),
... LineItem('apple', 10, 1.5),
... LineItem('watermellon', 5, 5.0)]
>>> Order(joe, cart, fidelity_promo)
<Order total: 42.00 due: 42.00>
>>> Order(ann, cart, fidelity_promo)
<Order total: 42.00 due: 39.90>
>>> banana_cart = [LineItem('banana', 30, .5),
... LineItem('apple', 10, 1.5)]
>>> Order(joe, banana_cart, bulk_item_promo)
<Order total: 30.00 due: 28.50>
>>> long_order = [LineItem(str(item_code), 1, 1.0)
... for item_code in range(10)]
>>> Order(joe, long_order, large_order_promo)
<Order total: 10.00 due: 9.30>
>>> Order(joe, cart, large_order_promo)
<Order total: 42.00 due: 42.00>
# tag::STRATEGY_BEST_TESTS[]
>>> Order(joe, long_order, best_promo)
<Order total: 10.00 due: 9.30>
>>> Order(joe, banana_cart, best_promo)
<Order total: 30.00 due: 28.50>
>>> Order(ann, cart, best_promo)
<Order total: 42.00 due: 39.90>
# end::STRATEGY_BEST_TESTS[]
"""
from collections import namedtuple
import inspect
import promotions
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: # the 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):
if self.promotion is None:
discount = 0
else:
discount = self.promotion(self)
return self.total() - discount
def __repr__(self):
fmt = '<Order total: {:.2f} due: {:.2f}>'
return fmt.format(self.total(), self.due())
# tag::STRATEGY_BEST3[]
promos = [func for name, func in inspect.getmembers(promotions, inspect.isfunction)]
def best_promo(order):
"""Select best discount available
"""
return max(promo(order) for promo in promos)
# end::STRATEGY_BEST3[]

View File

@@ -0,0 +1,122 @@
# strategy_best4.py
# Strategy pattern -- function-based implementation
# selecting best promotion from list of functions
# registered by a decorator
"""
>>> joe = Customer('John Doe', 0)
>>> ann = Customer('Ann Smith', 1100)
>>> cart = [LineItem('banana', 4, .5),
... LineItem('apple', 10, 1.5),
... LineItem('watermellon', 5, 5.0)]
>>> Order(joe, cart, fidelity)
<Order total: 42.00 due: 42.00>
>>> Order(ann, cart, fidelity)
<Order total: 42.00 due: 39.90>
>>> banana_cart = [LineItem('banana', 30, .5),
... LineItem('apple', 10, 1.5)]
>>> Order(joe, banana_cart, bulk_item)
<Order total: 30.00 due: 28.50>
>>> long_order = [LineItem(str(item_code), 1, 1.0)
... for item_code in range(10)]
>>> Order(joe, long_order, large_order)
<Order total: 10.00 due: 9.30>
>>> Order(joe, cart, large_order)
<Order total: 42.00 due: 42.00>
# tag::STRATEGY_BEST_TESTS[]
>>> Order(joe, long_order, best_promo)
<Order total: 10.00 due: 9.30>
>>> Order(joe, banana_cart, best_promo)
<Order total: 30.00 due: 28.50>
>>> Order(ann, cart, best_promo)
<Order total: 42.00 due: 39.90>
# end::STRATEGY_BEST_TESTS[]
"""
from collections import namedtuple
from typing import Callable, List
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: # the 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):
if self.promotion is None:
discount = 0
else:
discount = self.promotion(self)
return self.total() - discount
def __repr__(self):
fmt = '<Order total: {:.2f} due: {:.2f}>'
return fmt.format(self.total(), self.due())
# tag::STRATEGY_BEST4[]
Promotion = Callable[[Order], float] # <2>
def promotion(promo: Promotion) -> Promotion: # <2>
promos.append(promo)
return promo
promos: List[Promotion] = [] # <1>
@promotion # <3>
def fidelity(order: Order) -> float:
"""5% discount for customers with 1000 or more fidelity points"""
return order.total() * 0.05 if order.customer.fidelity >= 1000 else 0
@promotion
def bulk_item(order: Order) -> float:
"""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
@promotion
def large_order(order: Order) -> float:
"""7% discount for orders with 10 or more distinct items"""
distinct_items = {item.product for item in order.cart}
if len(distinct_items) >= 10:
return order.total() * 0.07
return 0
def best_promo(order: Order) -> float: # <4>
"""Select best discount available
"""
return max(promo(order) for promo in promos)
# end::STRATEGY_BEST4[]

View File

@@ -0,0 +1,123 @@
# strategy_param.py
# Strategy pattern -- parametrized with closure
"""
>>> joe = Customer('John Doe', 0)
>>> ann = Customer('Ann Smith', 1100)
>>> cart = [LineItem('banana', 4, .5),
... LineItem('apple', 10, 1.5),
... LineItem('watermellon', 5, 5.0)]
>>> Order(joe, cart, fidelity_promo(10))
<Order total: 42.00 due: 42.00>
>>> Order(ann, cart, fidelity_promo(10))
<Order total: 42.00 due: 37.80>
>>> banana_cart = [LineItem('banana', 30, .5),
... LineItem('apple', 10, 1.5)]
>>> Order(joe, banana_cart, bulk_item_promo(10))
<Order total: 30.00 due: 28.50>
>>> big_cart = [LineItem(str(item_code), 1, 1.0)
... for item_code in range(10)]
>>> Order(joe, big_cart, LargeOrderPromo(7))
<Order total: 10.00 due: 9.30>
>>> Order(joe, cart, LargeOrderPromo(7))
<Order total: 42.00 due: 42.00>
Using ``partial`` to build a parametrized discounter on the fly::
>>> from functools import partial
>>> Order(joe, cart, partial(general_discount, 5))
<Order total: 42.00 due: 39.90>
"""
import typing
from typing import Sequence, Optional, Callable
class Customer(typing.NamedTuple):
name: str
fidelity: int
class LineItem:
def __init__(self, product: str, quantity: int, price: float):
self.product = product
self.quantity = quantity
self.price = price
def total(self):
return self.price * self.quantity
class Order: # the Context
def __init__(
self,
customer: Customer,
cart: Sequence[LineItem],
promotion: Optional['Promotion'] = None,
):
self.customer = customer
self.cart = list(cart)
self.promotion = promotion
def total(self) -> float:
if not hasattr(self, '__total'):
self.__total = sum(item.total() for item in self.cart)
return self.__total
def due(self) -> float:
if self.promotion is None:
discount = 0.0
else:
discount = self.promotion(self) # <1>
return self.total() - discount
def __repr__(self):
fmt = '<Order total: {:.2f} due: {:.2f}>'
return fmt.format(self.total(), self.due())
# tag::STRATEGY_PARAM[]
Promotion = Callable[[Order], float] # <2>
def fidelity_promo(percent: float) -> Promotion:
"""discount for customers with 1000 or more fidelity points"""
return lambda order: (
order.total() * percent / 100.0 if order.customer.fidelity >= 1000 else 0
)
def bulk_item_promo(percent: float) -> Promotion:
"""discount for each LineItem with 20 or more units"""
def discounter(order: Order) -> float:
discount = 0
for item in order.cart:
if item.quantity >= 20:
discount += item.total() * percent / 100.0
return discount
return discounter
class LargeOrderPromo:
"""discount for orders with 10 or more distinct items"""
def __init__(self, percent: float):
self.percent = percent
def __call__(self, order: Order) -> float:
distinct_items = {item.product for item in order.cart}
if len(distinct_items) >= 10:
return order.total() * self.percent / 100.0
return 0
def general_discount(percent: float, order: Order) -> float:
"""unrestricted discount; usage: ``partial(general_discount, 5)``"""
return order.total() * percent / 100.0
# end::STRATEGY[]

View File

@@ -0,0 +1,54 @@
from typing import List
import functools
import pytest # type: ignore
from strategy_param import Customer, LineItem, Order, Promotion
from strategy_param import fidelity_promo, bulk_item_promo, LargeOrderPromo
from strategy_param import general_discount
@pytest.fixture
def customer_fidelity_0() -> Customer:
return Customer('John Doe', 0)
@pytest.fixture
def customer_fidelity_1100() -> Customer:
return Customer('Ann Smith', 1100)
@pytest.fixture
def cart_plain() -> List[LineItem]:
return [
LineItem('banana', 4, 0.5),
LineItem('apple', 10, 1.5),
LineItem('watermellon', 5, 5.0),
]
def test_fidelity_promo_with_discount(customer_fidelity_1100, cart_plain) -> None:
order = Order(customer_fidelity_1100, cart_plain, fidelity_promo(10))
assert order.total() == 42.0
assert order.due() == 37.8
def test_bulk_item_promo_with_discount(customer_fidelity_0) -> None:
cart = [LineItem('banana', 30, 0.5), LineItem('apple', 10, 1.5)]
order = Order(customer_fidelity_0, cart, bulk_item_promo(10))
assert order.total() == 30.0
assert order.due() == 28.5
def test_large_order_promo_with_discount(customer_fidelity_0) -> None:
cart = [LineItem(str(item_code), 1, 1.0) for item_code in range(10)]
order = Order(customer_fidelity_0, cart, LargeOrderPromo(7))
assert order.total() == 10.0
assert order.due() == 9.3
def test_general_discount(customer_fidelity_0, cart_plain) -> None:
general_promo: Promotion = functools.partial(general_discount, 5)
order = Order(customer_fidelity_1100, cart_plain, general_promo)
assert order.total() == 42.0
assert order.due() == 39.9

View File

@@ -0,0 +1,63 @@
from typing import List
import pytest # type: ignore
from strategy import Customer, LineItem, Order
from strategy import fidelity_promo, bulk_item_promo, large_order_promo
@pytest.fixture
def customer_fidelity_0() -> Customer:
return Customer('John Doe', 0)
@pytest.fixture
def customer_fidelity_1100() -> Customer:
return Customer('Ann Smith', 1100)
@pytest.fixture
def cart_plain() -> List[LineItem]:
return [
LineItem('banana', 4, 0.5),
LineItem('apple', 10, 1.5),
LineItem('watermellon', 5, 5.0),
]
def test_fidelity_promo_no_discount(customer_fidelity_0, cart_plain) -> None:
order = Order(customer_fidelity_0, cart_plain, fidelity_promo)
assert order.total() == 42.0
assert order.due() == 42.0
def test_fidelity_promo_with_discount(customer_fidelity_1100, cart_plain) -> None:
order = Order(customer_fidelity_1100, cart_plain, fidelity_promo)
assert order.total() == 42.0
assert order.due() == 39.9
def test_bulk_item_promo_no_discount(customer_fidelity_0, cart_plain) -> None:
order = Order(customer_fidelity_0, cart_plain, bulk_item_promo)
assert order.total() == 42.0
assert order.due() == 42.0
def test_bulk_item_promo_with_discount(customer_fidelity_0) -> None:
cart = [LineItem('banana', 30, 0.5), LineItem('apple', 10, 1.5)]
order = Order(customer_fidelity_0, cart, bulk_item_promo)
assert order.total() == 30.0
assert order.due() == 28.5
def test_large_order_promo_no_discount(customer_fidelity_0, cart_plain) -> None:
order = Order(customer_fidelity_0, cart_plain, large_order_promo)
assert order.total() == 42.0
assert order.due() == 42.0
def test_large_order_promo_with_discount(customer_fidelity_0) -> None:
cart = [LineItem(str(item_code), 1, 1.0) for item_code in range(10)]
order = Order(customer_fidelity_0, cart, large_order_promo)
assert order.total() == 10.0
assert order.due() == 9.3

View File

@@ -0,0 +1,106 @@
# classic_strategy.py
# Strategy pattern -- classic implementation
"""
# tag::CLASSIC_STRATEGY_TESTS[]
>>> joe = Customer('John Doe', 0) # <1>
>>> ann = Customer('Ann Smith', 1100)
>>> cart = [LineItem('banana', 4, .5), # <2>
... LineItem('apple', 10, 1.5),
... LineItem('watermellon', 5, 5.0)]
>>> Order(joe, cart, FidelityPromo()) # <3>
<Order total: 42.00 due: 42.00>
>>> Order(ann, cart, FidelityPromo()) # <4>
<Order total: 42.00 due: 39.90>
>>> banana_cart = [LineItem('banana', 30, .5), # <5>
... LineItem('apple', 10, 1.5)]
>>> Order(joe, banana_cart, BulkItemPromo()) # <6>
<Order total: 30.00 due: 28.50>
>>> long_order = [LineItem(str(item_code), 1, 1.0) # <7>
... for item_code in range(10)]
>>> Order(joe, long_order, LargeOrderPromo()) # <8>
<Order total: 10.00 due: 9.30>
>>> Order(joe, cart, LargeOrderPromo())
<Order total: 42.00 due: 42.00>
# end::CLASSIC_STRATEGY_TESTS[]
"""
# tag::CLASSIC_STRATEGY[]
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: # the 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):
if self.promotion is None:
discount = 0
else:
discount = 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): # first Concrete Strategy
"""5% discount for customers with 1000 or more fidelity points"""
def discount(self, order):
return order.total() * .05 if order.customer.fidelity >= 1000 else 0
class BulkItemPromo(Promotion): # second Concrete Strategy
"""10% discount for each LineItem with 20 or more units"""
def discount(self, order):
discount = 0
for item in order.cart:
if item.quantity >= 20:
discount += item.total() * .1
return discount
class LargeOrderPromo(Promotion): # third Concrete Strategy
"""7% discount for orders with 10 or more distinct items"""
def discount(self, order):
distinct_items = {item.product for item in order.cart}
if len(distinct_items) >= 10:
return order.total() * .07
return 0
# end::CLASSIC_STRATEGY[]

View File

@@ -0,0 +1,20 @@
def fidelity_promo(order):
"""5% discount for customers with 1000 or more fidelity points"""
return order.total() * .05 if order.customer.fidelity >= 1000 else 0
def bulk_item_promo(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() * .1
return discount
def large_order_promo(order):
"""7% discount for orders with 10 or more distinct items"""
distinct_items = {item.product for item in order.cart}
if len(distinct_items) >= 10:
return order.total() * .07
return 0

View File

@@ -0,0 +1,93 @@
# strategy.py
# Strategy pattern -- function-based implementation
"""
# tag::STRATEGY_TESTS[]
>>> joe = Customer('John Doe', 0) # <1>
>>> ann = Customer('Ann Smith', 1100)
>>> cart = [LineItem('banana', 4, .5),
... LineItem('apple', 10, 1.5),
... LineItem('watermellon', 5, 5.0)]
>>> Order(joe, cart, fidelity_promo) # <2>
<Order total: 42.00 due: 42.00>
>>> Order(ann, cart, fidelity_promo)
<Order total: 42.00 due: 39.90>
>>> banana_cart = [LineItem('banana', 30, .5),
... LineItem('apple', 10, 1.5)]
>>> Order(joe, banana_cart, bulk_item_promo) # <3>
<Order total: 30.00 due: 28.50>
>>> long_order = [LineItem(str(item_code), 1, 1.0)
... for item_code in range(10)]
>>> Order(joe, long_order, large_order_promo)
<Order total: 10.00 due: 9.30>
>>> Order(joe, cart, large_order_promo)
<Order total: 42.00 due: 42.00>
# end::STRATEGY_TESTS[]
"""
# tag::STRATEGY[]
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: # the 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):
if self.promotion is None:
discount = 0
else:
discount = self.promotion(self) # <1>
return self.total() - discount
def __repr__(self):
fmt = '<Order total: {:.2f} due: {:.2f}>'
return fmt.format(self.total(), self.due())
# <2>
def fidelity_promo(order): # <3>
"""5% discount for customers with 1000 or more fidelity points"""
return order.total() * .05 if order.customer.fidelity >= 1000 else 0
def bulk_item_promo(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() * .1
return discount
def large_order_promo(order):
"""7% discount for orders with 10 or more distinct items"""
distinct_items = {item.product for item in order.cart}
if len(distinct_items) >= 10:
return order.total() * .07
return 0
# end::STRATEGY[]

View File

@@ -0,0 +1,108 @@
# strategy_best.py
# Strategy pattern -- function-based implementation
# selecting best promotion from static list of functions
"""
>>> joe = Customer('John Doe', 0)
>>> ann = Customer('Ann Smith', 1100)
>>> cart = [LineItem('banana', 4, .5),
... LineItem('apple', 10, 1.5),
... LineItem('watermellon', 5, 5.0)]
>>> Order(joe, cart, fidelity_promo)
<Order total: 42.00 due: 42.00>
>>> Order(ann, cart, fidelity_promo)
<Order total: 42.00 due: 39.90>
>>> banana_cart = [LineItem('banana', 30, .5),
... LineItem('apple', 10, 1.5)]
>>> Order(joe, banana_cart, bulk_item_promo)
<Order total: 30.00 due: 28.50>
>>> long_order = [LineItem(str(item_code), 1, 1.0)
... for item_code in range(10)]
>>> Order(joe, long_order, large_order_promo)
<Order total: 10.00 due: 9.30>
>>> Order(joe, cart, large_order_promo)
<Order total: 42.00 due: 42.00>
# tag::STRATEGY_BEST_TESTS[]
>>> Order(joe, long_order, best_promo) # <1>
<Order total: 10.00 due: 9.30>
>>> Order(joe, banana_cart, best_promo) # <2>
<Order total: 30.00 due: 28.50>
>>> Order(ann, cart, best_promo) # <3>
<Order total: 42.00 due: 39.90>
# end::STRATEGY_BEST_TESTS[]
"""
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: # the 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):
if self.promotion is None:
discount = 0
else:
discount = self.promotion(self)
return self.total() - discount
def __repr__(self):
fmt = '<Order total: {:.2f} due: {:.2f}>'
return fmt.format(self.total(), self.due())
def fidelity_promo(order):
"""5% discount for customers with 1000 or more fidelity points"""
return order.total() * .05 if order.customer.fidelity >= 1000 else 0
def bulk_item_promo(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() * .1
return discount
def large_order_promo(order):
"""7% discount for orders with 10 or more distinct items"""
distinct_items = {item.product for item in order.cart}
if len(distinct_items) >= 10:
return order.total() * .07
return 0
# tag::STRATEGY_BEST[]
promos = [fidelity_promo, bulk_item_promo, large_order_promo] # <1>
def best_promo(order): # <2>
"""Select best discount available
"""
return max(promo(order) for promo in promos) # <3>
# end::STRATEGY_BEST[]

View File

@@ -0,0 +1,110 @@
# strategy_best2.py
# Strategy pattern -- function-based implementation
# selecting best promotion from current module globals
"""
>>> joe = Customer('John Doe', 0)
>>> ann = Customer('Ann Smith', 1100)
>>> cart = [LineItem('banana', 4, .5),
... LineItem('apple', 10, 1.5),
... LineItem('watermellon', 5, 5.0)]
>>> Order(joe, cart, fidelity_promo)
<Order total: 42.00 due: 42.00>
>>> Order(ann, cart, fidelity_promo)
<Order total: 42.00 due: 39.90>
>>> banana_cart = [LineItem('banana', 30, .5),
... LineItem('apple', 10, 1.5)]
>>> Order(joe, banana_cart, bulk_item_promo)
<Order total: 30.00 due: 28.50>
>>> long_order = [LineItem(str(item_code), 1, 1.0)
... for item_code in range(10)]
>>> Order(joe, long_order, large_order_promo)
<Order total: 10.00 due: 9.30>
>>> Order(joe, cart, large_order_promo)
<Order total: 42.00 due: 42.00>
# tag::STRATEGY_BEST_TESTS[]
>>> Order(joe, long_order, best_promo)
<Order total: 10.00 due: 9.30>
>>> Order(joe, banana_cart, best_promo)
<Order total: 30.00 due: 28.50>
>>> Order(ann, cart, best_promo)
<Order total: 42.00 due: 39.90>
# end::STRATEGY_BEST_TESTS[]
"""
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: # the 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):
if self.promotion is None:
discount = 0
else:
discount = self.promotion(self)
return self.total() - discount
def __repr__(self):
fmt = '<Order total: {:.2f} due: {:.2f}>'
return fmt.format(self.total(), self.due())
def fidelity_promo(order):
"""5% discount for customers with 1000 or more fidelity points"""
return order.total() * .05 if order.customer.fidelity >= 1000 else 0
def bulk_item_promo(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() * .1
return discount
def large_order_promo(order):
"""7% discount for orders with 10 or more distinct items"""
distinct_items = {item.product for item in order.cart}
if len(distinct_items) >= 10:
return order.total() * .07
return 0
# tag::STRATEGY_BEST2[]
promos = [globals()[name] for name in globals() # <1>
if name.endswith('_promo') # <2>
and name != 'best_promo'] # <3>
def best_promo(order):
"""Select best discount available
"""
return max(promo(order) for promo in promos) # <4>
# end::STRATEGY_BEST2[]

View File

@@ -0,0 +1,93 @@
# strategy_best3.py
# Strategy pattern -- function-based implementation
# selecting best promotion from imported module
"""
>>> from promotions import *
>>> joe = Customer('John Doe', 0)
>>> ann = Customer('Ann Smith', 1100)
>>> cart = [LineItem('banana', 4, .5),
... LineItem('apple', 10, 1.5),
... LineItem('watermellon', 5, 5.0)]
>>> Order(joe, cart, fidelity_promo)
<Order total: 42.00 due: 42.00>
>>> Order(ann, cart, fidelity_promo)
<Order total: 42.00 due: 39.90>
>>> banana_cart = [LineItem('banana', 30, .5),
... LineItem('apple', 10, 1.5)]
>>> Order(joe, banana_cart, bulk_item_promo)
<Order total: 30.00 due: 28.50>
>>> long_order = [LineItem(str(item_code), 1, 1.0)
... for item_code in range(10)]
>>> Order(joe, long_order, large_order_promo)
<Order total: 10.00 due: 9.30>
>>> Order(joe, cart, large_order_promo)
<Order total: 42.00 due: 42.00>
# tag::STRATEGY_BEST_TESTS[]
>>> Order(joe, long_order, best_promo)
<Order total: 10.00 due: 9.30>
>>> Order(joe, banana_cart, best_promo)
<Order total: 30.00 due: 28.50>
>>> Order(ann, cart, best_promo)
<Order total: 42.00 due: 39.90>
# end::STRATEGY_BEST_TESTS[]
"""
from collections import namedtuple
import inspect
import promotions
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: # the 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):
if self.promotion is None:
discount = 0
else:
discount = self.promotion(self)
return self.total() - discount
def __repr__(self):
fmt = '<Order total: {:.2f} due: {:.2f}>'
return fmt.format(self.total(), self.due())
# tag::STRATEGY_BEST3[]
promos = [func for name, func in
inspect.getmembers(promotions, inspect.isfunction)]
def best_promo(order):
"""Select best discount available
"""
return max(promo(order) for promo in promos)
# end::STRATEGY_BEST3[]

View File

@@ -0,0 +1,113 @@
# strategy_best4.py
# Strategy pattern -- function-based implementation
# selecting best promotion from list of functions
# registered by a decorator
"""
>>> joe = Customer('John Doe', 0)
>>> ann = Customer('Ann Smith', 1100)
>>> cart = [LineItem('banana', 4, .5),
... LineItem('apple', 10, 1.5),
... LineItem('watermellon', 5, 5.0)]
>>> Order(joe, cart, fidelity)
<Order total: 42.00 due: 42.00>
>>> Order(ann, cart, fidelity)
<Order total: 42.00 due: 39.90>
>>> banana_cart = [LineItem('banana', 30, .5),
... LineItem('apple', 10, 1.5)]
>>> Order(joe, banana_cart, bulk_item)
<Order total: 30.00 due: 28.50>
>>> long_order = [LineItem(str(item_code), 1, 1.0)
... for item_code in range(10)]
>>> Order(joe, long_order, large_order)
<Order total: 10.00 due: 9.30>
>>> Order(joe, cart, large_order)
<Order total: 42.00 due: 42.00>
# tag::STRATEGY_BEST_TESTS[]
>>> Order(joe, long_order, best_promo)
<Order total: 10.00 due: 9.30>
>>> Order(joe, banana_cart, best_promo)
<Order total: 30.00 due: 28.50>
>>> Order(ann, cart, best_promo)
<Order total: 42.00 due: 39.90>
# end::STRATEGY_BEST_TESTS[]
"""
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: # the 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):
if self.promotion is None:
discount = 0
else:
discount = self.promotion(self)
return self.total() - discount
def __repr__(self):
fmt = '<Order total: {:.2f} due: {:.2f}>'
return fmt.format(self.total(), self.due())
# tag::STRATEGY_BEST4[]
promos = [] # <1>
def promotion(promo_func): # <2>
promos.append(promo_func)
return promo_func
@promotion # <3>
def fidelity(order):
"""5% discount for customers with 1000 or more fidelity points"""
return order.total() * .05 if order.customer.fidelity >= 1000 else 0
@promotion
def bulk_item(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() * .1
return discount
@promotion
def large_order(order):
"""7% discount for orders with 10 or more distinct items"""
distinct_items = {item.product for item in order.cart}
if len(distinct_items) >= 10:
return order.total() * .07
return 0
def best_promo(order): # <4>
"""Select best discount available
"""
return max(promo(order) for promo in promos)
# end::STRATEGY_BEST4[]

View File

@@ -0,0 +1,91 @@
# strategy_param.py
# Strategy pattern -- parametrized with closure
"""
>>> joe = Customer('John Doe', 0)
>>> ann = Customer('Ann Smith', 1100)
>>> cart = [LineItem('banana', 4, .5),
... LineItem('apple', 10, 1.5),
... LineItem('watermellon', 5, 5.0)]
>>> Order(joe, cart, fidelity_promo(10))
<Order total: 42.00 due: 42.00>
>>> Order(ann, cart, fidelity_promo(10))
<Order total: 42.00 due: 37.80>
>>> banana_cart = [LineItem('banana', 30, .5),
... LineItem('apple', 10, 1.5)]
>>> Order(joe, banana_cart, bulk_item_promo(10))
<Order total: 30.00 due: 28.50>
>>> long_order = [LineItem(str(item_code), 1, 1.0)
... for item_code in range(10)]
>>> Order(joe, long_order, large_order_promo(7))
<Order total: 10.00 due: 9.30>
>>> Order(joe, cart, large_order_promo(7))
<Order total: 42.00 due: 42.00>
"""
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: # the 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):
if self.promotion is None:
discount = 0
else:
discount = self.promotion(self) # <1>
return self.total() - discount
def __repr__(self):
fmt = '<Order total: {:.2f} due: {:.2f}>'
return fmt.format(self.total(), self.due())
def fidelity_promo(percent):
"""discount for customers with 1000 or more fidelity points"""
return lambda order: (order.total() * percent/100.0
if order.customer.fidelity >= 1000 else 0)
def bulk_item_promo(percent):
"""discount for each LineItem with 20 or more units"""
def discounter(order):
discount = 0
for item in order.cart:
if item.quantity >= 20:
discount += item.total() * percent/100.0
return discount
return discounter
def large_order_promo(percent):
"""discount for orders with 10 or more distinct items"""
def discounter(order):
distinct_items = {item.product for item in order.cart}
if len(distinct_items) >= 10:
return order.total() * percent / 100.0
return 0
return discounter

View File

@@ -0,0 +1,104 @@
# strategy_param2.py
# Strategy pattern — parametrized with callable
"""
>>> joe = Customer('John Doe', 0)
>>> ann = Customer('Ann Smith', 1100)
>>> cart = [LineItem('banana', 4, .5),
... LineItem('apple', 10, 1.5),
... LineItem('watermellon', 5, 5.0)]
>>> Order(joe, cart, FidelityPromo(10))
<Order total: 42.00 due: 42.00>
>>> Order(ann, cart, FidelityPromo(10))
<Order total: 42.00 due: 37.80>
>>> banana_cart = [LineItem('banana', 30, .5),
... LineItem('apple', 10, 1.5)]
>>> Order(joe, banana_cart, BulkItemPromo(10))
<Order total: 30.00 due: 28.50>
>>> long_order = [LineItem(str(item_code), 1, 1.0)
... for item_code in range(10)]
>>> Order(joe, long_order, LargeOrderPromo(7))
<Order total: 10.00 due: 9.30>
>>> Order(joe, cart, LargeOrderPromo(7))
<Order total: 42.00 due: 42.00>
"""
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: # the 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):
if self.promotion is None:
discount = 0
else:
discount = self.promotion(self) # <1>
return self.total() - discount
def __repr__(self):
fmt = '<Order total: {:.2f} due: {:.2f}>'
return fmt.format(self.total(), self.due())
class Promotion():
"""compute discount for order"""
def __init__(self, percent):
self.percent = percent
def __call__(self, order):
raise NotImplementedError("Subclass responsibility")
class FidelityPromo(Promotion):
"""discount for customers with 1000 or more fidelity points"""
def __call__(self, order):
if order.customer.fidelity >= 1000:
return order.total() * self.percent/100.0
return 0
class BulkItemPromo(Promotion):
"""discount for each LineItem with 20 or more units"""
def __call__(self, order):
discount = 0
for item in order.cart:
if item.quantity >= 20:
discount += item.total() * self.percent/100.0
return discount
class LargeOrderPromo(Promotion):
"""discount for orders with 10 or more distinct items"""
def __call__(self, order):
distinct_items = {item.product for item in order.cart}
if len(distinct_items) >= 10:
return order.total() * self.percent / 100.0
return 0