Welcome, guest | Sign In | My Account | Store | Cart

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

Python, 42 lines
 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")

1 comment

Martin Miller 11 years, 10 months ago  # | flag

Looks like the beginning text of this recipe was cut off...

Created by Eric Snow on Mon, 11 Jun 2012 (MIT)
Python recipes (4591)
Eric Snow's recipes (39)

Required Modules

  • (none specified)

Other Information and Tasks