Context manager as a factory

We can create a context manager class, which is a factory for an application object. This gives us a pleasant separation of design considerations without cluttering up an application class with context management features.

Let's say we want a deterministic Deck for dealing in Blackjack. This isn't as useful as it might sound. For unit testing, we'll need a complete mock deck with specific sequences of cards. This has the advantage that the context manager works with the classes we already saw.

We'll extend the simple context manager shown earlier to create a Deck that can be used within the with statement context.

The following is a class that is a factory for Deck and also tweaks the random module:

class Deterministic_Deck:

def __init__(self, *args, **kw) -> None:
self.args = args
self.kw = kw

def __enter__(self) -> Deck:
self.was = random.getstate()
random.seed(0, version=1)
return Deck(*self.args, **self.kw)

def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_value: Optional[BaseException],
traceback: Optional[TracebackType]
) -> Optional[bool]:
random.setstate(self.was)
return False

The preceding context manager class preserves the argument values so that it can create a Deck with the given arguments.

The __enter__() method preserves the old random number state and then sets the random module in a mode that provides a fixed sequence of values. This is used to build and shuffle the deck.

Note that the __enter__() method returns a newly minted Deck object to be used in the with statement context. This is assigned via the as clause in the with statement. The type hint specifies Deck as the return type of this method. The following is a way to use this factory context manager:

with Deterministic_Deck(size=6) as deck: 
    h = Hand(deck.pop(), deck.pop(), deck.pop()) 

The preceding example of code guarantees a specific sequence of cards that we can use for demonstration and testing purposes.

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

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