Designing a module-package hybrid

In some cases, a design evolves into a module that is very complex; it can become so complex that a single file becomes a bad idea. When we start putting billboard comments in a module, it's a hint that we should consider refactoring a complex module into a package built from several smaller modules.

In this case, the package can be as simple as the following kind of structure. We can create a directory, named blackjack; within this directory, the __init__.py file would look like the following example:

"""Blackjack package""" 
from blackjack.cards import Shoe from blackjack.player import Strategy_1, Strategy_2 from blackjack.casino import ReSplit, NoReSplit, NoReSplitAces, Hit17, Stand17 from blackjack.simulator import Table, Player, Simulate from betting import Flat, Martingale, OneThreeTwoSix

This shows us how we can build a module-like package that is actually an assembly of parts imported from subsidiary modules. An overall application could be named simulate.py, containing code that looks like the following:

from blackjack import *
table = Table(
decks=6, limit=500, dealer=Hit17(), split=NoReSplitAces(),
payout=(3,2)) player = Player(
play=Strategy_1(), betting=Martingale(), rounds=100,
stake=100) simulate = Simulate(table, player, 100) for result in simulate: print(result)

This snippet shows us how we can use from blackjack import * to create a number of class definitions that originate in a number of other modules within the blackjack package. Specifically, there's an overall blackjack package that has the following modules within it:

  • The blackjack.cards package contains the Card, Deck, and Shoe definitions.
  • The blackjack.player package contains various strategies for play.
  • The blackjack.casino package contains a number of classes that customize how casino rules vary.
  • The blackjack.simulator package contains the top-level simulation tools.
  • The betting package is also used by the application to define various betting strategies that are not unique to Blackjack but apply to any casino game.

The architecture of this package may simplify how we upgrade or extend our design. If each module is smaller and more focused, it's more readable and more understandable. It may be simpler to update each module in isolation.

Let's see how to design a package with alternate implementations.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset