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

so_magic.utils.memoize   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 27
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 16
dl 0
loc 27
rs 10
c 0
b 0
f 0
wmc 4

3 Methods

Rating   Name   Duplication   Size   Complexity  
A ObjectsPool.get_object() 0 5 2
A ObjectsPool._build_hash() 0 3 1
A ObjectsPool.__getattr__() 0 2 1
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