| Total Complexity | 4 |
| Total Lines | 27 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 1 | import attr |
||
| 2 | |||
| 3 | __all__ = ['ObjectsPool'] |
||
| 4 | |||
| 5 | |||
| 6 | @attr.s |
||
| 7 | class ObjectsPool: |
||
| 8 | """A generic object pool able to return a reference to an object upon request. Whenever an object is requested a |
||
| 9 | hash is built out of the (request) arguments, which is then checked against the registry of keys to determine |
||
| 10 | whether the object is present in the pool or to create (using the local constructor attribute) and insert a new one |
||
| 11 | (in the pool).""" |
||
| 12 | constructor = attr.ib(init=True) |
||
| 13 | _objects = attr.ib(init=True, default={}) |
||
| 14 | |||
| 15 | def get_object(self, *args, **kwargs): |
||
| 16 | key = self._build_hash(*args, **kwargs) |
||
| 17 | if key not in self._objects: |
||
| 18 | self._objects[key] = self.constructor(*args, **kwargs) |
||
| 19 | return self._objects[key] |
||
| 20 | |||
| 21 | def _build_hash(self, *args, **kwargs): |
||
| 22 | """Construct a unique string out of the arguments that the constructor receives.""" |
||
| 23 | return hash('-'.join([str(_) for _ in args])) |
||
| 24 | |||
| 25 | def __getattr__(self, item): |
||
| 26 | return self._objects[item] |
||
| 27 |