Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ cache:

install:
- travis_retry pip install -q coveralls codecov
- pip install flake8 # eventually worth
- pip install flake8 six # eventually worth

script:
# Run tests
Expand Down
19 changes: 8 additions & 11 deletions flyweight.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,31 @@

import weakref

from six import add_metaclass


class FlyweightMeta(type):

def __new__(mcs, name, parents, dct):
"""
Set up object pool

:param name: class name
:param parents: class parents
:param dct: dict: includes class attributes, class methods,
static methods, etc
:return: new class
"""

# set up instances pool
dct['pool'] = weakref.WeakValueDictionary()
return super(FlyweightMeta, mcs).__new__(mcs, name, parents, dct)

@staticmethod
def _serialize_params(cls, *args, **kwargs):
"""Serialize input parameters to a key.
"""
Serialize input parameters to a key.
Simple implementation is just to serialize it as a string

"""
args_list = map(str, args)
args_list = list(map(str, args))
args_list.extend([str(kwargs), cls.__name__])
key = ''.join(args_list)
return key
Expand Down Expand Up @@ -65,20 +67,15 @@ def __repr__(self):
return "<Card: %s%s>" % (self.value, self.suit)


@add_metaclass(FlyweightMeta)
class Card2(object):
__metaclass__ = FlyweightMeta

def __init__(self, *args, **kwargs):
# print('Init {}: {}'.format(self.__class__, (args, kwargs)))
pass


if __name__ == '__main__':
import sys
if sys.version_info[0] > 2:
sys.stderr.write("!!! This example is compatible only with Python 2 ATM !!!\n")
raise SystemExit(0)

# comment __new__ and uncomment __init__ to see the difference
c1 = Card('9', 'h')
c2 = Card('9', 'h')
Expand Down