|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | + |
| 4 | +""" |
| 5 | +*What is this pattern about? |
| 6 | +This pattern aims to minimise the number of objects that are needed by |
| 7 | +a program at run-time. A Flyweight is an object shared by multiple |
| 8 | +contexts, and is indistinguishable from an object that is not shared. |
| 9 | +
|
| 10 | +The state of a Flyweight should not be affected by it's context, this |
| 11 | +is known as its intrinsic state. The decoupling of the objects state |
| 12 | +from the object's context, allows the Flyweight to be shared. |
| 13 | +
|
| 14 | +*What does this example do? |
| 15 | +The example below sets-up an 'object pool' which stores initialised |
| 16 | +objects. When a 'Card' is created it first checks to see if it already |
| 17 | +exists instead of creating a new one. This aims to reduce the number of |
| 18 | +objects initialised by the program. |
| 19 | +
|
| 20 | +*References: |
| 21 | +http://codesnipers.com/?q=python-flyweights |
| 22 | +
|
| 23 | +*TL;DR80 |
| 24 | +Minimizes memory usage by sharing data with other similar objects. |
| 25 | +""" |
| 26 | + |
| 27 | +import weakref |
| 28 | + |
| 29 | + |
| 30 | +class FlyweightMeta(type): |
| 31 | + def __new__(mcs, name, parents, dct): |
| 32 | + """ |
| 33 | + Set up object pool |
| 34 | +
|
| 35 | + :param name: class name |
| 36 | + :param parents: class parents |
| 37 | + :param dct: dict: includes class attributes, class methods, |
| 38 | + static methods, etc |
| 39 | + :return: new class |
| 40 | + """ |
| 41 | + dct['pool'] = weakref.WeakValueDictionary() |
| 42 | + return super(FlyweightMeta, mcs).__new__(mcs, name, parents, dct) |
| 43 | + |
| 44 | + @staticmethod |
| 45 | + def _serialize_params(cls, *args, **kwargs): |
| 46 | + """ |
| 47 | + Serialize input parameters to a key. |
| 48 | + Simple implementation is just to serialize it as a string |
| 49 | + """ |
| 50 | + args_list = list(map(str, args)) |
| 51 | + args_list.extend([str(kwargs), cls.__name__]) |
| 52 | + key = ''.join(args_list) |
| 53 | + return key |
| 54 | + |
| 55 | + def __call__(cls, *args, **kwargs): |
| 56 | + key = FlyweightMeta._serialize_params(cls, *args, **kwargs) |
| 57 | + pool = getattr(cls, 'pool', {}) |
| 58 | + |
| 59 | + instance = pool.get(key) |
| 60 | + if instance is None: |
| 61 | + instance = super(FlyweightMeta, cls).__call__(*args, **kwargs) |
| 62 | + pool[key] = instance |
| 63 | + return instance |
| 64 | + |
| 65 | + |
| 66 | +class Card(object): |
| 67 | + |
| 68 | + """The object pool. Has builtin reference counting""" |
| 69 | + |
| 70 | + _CardPool = weakref.WeakValueDictionary() |
| 71 | + |
| 72 | + """Flyweight implementation. If the object exists in the |
| 73 | + pool just return it (instead of creating a new one)""" |
| 74 | + |
| 75 | + def __new__(cls, value, suit): |
| 76 | + obj = Card._CardPool.get(value + suit) |
| 77 | + if not obj: |
| 78 | + obj = object.__new__(cls) |
| 79 | + Card._CardPool[value + suit] = obj |
| 80 | + obj.value, obj.suit = value, suit |
| 81 | + return obj |
| 82 | + |
| 83 | + # def __init__(self, value, suit): |
| 84 | + # self.value, self.suit = value, suit |
| 85 | + |
| 86 | + def __repr__(self): |
| 87 | + return "<Card: %s%s>" % (self.value, self.suit) |
| 88 | + |
| 89 | + |
| 90 | +class Card2(metaclass=FlyweightMeta): |
| 91 | + def __init__(self, *args, **kwargs): |
| 92 | + # print('Init {}: {}'.format(self.__class__, (args, kwargs))) |
| 93 | + pass |
| 94 | + |
| 95 | + |
| 96 | +if __name__ == '__main__': |
| 97 | + # comment __new__ and uncomment __init__ to see the difference |
| 98 | + c1 = Card('9', 'h') |
| 99 | + c2 = Card('9', 'h') |
| 100 | + print(c1, c2) |
| 101 | + print(c1 == c2, c1 is c2) |
| 102 | + print(id(c1), id(c2)) |
| 103 | + |
| 104 | + c1.temp = None |
| 105 | + c3 = Card('9', 'h') |
| 106 | + print(hasattr(c3, 'temp')) |
| 107 | + c1 = c2 = c3 = None |
| 108 | + c3 = Card('9', 'h') |
| 109 | + print(hasattr(c3, 'temp')) |
| 110 | + |
| 111 | + # Tests with metaclass |
| 112 | + instances_pool = getattr(Card2, 'pool') |
| 113 | + cm1 = Card2('10', 'h', a=1) |
| 114 | + cm2 = Card2('10', 'h', a=1) |
| 115 | + cm3 = Card2('10', 'h', a=2) |
| 116 | + |
| 117 | + assert (cm1 == cm2) and (cm1 != cm3) |
| 118 | + assert (cm1 is cm2) and (cm1 is not cm3) |
| 119 | + assert len(instances_pool) == 2 |
| 120 | + |
| 121 | + del cm1 |
| 122 | + assert len(instances_pool) == 2 |
| 123 | + |
| 124 | + del cm2 |
| 125 | + assert len(instances_pool) == 1 |
| 126 | + |
| 127 | + del cm3 |
| 128 | + assert len(instances_pool) == 0 |
| 129 | + |
| 130 | +### OUTPUT ### |
| 131 | +# (<Card: 9h>, <Card: 9h>) |
| 132 | +# (True, True) |
| 133 | +# (31903856, 31903856) |
| 134 | +# True |
| 135 | +# False |
0 commit comments