Factories are useful for producing objects without having to store certain data on the objects' type. Instances of this factory class are factories that can produce
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | import contextlib
class Factory:
"""A generic instance factory that tracks the instances.
A Factory must be created with the target type as its only
non-keyword argument.
"""
def __init__(self, *args, **defaults):
self.type, = args
self.defaults = defaults
self.objects = set()
def create(self, **kwargs):
"""Create and track a new instance of the factory's type."""
fullkwargs = self.defaults.copy()
fullkwargs.update(kwargs)
obj = self.type(**fullkwargs)
self.objects.add(obj)
def remove(self, obj):
"""Remove the object."""
# obj.__del__() should call obj.clear()
self.objects.remove(obj)
def clear(self):
"""Delete all the objects."""
for obj in list(self.objects):
self.remove(obj)
@contextlib.contextmanager
def one(self, **kwargs):
"""A context manager for temporary instances."""
device = self.create(**kwargs)
yield device
self.clear(device)
factory = Factory(str, encoding='ascii', errors='replace')
name = factory.create(b"Lancelot")
|
Tags: factory
Looks like the beginning text of this recipe was cut off...