Home > Articles > Open Source > Python

  • Print
  • + Share This
This chapter is from the book

1.3. Factory Method Pattern

The Factory Method Pattern is intended to be used when we want subclasses to choose which classes they should instantiate when an object is requested. This is useful in its own right, but can be taken further and used in cases where we cannot know the class in advance (e.g., the class to use is based on what we read from a file or depends on user input).

In this section we will review a program that can be used to create game boards (e.g., a checkers or chess board). The program’s output is shown in Figure 1.3, and the four variants of the source code are in the files gameboard1.py...game-board4.py.*star.jpg

We want to have an abstract board class that can be subclassed to create game-specific boards. Each board subclass will populate itself with its initial layout of pieces. And we want every unique kind of piece to belong to its own class (e.g., BlackDraught, WhiteDraught, BlackChessBishop, WhiteChessKnight, etc.). Incidentally, for individual pieces, we have used class names like WhiteDraught rather than, say, WhiteChecker, to match the names used in Unicode for the corresponding characters.

Figure 1.3

Figure 1.3 The checkers and chess game boards on a Linux console

We will begin by reviewing the top-level code that instantiates and prints the boards. Next, we will look at the board classes and some of the piece classes—starting with hard-coded classes. Then we will review some variations that allow us to avoid hard-coding classes and at the same time use fewer lines of code.

def main():
    checkers = CheckersBoard()
    print(checkers)

    chess = ChessBoard()
    print(chess)

This function is common to all versions of the program. It simply creates each type of board and prints it to the console, relying on the AbstractBoard’s __str__() method to convert the board’s internal representation into a string.

BLACK, WHITE = ("BLACK", "WHITE")

class AbstractBoard:

    def  __init__(self, rows, columns):
         self.board = [[None for _ in range(columns)] for _ in range(rows)]
         self.populate_board()

    def populate_board(self):
        raise NotImplementedError()

    def __str__(self):
        squares = []
        for y, row in enumerate(self.board):
            for x, piece in enumerate(row):
                square = console(piece, BLACK if (y + x) % 2 else WHITE)
                squares.append(square)
            squares.append("\n")
        return "".join(squares)

The BLACK and WHITE constants are used here to indicate each square’s background color. In later variants they are also used to indicate each piece’s color. This class is quoted from gameboard1.py, but it is the same in all versions.

It would have been more conventional to specify the constants by writing: BLACK, WHITE = range(2). However, using strings is much more helpful when it comes to debugging error messages, and should be just as fast as using integers thanks to Python’s smart interning and identity checks.

The board is represented by a list of rows of single-character strings—or None for unoccupied squares. The console() function (not shown, but in the source code), returns a string representing the given piece on the given background color. (On Unix-like systems this string includes escape codes to color the background.)

We could have made the AbstractBoard a formally abstract class by giving it a metaclass of abc.ABCMeta (as we did for the AbstractFormBuilder class; 12 left-arrow.jpg). However, here we have chosen to use a different approach, and simply raise a NotImplementedError exception for any methods we want subclasses to reimplement.

class CheckersBoard(AbstractBoard):

    def __init__(self):
        super().__init__(10, 10)

    def populate_board(self):
        for x in range(0, 9, 2):
            for row in range(4):
                column = x + ((row + 1) % 2)
                self.board[row][column] = BlackDraught()
                self.board[row + 6][column] = WhiteDraught()

This subclass is used to create a representation of a 10 × 10 international checkers board. This class’s populate_board() method is not a factory method, since it uses hard-coded classes; it is shown in this form as a step on the way to making it into a factory method.

class ChessBoard(AbstractBoard):

    def __init__(self):
        super().__init__(8, 8)

    def populate_board(self):
        self.board[0][0] = BlackChessRook()
        self.board[0][1] = BlackChessKnight()
        ...
        self.board[7][7] = WhiteChessRook()
        for column in range(8):
            self.board[1][column] = BlackChessPawn()
            self.board[6][column] = WhiteChessPawn()

This version of the ChessBoard’s populate_board() method—just like the Checkers-Board’s one—is not a factory method, but it does illustrate how the chess board is populated.

class Piece(str):

    __slots__ = ()

This class serves as a base class for pieces. We could have simply used str, but that would not have allowed us to determine if an object is a piece (e.g., using isinstance(x, Piece)). Using __slots__ = () ensures that instances have no data, a topic we’ll discuss later on (§2.6, right-arrow.jpg 65).

class BlackDraught(Piece):

    __slots__ = ()

    def __new__(Class):
        return super().__new__(Class, "\N{black draughts man}")

class WhiteChessKing(Piece):

    __slots__ = ()

    def __new__(Class):
        return super().__new__(Class, "\N{white chess king}")

These two classes are models for the pattern used for all the piece classes. Every one is an immutable Piece subclass (itself a str subclass) that is initialized with a one-character string holding the Unicode character that represents the relevant piece. There are fourteen of these tiny subclasses in all, each one differing only by its class name and the string it holds: clearly, it would be nice to eliminate all this near-duplication.

    def populate_board(self):
        for x in range(0, 9, 2):
            for y in range(4):
                column = x + ((y + 1) % 2)
                for row, color in ((y, "black"), (y + 6, "white")):
                    self.board[row][column] = create_piece("draught",
                            color)

This new version of the CheckersBoard.populate_board() method (quoted from gameboard2.py) is a factory method, since it depends on a new create_piece() factory function rather than on hard-coded classes. The create_piece() function returns an object of the appropriate type (e.g., a BlackDraught or a WhiteDraught), depending on its arguments. This version of the program has a similar Chess-Board.populate_board() method (not shown), which also uses string color and piece names and the same create_piece() function.

def create_piece(kind, color):
    if kind == "draught":
        return eval("{}{}()".format(color.title(), kind.title()))
    return eval("{}Chess{}()".format(color.title(), kind.title()))

This factory function uses the built-in eval() function to create class instances. For example, if the arguments are "knight" and "black", the string to be eval()’d will be "BlackChessKnight()". Although this works perfectly well, it is potentially risky since pretty well anything could be eval()’d into existence—we will see a solution, using the built-in type() function, shortly.

for code in itertools.chain((0x26C0, 0x26C2), range(0x2654, 0x2660)):
    char = chr(code)
    name = unicodedata.name(char).title().replace("  ", "")
    if name.endswith("sMan"):
        name = name[:-4]
    exec("""\
class {}(Piece):

    __slots__ = ()

    def __new__(Class):
        return super().__new__(Class,  "{}")""".format(name, char))

Instead of writing the code for fourteen very similar classes, here we create all the classes we need with a single block of code.

The itertools.chain() function takes one or more iterables and returns a single iterable that iterates over the first iterable it was passed, then the second, and so on. Here, we have given it two iterables, the first a 2-tuple of the Unicode code points for black and white checkers pieces, and the second a range-object (in effect, a generator) for the black and white chess pieces.

For each code point we create a single character string (e.g., “horse.jpg”) and then create a class name based on the character’s Unicode name (e.g., “black chess knight” becomes BlackChessKnight). Once we have the character and the name we use exec() to create the class we need. This code block is a mere dozen lines—compared with around a hundred lines for creating all the classes individually.

Unfortunately, though, using exec() is potentially even more risky than using eval(), so we must find a better way.

DRAUGHT, PAWN, ROOK, KNIGHT, BISHOP, KING, QUEEN = ("DRAUGHT", "PAWN",
        "ROOK", "KNIGHT", "BISHOP", "KING", "QUEEN")

class CheckersBoard(AbstractBoard):
    ...

    def populate_board(self):
        for x in range(0, 9, 2):
            for y in range(4):
                column = x + ((y + 1) % 2)
                for row, color in ((y, BLACK), (y + 6, WHITE)):
                    self.board[row][column] = self.create_piece(DRAUGHT,
                            color)

This CheckersBoard.populate_board() method is from gameboard3.py. It differs from the previous version in that the piece and color are both specified using constants rather than easy to mistype string literals. Also, it uses a new create_piece() factory to create each piece.

An alternative CheckersBoard.populate_board() implementation is provided in gameboard4.py (not shown)—this version uses a subtle combination of a list comprehension and a couple of itertools functions.

class AbstractBoard:

    __classForPiece = {(DRAUGHT, BLACK): BlackDraught,
            (PAWN, BLACK): BlackChessPawn,
            ...
            (QUEEN, WHITE): WhiteChessQueen}
    ...
    def create_piece(self, kind, color):
        return AbstractBoard.__classForPiece[kind, color]()

This version of the create_piece() factory (also from gameboard3.py, of course) is a method of the AbstractBoard that the CheckersBoard and ChessBoard classes inherit. It takes two constants and looks them up in a static (i.e., class-level) dictionary whose keys are (piece kind, color) 2-tuples, and whose values are class objects. The looked-up value—a class—is immediately called (using the () call operator), and the resulting piece instance is returned.

The classes in the dictionary could have been individually coded (as they were in gameboard1.py) or created dynamically but riskily (as they were in gameboard2.py). But for gameboard3.py, we have created them dynamically and safely, without using eval() or exec().

for code in itertools.chain((0x26C0, 0x26C2), range(0x2654, 0x2660)):
    char = chr(code)
    name = unicodedata.name(char).title().replace(" ", "")
    if name.endswith("sMan"):
        name = name[:-4]
    new = make_new_method(char)
    Class = type(name, (Piece,), dict(__slots__=(), __new__=new))
    setattr(sys.modules[__name__], name, Class) # Can be done better!

This code has the same overall structure as the code shown earlier for creating the fourteen piece subclasses that the program needs (21 left-arrow.jpg). Only this time instead of using eval() and exec() we take a somewhat safer approach.

Once we have the character and name we create a new function (called new()) by calling a custom make_new_method() function. We then create a new class using the built-in type() function. To create a class this way we must pass in the type’s name, a tuple of its base classes (in this case, there’s just one, Piece), and a dictionary of the class’s attributes. Here, we have set the __slots__ attribute to an empty tuple (to stop the class’s instances having a private __dict__ that isn’t needed), and set the __new__ method attribute to the new() function we have just created.

Finally, we use the built-in setattr() function to add to the current module (sys.modules[__name__]) the newly created class (Class) as an attribute called name (e.g., "WhiteChessPawn"). In gameboard4.py, we have written the last line of this code snippet in a nicer way:

    globals()[name] = Class

Here, we have retrieved a reference to the dict of globals and added a new item whose key is the name held in name, and whose value is our newly created Class. This does exactly the same thing as the setattr() line used in gameboard3.py.

def make_new_method(char): # Needed to create a fresh method each time
    def new(Class): # Can't use super() or super(Piece, Class)
        return Piece.__new__(Class, char)
    return new

This function is used to create a new() function (that will become a class’s __new__() method). We cannot use a super() call since at the time the new() function is created there is no class context for the super() function to access. Note that the Piece class (19 left-arrow.jpg) doesn’t have a __new__() method—but its base class (str) does, so that is the method that will actually be called.

Incidentally, the earlier code block’s new = make_new_method(char) line and the make_new_method() function just shown could both be deleted, so long as the line that called the make_new_method() function was replaced with these:

    new = (lambda char: lambda Class: Piece.__new__(Class, char))(char)
    new.__name__ = "__new__"

Here, we create a function that creates a function and immediately calls the outer function parameterized by char to return a new() function. (This code is used in gameboard4.py.)

All lambda functions are called "lambda", which isn’t very helpful for debugging. So, here, we explicitly give the function the name it should have, once it is created.

    def populate_board(self):
        for row, color in ((0, BLACK), (7, WHITE)):
            for columns, kind in (((0, 7), ROOK), ((1, 6), KNIGHT),
                    ((2, 5), BISHOP), ((3,), QUEEN), ((4,), KING)):
                for column in columns:
                    self.board[row][column] = self.create_piece(kind,
                            color)
        for column in range(8):
            for row, color in ((1, BLACK), (6, WHITE)):
                self.board[row][column] = self.create_piece(PAWN, color)

For completeness, here is the ChessBoard.populate_board() method from game-board3.py (and gameboard4.py). It depends on color and piece constants (which could be provided by a file or come from menu options, rather than being hard-coded). In the gameboard3.py version, this uses the create_piece() factory function shown earlier (22 left-arrow.jpg). But for gameboard4.py, we have used our final create_piece() variant.

def create_piece(kind, color):
    color = "White" if color == WHITE else "Black"
    name = {DRAUGHT: "Draught", PAWN: "ChessPawn", ROOK: "ChessRook",
            KNIGHT: "ChessKnight", BISHOP: "ChessBishop",
            KING: "ChessKing", QUEEN: "ChessQueen"}[kind]
    return globals()[color + name]()

This is the gameboard4.py version’s create_piece() factory function. It uses the same constants as gameboard3.py, but rather than keeping a dictionary of class objects it dynamically finds the relevant class in the dictionary returned by the built-in globals() function. The looked-up class object is immediately called and the resulting piece instance is returned.

  • + Share This
  • 🔖 Save To Your Account