Подтвердить что ты не робот

Python - у кого-нибудь есть памятный декоратор, который может обрабатывать нераскрывающиеся аргументы?

Я использовал следующий memoizing decorator (из большой книги Python Algorithms: Освоение основных алгоритмов на языке Python... люблю его, кстати).

def memo(func):
    cache = {}
    @ wraps(func)
    def wrap(*args):
        if args not in cache:
            cache[args] = func(*args)
        return cache[args]
    return wrap

Проблема с этим декоратором заключается в том, что кеш-словарь на основе слова означает, что все мои аргументы должны быть хешируемыми.

Есть ли у кого-нибудь реализация (или настройка к ней), которая допускает несанкционированные аргументы (например, словари)?

Я знаю, что отсутствие хэш-значения означает, что вопрос "это в кеше?" становится нетривиальным, но я просто подумал, что попрошу.

=== ИЗМЕНИТЬ СООБЩЕНИЕ ===

Я работаю над функцией, которая возвращает стиль Parnas "использует иерархию", учитывая словарь модулей: зависимости. Здесь настройка:

def uses_hierarchy(requirements):
    """
    uses_hierarchy(requirements)

    Arguments:
    requirements - a dictionary of the form {mod: list of dependencies, }

    Return value:
    A dictionary of the form {level: list of mods, ...}

    Assumptions:
    - No cyclical requirements (e.g. if a requires b, b cannot require a).
    - Any dependency not listed as a mod assumed to be level 0.

    """

    levels = dict([(mod, _level(mod, requirements))
                   for mod in requirements.iterkeys()])
    reversed = dict([(value, []) for value in levels.itervalues()])
    for k, v in levels.iteritems():
        reversed[v].append(k)
    return reversed


def _level(mod, requirements):
    if not requirements.has_key(mod):
        return 0
    dependencies = requirements[mod]
    if not dependencies:
        return 0
    else:
        return max([_level(dependency, requirements)
                    for dependency in dependencies]) + 1

Итак, чтобы:

>>> requirements = {'a': [],
...                 'b': [],
...                 'c': ['a'],
...                 'd': ['a','b'],
...                 'e': ['c','d'],
...                 'f': ['e']
...                 }

>>> uses_hierarchy(requirements)
{0: ['a', 'b'], 1: ['c', 'd'], 2: ['e'], 3: ['f']}

_level - это функция, которую я хочу memoize, чтобы сделать эту настройку более масштабируемой. Как реализовано без memoization, он вычисляет уровень зависимостей несколько раз (например, "a" вычисляется 8 раз, как я думаю в примере выше).

Спасибо,

Mike

4b9b3361

Ответ 1

Вот пример в Alex Martelli Python Cookbook, в котором показано, как создать декоратор memoize с помощью cPickle для функции, которая принимает измененный аргумент (исходная версия):

import cPickle

class MemoizeMutable:
    def __init__(self, fn):
        self.fn = fn
        self.memo = {}
    def __call__(self, *args, **kwds):
        import cPickle
        str = cPickle.dumps(args, 1)+cPickle.dumps(kwds, 1)
        if not self.memo.has_key(str): 
            print "miss"  # DEBUG INFO
            self.memo[str] = self.fn(*args, **kwds)
        else:
            print "hit"  # DEBUG INFO

        return self.memo[str]

Вот ссылка .

РЕДАКТИРОВАТЬ: Используя код, который вы указали, и этот декоратор memoize:

_level = MemoizeMutable(_level)

equirements = {'a': [],
               'b': [],
               'c': ['a'],
               'd': ['a','b'],
               'e': ['c','d'],
               'f': ['e']
                 }

print uses_hierarchy(equirements)

i смог воспроизвести это:

miss
miss
hit
miss
miss
hit
miss
hit
hit
hit
miss
hit
{0: ['a', 'b'], 1: ['c', 'd'], 2: ['e'], 3: ['f']}

Ответ 2

Технически вы можете решить эту проблему, повернув dict (или list или set) в кортеж. Например:

 key = tuple(the_dict.iteritems())
 key = tuple(the_list)
 key = tuple(sorted(the_set))

 cache[key] = func( .. )

Но я бы не сделал этого в memo, я бы скорее изменил функции, которые вы хотите использовать memo, например, вместо того, чтобы принимать dict, они должны принимать только пары (key, value), а не беря списки или наборы, они должны просто взять *args.

Ответ 3

Поскольку никто не упомянул об этом, в Python Wiki есть библиотека Decorator, которая включает в себя memoizing decorator patterns.

Мое личное предпочтение - это последнее, которое позволяет вызывать код просто рассматривать метод как лениво оцениваемое свойство, а не метод. Но мне больше нравится здесь.

class lazy_property(object):
    '''Decorator: Enables the value of a property to be lazy-loaded.
    From Mercurial util.propertycache

    Apply this decorator to a no-argument method of a class and you
    will be able to access the result as a lazy-loaded class property.
    The method becomes inaccessible, and the property isn't loaded
    until the first time it called.  Repeated calls to the property
    don't re-run the function.

    This takes advantage of the override behavior of Descriptors - 
    __get__ is only called if an attribute with the same name does
    not exist.  By not setting __set__ this is a non-data descriptor,
    and "If an instance dictionary has an entry with the same name
    as a non-data descriptor, the dictionary entry takes precedence."
     - http://users.rcn.com/python/download/Descriptor.htm

    To trigger a re-computation, 'del' the property - the value, not
    this class, will be deleted, and the value will be restored upon
    the next attempt to access the property.
    '''
    def __init__(self,func):
        self.func = func
        self.name = func.__name__
    def __get__(self, obj, type=None):
        result = self.func(obj)
        setattr(obj, self.name, result)
        return result

В том же файле, связанном выше, также есть lazy_dict decorator, который позволяет обрабатывать функцию как словарь с лениво оцениваемыми значениями.

Ответ 4

Не сильно тестируется, но, похоже, работает:

from functools import wraps

def memo(func):
    cache = []
    argslist = []
    @ wraps(func)
    def wrap(*args):
        try:
            result = cache[argslist.index(args)]
            print 'cache hit'
            return result
        except ValueError:
            argslist.append(args)
            cache.append(func(*args))
            print 'cache miss'
            return cache[-1]
    return wrap

d1 = { 'a':3, 'b':42 }
d2 = { 'c':7, 'd':19 }
d3 = { 'e':34, 'f':67 }

@memo
def func(d):
    return sum(d.values())

print func(d1)
# cache miss
# 45
print func(d2)
# cache miss
# 26
print func(d3)
# cache miss
# 101
print func(d2)
# cache hit
# 26