Source code for nxpy.core.memo
# nxpy.core package ----------------------------------------------------------
# Copyright Nicola Musatti 2008 - 2012
# Use, modification, and distribution are subject to the Boost Software
# License, Version 1.0. (See accompanying file LICENSE.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
# See http://sourceforge.net/nxpy for library home page. ---------------------
r"""
Memoize class instances according to a given key.
By default the key only assumes the 'True' value, thus implementing a singleton.
"""
[docs]class Memo(object):
r"""
Base class for classes that require memoization.
Care should be taken to avoid calling __init__() again for entities already constructed.
"""
_dict = {}
def __new__(cls, *args, **kwargs):
k = cls._key(*args, **kwargs)
try:
return Memo._dict[(cls, k)]
except KeyError:
i = super(Memo, cls).__new__(cls)
Memo._dict[(cls, k)] = i
return i
@staticmethod
def _key(*args, **kwargs):
r"""
Returns the key by which instances are memoized.
Subclasses should override it as a function of their construction arguments.
"""
return True