Package konval :: Module vocabval
[hide private]
[frames] | no frames]

Source Code for Module konval.vocabval

  1  """ 
  2  Validators that remap values or check vocabulary membership. 
  3   
  4  """ 
  5   
  6  __docformat__ = "restructuredtext en" 
  7   
  8   
  9  ### IMPORTS 
 10   
 11  import impl 
 12  from basevalidator import BaseValidator 
 13   
 14   
 15  ### CONSTANTS & DEFINES 
 16   
 17  ### IMPLEMENTATION ### 
 18   
19 -class Synonyms (BaseValidator):
20 """ 21 Map values to other values. 22 23 Note that this does not explicitly throw errors. If a value is un-mapped, 24 it is simply returned. 25 """
26 - def __init__ (self, d):
27 """ 28 :Parameters: 29 d 30 a dictionary mapping input values to output values 31 32 :Returns: 33 the mapped value or the original is no mapping available 34 35 For example:: 36 37 >>> d = {'foo': 1, 'bar': 2} 38 >>> v = Synonyms(d) 39 >>> v('foo') 40 1 41 >>> v('quux') 42 'quux' 43 44 """ 45 self._syns = d
46
47 - def convert_value (self, value):
48 return self._syns.get (value, value)
49 50
51 -class Vocab (BaseValidator):
52 """ 53 Ensure values fall within a fixed set. 54 """ 55
56 - def __init__ (self, vocab, canonize=False, allow_other=False):
57 """ 58 :Parameters: 59 vocab 60 a sequence of permitted values or value pairs (input and 61 transformation) 62 canonize : bool 63 should all values be transformed to a canonical form 64 allow_other : bool 65 allow non-listed values 66 67 :Returns: 68 the original value, mapped & canonized if supplied and requested 69 70 For example:: 71 72 >>> d = ['foo', ['bar', 'baz'], 'quux'] 73 >>> v = Vocab(d) 74 >>> v('foo') 75 'foo' 76 >>> v('bar') 77 'baz' 78 >>> v('corge') 79 Traceback (most recent call last): 80 ... 81 ValueError: 'corge' is not a member of ['quux', 'foo', 'bar'] 82 >>> v = Vocab(d, allow_other=True) 83 >>> v('corge') 84 'corge' 85 >>> v = Vocab(d, canonize=True, allow_other=True) 86 >>> v('foo') 87 'FOO' 88 >>> v('bar') 89 'BAZ' 90 >>> v('corge') 91 'CORGE' 92 93 94 """ 95 self.conv_dict = {} 96 for t in vocab: 97 t = impl.make_list (t) 98 if canonize: 99 k, v = impl.make_canonical(t[0]), impl.make_canonical(t[-1]) 100 else: 101 k, v = t[0], t[-1] 102 self.conv_dict[k] = v 103 self.canonize = canonize 104 self.allow_other = allow_other
105
106 - def convert_value (self, value):
107 if self.canonize: 108 value = impl.make_canonical (value) 109 if self.allow_other: 110 return self.conv_dict.get (value, value) 111 else: 112 return self.conv_dict[value]
113
114 - def make_conversion_error_msg (self, bad_val, err):
115 """ 116 Generate an meaningful error message for a membership problem. 117 """ 118 return "'%s' is not a member of %s" % (bad_val, self.conv_dict.keys())
119 120 121 122 ## DEBUG & TEST ### 123 124 if __name__ == "__main__": 125 import doctest 126 doctest.testmod() 127 128 129 130 131 ### END ####################################################################### 132