File: options.py

package info (click to toggle)
python-memoize 1.0.3-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 112 kB
  • sloc: python: 324; makefile: 3
file content (38 lines) | stat: -rw-r--r-- 914 bytes parent folder | download | duplicates (3)
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
26
27
28
29
30
31
32
33
34
35
36
37
38
from functools import partial

try:
    from collections.abc import Callable
except ImportError:
    from collections import Callable


def call_or_pass(value, args, kwargs):
    if isinstance(value, Callable):
        return value(*args, **kwargs)
    return value


class OptionProperty(object):

    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return '<%s %r>' % (self.__class__.__name__, self.name)

    def __get__(self, obj, cls):
        return partial(self, obj)

    def __set__(self, obj, value):
        obj.opts[self.name] = value

    def __call__(self, obj, *args, **kwargs):

        # As a decorator.
        if len(args) == 1 and not kwargs and isinstance(args[0], Callable):
            obj.opts[self.name] = args[0]
            return args[0]

        else:
            value = obj.opts.get(self.name)
            return call_or_pass(value, args, kwargs)