Completed
Push — appveyor ( 280314...2c0e2c )
by Konstantinos
02:09
created

so_magic.utils.memoize.ObjectsPool.__getattr__()   A

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nop 2
dl 0
loc 2
rs 10
c 0
b 0
f 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