-
Notifications
You must be signed in to change notification settings - Fork 14
/
choicemeta.py
70 lines (52 loc) · 1.81 KB
/
choicemeta.py
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
from collections import OrderedDict
from malcolm.core.scalarmeta import ScalarMeta
from malcolm.core.serializable import Serializable
@Serializable.register_subclass("malcolm:core/ChoiceMeta:1.0")
class ChoiceMeta(ScalarMeta):
"""Meta object containing information for a enum"""
def __init__(self, name, description, choices):
super(ChoiceMeta, self).__init__(name=name, description=description)
self.choices = choices
def set_choices(self, choices):
"""
Set allowed values
Args:
choices (list): List of allowed values
"""
self.choices = choices
def validate(self, value):
"""
Check if the value is valid returns it
Args:
value: Value to validate
Returns:
Value if it is valid
Raises:
ValueError: If value not valid
"""
if value is None or value in self.choices:
return value
else:
raise ValueError("%s is not a valid value" % value)
def to_dict(self):
"""Convert object attributes into a dictionary"""
d = OrderedDict()
d["typeid"] = self.typeid
d["choices"] = self.choices
d.update(super(ChoiceMeta, self).to_dict())
return d
@classmethod
def from_dict(cls, name, d):
"""Create a ChoiceMeta subclass instance from the serialized version
of itself
Args:
name (str): ChoiceMeta instance name
d (dict): Serialised version of ChoiceMeta
"""
description = d['description']
choices = d['choices']
choice_meta = cls(name, description, choices)
choice_meta.tags = d['tags']
choice_meta.writeable = d['writeable']
choice_meta.label = d['label']
return choice_meta