How to use memoization - 10 common examples

To help you get started, we’ve selected a few memoization examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github lonelyenvoy / python-memoization / memoization / backport / backport_enum.py View on Github external
members.sort(key=lambda t: t[0])
        cls = cls(name, members, module=module)
        cls.__reduce_ex__ = _reduce_ex_by_name
        module_globals.update(cls.__members__)
        module_globals[name] = cls
        return cls


class IntEnum(int, Enum):
    """Enum where members are also (and must be) ints"""


def _reduce_ex_by_name(self, proto):
    return self.name

class Flag(Enum):
    """Support for flags"""

    def _generate_next_value_(name, start, count, last_values):
        """
        Generate the next value when not given.

        name: the name of the member
        start: the initital start value or None
        count: the number of existing members
        last_value: the last value assigned or None
        """
        if not count:
            return start if start is not None else 1
        for last_value in reversed(last_values):
            try:
                high_bit = _high_bit(last_value)
github lonelyenvoy / python-memoization / memoization / backport / backport_enum.py View on Github external
# things break (such as pickle)
        for name in ('__repr__', '__str__', '__format__', '__reduce_ex__'):
            class_method = getattr(enum_class, name)
            obj_method = getattr(member_type, name, None)
            enum_method = getattr(first_enum, name, None)
            if obj_method is not None and obj_method is class_method:
                setattr(enum_class, name, enum_method)

        # replace any other __new__ with our own (as long as Enum is not None,
        # anyway) -- again, this is to support pickle
        if Enum is not None:
            # if the user defined their own __new__, save it before it gets
            # clobbered in case they subclass later
            if save_new:
                enum_class.__new_member__ = __new__
            enum_class.__new__ = Enum.__new__

        # py3 support for definition order (helps keep py2/py3 code in sync)
        if _order_ is not None:
            if isinstance(_order_, str):
                _order_ = _order_.replace(',', ' ').split()
            if _order_ != enum_class._member_names_:
                raise TypeError('member order does not match _order_')

        return enum_class
github lonelyenvoy / python-memoization / memoization / memoization.py View on Github external
def _create_cached_wrapper(user_function, max_size, ttl, algorithm, thread_safe, order_independent, custom_key_maker):
    """
    Factory that creates an actual executed function when a function is decorated with @cached
    """
    if max_size == 0:
        return statistic_cache.get_caching_wrapper(user_function, max_size, ttl, algorithm,
                                                   thread_safe, order_independent, custom_key_maker)
    elif max_size is None:
        return plain_cache.get_caching_wrapper(user_function, max_size, ttl, algorithm,
                                               thread_safe, order_independent, custom_key_maker)
    else:
        cache_toolkit = get_cache_toolkit(algorithm)
        return cache_toolkit.get_caching_wrapper(user_function, max_size, ttl, algorithm,
                                                 thread_safe, order_independent, custom_key_maker)
github lonelyenvoy / python-memoization / memoization / memoization.py View on Github external
def _create_cached_wrapper(user_function, max_size, ttl, algorithm, thread_safe, order_independent, custom_key_maker):
    """
    Factory that creates an actual executed function when a function is decorated with @cached
    """
    if max_size == 0:
        return statistic_cache.get_caching_wrapper(user_function, max_size, ttl, algorithm,
                                                   thread_safe, order_independent, custom_key_maker)
    elif max_size is None:
        return plain_cache.get_caching_wrapper(user_function, max_size, ttl, algorithm,
                                               thread_safe, order_independent, custom_key_maker)
    else:
        cache_toolkit = get_cache_toolkit(algorithm)
        return cache_toolkit.get_caching_wrapper(user_function, max_size, ttl, algorithm,
                                                 thread_safe, order_independent, custom_key_maker)
github lonelyenvoy / python-memoization / memoization / memoization_py2.py View on Github external
del cache[old_key]
    else:
        # The cache is not full

        if first_freq_node.frequency != 1:
            # The first element in frequency list has its frequency other than 1 (> 1)
            # Creating a new node in frequency list with 1 as its frequency required
            # We also need to create a new cache list and attach it to this new node

            # Create a cache root and a frequency node
            cache_root = _CacheNode.root()
            freq_node = _FreqNode(root, first_freq_node, 1, cache_root)
            cache_root.parent = freq_node

            # Create another cache node to store data
            cache_node = _CacheNode(cache_root, cache_root, freq_node, key, value)

            # Modify references
            cache_root.prev = cache_root.next = cache_node
            first_freq_node.prev = root.next = freq_node  # note: DO NOT swap "=", because first_freq_node == root.next

        else:
            # We create a new cache node in the cache list
            # under the frequency node with frequency 1

            # Create a cache node and store data in it
            cache_head = first_freq_node.cache_head
            cache_node = _CacheNode(cache_head, cache_head.next, first_freq_node, key, value)

            # Modify references
            cache_node.prev.next = cache_node.next.prev = cache_node
github lonelyenvoy / python-memoization / memoization / memoization_py2.py View on Github external
cache_root.parent = freq_node

            # Create another cache node to store data
            cache_node = _CacheNode(cache_root, cache_root, freq_node, key, value)

            # Modify references
            cache_root.prev = cache_root.next = cache_node
            first_freq_node.prev = root.next = freq_node  # note: DO NOT swap "=", because first_freq_node == root.next

        else:
            # We create a new cache node in the cache list
            # under the frequency node with frequency 1

            # Create a cache node and store data in it
            cache_head = first_freq_node.cache_head
            cache_node = _CacheNode(cache_head, cache_head.next, first_freq_node, key, value)

            # Modify references
            cache_node.prev.next = cache_node.next.prev = cache_node

    # Finally, insert the data into the cache
    cache[key] = cache_node
github lonelyenvoy / python-memoization / memoization / memoization_py2.py View on Github external
last_node.destroy()

            if first_freq_node.cache_head.next == first_freq_node.cache_head:
                # Getting here means that we just deleted the only data node in the cache list
                # under the first frequency list
                # Note: there is still an empty sentinel node
                # We then need to destroy the sentinel node and its parent frequency node too
                first_freq_node.cache_head.destroy()
                first_freq_node.destroy()
                first_freq_node = root.next  # update

            # Delete from cache
            del cache[old_key]

            # Prepare a new frequency node, a cache root node and a cache data node
            empty_cache_root = _CacheNode.root()
            freq_node = _FreqNode(root, first_freq_node, 1, empty_cache_root)
            cache_node = _CacheNode(empty_cache_root, empty_cache_root, freq_node, key, value)
            empty_cache_root.parent = freq_node

            # Modify references
            root.next.prev = root.next = freq_node
            empty_cache_root.prev = empty_cache_root.next = cache_node

        else:
            # We can find the last element in the cache list under the first frequency list
            # Moving it to the head and replace the stored data with a new key and a new value
            # This is more efficient

            # Find the target
            cache_head = first_freq_node.cache_head
            manipulated_node = cache_head.prev
github lonelyenvoy / python-memoization / memoization / memoization_py2.py View on Github external
if first_freq_node.cache_head.next == first_freq_node.cache_head:
                # Getting here means that we just deleted the only data node in the cache list
                # under the first frequency list
                # Note: there is still an empty sentinel node
                # We then need to destroy the sentinel node and its parent frequency node too
                first_freq_node.cache_head.destroy()
                first_freq_node.destroy()
                first_freq_node = root.next  # update

            # Delete from cache
            del cache[old_key]

            # Prepare a new frequency node, a cache root node and a cache data node
            empty_cache_root = _CacheNode.root()
            freq_node = _FreqNode(root, first_freq_node, 1, empty_cache_root)
            cache_node = _CacheNode(empty_cache_root, empty_cache_root, freq_node, key, value)
            empty_cache_root.parent = freq_node

            # Modify references
            root.next.prev = root.next = freq_node
            empty_cache_root.prev = empty_cache_root.next = cache_node

        else:
            # We can find the last element in the cache list under the first frequency list
            # Moving it to the head and replace the stored data with a new key and a new value
            # This is more efficient

            # Find the target
            cache_head = first_freq_node.cache_head
            manipulated_node = cache_head.prev

            # Modify references
github lonelyenvoy / python-memoization / memoization / memoization_py2.py View on Github external
# use another name so it can be accessed later
            cache_node = manipulated_node

            # Delete from cache
            del cache[old_key]
    else:
        # The cache is not full

        if first_freq_node.frequency != 1:
            # The first element in frequency list has its frequency other than 1 (> 1)
            # Creating a new node in frequency list with 1 as its frequency required
            # We also need to create a new cache list and attach it to this new node

            # Create a cache root and a frequency node
            cache_root = _CacheNode.root()
            freq_node = _FreqNode(root, first_freq_node, 1, cache_root)
            cache_root.parent = freq_node

            # Create another cache node to store data
            cache_node = _CacheNode(cache_root, cache_root, freq_node, key, value)

            # Modify references
            cache_root.prev = cache_root.next = cache_node
            first_freq_node.prev = root.next = freq_node  # note: DO NOT swap "=", because first_freq_node == root.next

        else:
            # We create a new cache node in the cache list
            # under the frequency node with frequency 1

            # Create a cache node and store data in it
            cache_head = first_freq_node.cache_head
github lonelyenvoy / python-memoization / memoization / memoization_py2.py View on Github external
if key in cache:
        cache_node = cache[key]
    else:
        # Key does not exist
        # Access failed
        return sentinel
    freq_node = cache_node.parent
    target_frequency = freq_node.frequency + 1
    if freq_node.next.frequency != target_frequency:
        # The next node on the frequency list has a frequency value different from
        # (the frequency of the current node) + 1, which means we need to construct
        # a new frequency node and an empty cache root node
        # Then we move the current node to the newly created cache list

        # Create a cache root and a frequency root
        cache_root = _CacheNode.root()
        new_freq_node = _FreqNode(freq_node, freq_node.next, target_frequency, cache_root)
        cache_root.parent = new_freq_node

        # Modify references
        cache_node.prev.next = cache_node.next
        cache_node.next.prev = cache_node.prev
        cache_node.prev = cache_node.next = cache_root
        cache_root.prev = cache_root.next = cache_node
        new_freq_node.next.prev = new_freq_node.prev.next = new_freq_node
        cache_node.parent = cache_root.parent

    else:
        # We can move the cache node to the cache list of the next node on the frequency list

        # Find the head element of the next cache list
        next_cache_head = freq_node.next.cache_head