Tip
Just allow it
Generally, it's considered better Python style to simply permit any type of data to be used.
We'll return to this in Chapter 4, The ABCs of Consistent Design.
The question is this: why restrict potential future use cases?
And the usual answer is that there's no good reason to restrict potential future use cases.
Rather than prevent a sensible, but possibly unforeseen, use case, we can provide documentation, testing, and debug logging to help other programmers understand any restrictions on the types that can be processed. We have to provide the documentation, logging, and test cases anyway, so there's minimal additional work involved.
The following is an example docstring that provides the expectations of the class:
class Player: def __init__( self, table, bet_strategy, game_strategy ): """Creates a new player associated with a table, and configured with proper betting and play strategies :param table: an instance of :class:`Table` :param bet_strategy: an instance of :class:`BettingStrategy` :param game_strategy: an instance of :class:`GameStrategy` """ self.bet_strategy = bet_strategy self.game_strategy = game_strategy self.table= table
The programmer using this class has been warned about what the type restrictions are. The use of other types is permitted. If the type isn't compatible with the expected type, then things will break. Ideally, we'll use too like unittest
or doctest
to uncover the breakage.