23 from builtins
import str
25 from .config
import Field, _typeStr
26 from .callStack
import getStackFrame
28 __all__ = [
"ChoiceField"]
33 Defines a Config Field which allows only a set of values
34 All allowed must be of the same type.
35 Allowed values should be provided as a dict of value, doc string pairs
38 def __init__(self, doc, dtype, allowed, default=None, optional=True):
40 if optional
and None not in self.
allowed:
41 self.
allowed[
None] =
"Field is optional"
44 raise ValueError(
"ChoiceFields must allow at least one choice")
50 doc +=
"\nAllowed values:\n"
51 for choice, choiceDoc
in self.allowed.items():
52 if choice
is not None and not isinstance(choice, dtype):
53 raise ValueError(
"ChoiceField's allowed choice %s is of incorrect type %s. Expected %s" %
54 (choice, _typeStr(choice), _typeStr(dtype)))
55 doc +=
"\t%s\t%s\n" % (str(choice), choiceDoc)
57 Field.__init__(self, doc=doc, dtype=dtype, default=default,
58 check=
None, optional=optional)
61 def _validateValue(self, value):
62 Field._validateValue(self, value)
64 msg =
"Value {} is not allowed.\n" \
65 "\tAllowed values: [{}]".
format(value,
", ".join(str(key)
for key
in self.
allowed))