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 completely 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 ): self.args= args self.kw= kw def __enter__( self ): self.was= random.getstate() random.seed( 0, version=1 ) return Deck( *self.args, **self.kw ) def __exit__...