File: decorators.py

package info (click to toggle)
python-aptly 0.12.12-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, trixie
  • size: 316 kB
  • sloc: python: 992; makefile: 14
file content (25 lines) | stat: -rw-r--r-- 681 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# -*- coding: utf-8 -*-


class CachedMethod(object):
    """
    Decorator for caching of function results
    """
    def __init__(self, function):
        self.function = function
        self.mem = {}

    def __call__(self, *args, **kwargs):
        cached = kwargs.pop('cached', True)
        if cached is True:
            if (args, str(kwargs)) in self.mem:
                return self.mem[args, str(kwargs)]

        tmp = self.function(*args, **kwargs)
        self.mem[args, str(kwargs)] = tmp
        return tmp

    def __get__(self, obj, objtype):
        """ Support instance methods """
        import functools
        return functools.partial(self.__call__, obj)