summaryrefslogtreecommitdiff
path: root/ricky/param/enum.py
blob: 3a9fe0e1bd7f8518fdb92a8d1a2f6628b8f0cc08 (plain)
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
39
40
41
42
43
44
45
46
47
48
49
import random
from ricky.param import Param
import decimal


class Enum(Param):
    def __init__(self, options=None, **kwargs):
        self._options = set(options)
        if not self._options:
            raise ValueError("Object must be initialized with options set")
        super(Enum, self).__init__(**kwargs)
        self._validate_options()

    def options(self):
        return self._options

    def _validate_options(self):
        try:
            pass
        except Exception:
            raise ValueError('Unable to validate %s\n:' % self.name)

    def value_get(self):
        return super(Enum, self).value_get()

    def value_set(self, value):
        if value not in self._options and value is not None:
            raise ValueError
        super(Enum, self).value_set(value)

    value = property(value_get, value_set)

    def randomize(self):
        self.value_set(random.choice(self._options))

    def as_dict(self):
        my_dict = super(Enum, self).as_dict()
        my_dict['options'] = self._options
        return my_dict

    def from_normalized(self, value):
        maximum = len(self._options - 1)
        idx_val = int(round(maximum * value, 0))
        self.value = self._options[idx_val]

    def as_normalized(self):
        maximum = len(self._options - 1)
        value = int(self.as_hex(), 16)
        return decimal.Decimal(value)/decimal.Decimal(maximum)