[constraints] deal with py3k's string types

Related to #267910.

authorJulien Cristau <julien.cristau@logilab.fr>
changeset88c2c8b7373d
branchdefault
phasepublic
hiddenno
parent revision#32c4bc375ae0 [buildobjs] deal with py3k's string types
child revision#a54af46409ce [reader] use six.moves to get at __builtin__ or builtins module
files modified by this revision
constraints.py
# HG changeset patch
# User Julien Cristau <julien.cristau@logilab.fr>
# Date 1413468323 -7200
# Thu Oct 16 16:05:23 2014 +0200
# Node ID 88c2c8b7373dcdc7d1db606255507951fa7cb6d8
# Parent 32c4bc375ae09edb7b32d5f8661a7df1cb214dba
[constraints] deal with py3k's string types

Related to #267910.

diff --git a/constraints.py b/constraints.py
@@ -16,23 +16,25 @@
1  # You should have received a copy of the GNU Lesser General Public License along
2  # with yams. If not, see <http://www.gnu.org/licenses/>.
3  """Some common constraint classes."""
4 
5  __docformat__ = "restructuredtext en"
6 -_ = unicode
7 
8  import re
9  import decimal
10  import operator
11  from StringIO import StringIO
12 
13 +from six import string_types, text_type, binary_type
14 +
15  from logilab.common.deprecation import class_renamed
16 
17  import yams
18  from yams import BadSchemaDefinition
19  from yams.interfaces import IConstraint, IVocabularyConstraint
20 
21 +_ = text_type
22 
23  class BaseConstraint(object):
24      """base class for constraints"""
25      __implements__ = IConstraint
26 
@@ -329,15 +331,15 @@
27      def check(self, entity, rtype, value):
28          """return true if the value is in the specific vocabulary"""
29          return value in self.vocabulary(entity=entity)
30 
31      def failed_message(self, key, value):
32 -        if isinstance(value, basestring):
33 -            value = '"%s"' % unicode(value)
34 +        if isinstance(value, string_types):
35 +            value = '"%s"' % text_type(value)
36              choices = ', '.join('"%s"' % val for val in self.values)
37          else:
38 -            choices = ', '.join(unicode(val) for val in self.values)
39 +            choices = ', '.join(text_type(val) for val in self.values)
40          return _('invalid value %(KEY-value)s, it must be one of %(KEY-choices)s'), {
41              key+'-value': value,
42              key+'-choices': choices}
43 
44      def vocabulary(self, **kwargs):
@@ -347,21 +349,21 @@
45      def serialize(self):
46          """serialize possible values as a csv list of evaluable strings"""
47          try:
48              sample = next(iter(self.vocabulary()))
49          except:
50 -            sample = unicode()
51 -        if not isinstance(sample, basestring):
52 +            sample = u''
53 +        if not isinstance(sample, string_types):
54              return u', '.join(repr(word) for word in self.vocabulary())
55 -        return u', '.join(repr(unicode(word).replace(',', ',,'))
56 +        return u', '.join(repr(text_type(word).replace(',', ',,'))
57                            for word in self.vocabulary())
58 
59      @classmethod
60      def deserialize(cls, value):
61          """deserialize possible values from a csv list of evaluable strings"""
62          values = [eval(w) for w in re.split('(?<!,), ', value)]
63 -        if values and isinstance(values[0], basestring):
64 +        if values and isinstance(values[0], string_types):
65              values = [v.replace(',,', ',') for v in values]
66          return cls(values)
67 
68 
69  class FormatConstraint(StaticVocabularyConstraint):
@@ -394,11 +396,11 @@
70 
71      def vocabulary(self, **kwargs):
72          return self.regular_formats
73 
74      def __str__(self):
75 -        return 'value in (%s)' % u', '.join(repr(unicode(word)) for word in self.vocabulary())
76 +        return 'value in (%s)' % u', '.join(repr(text_type(word)) for word in self.vocabulary())
77 
78  FORMAT_CONSTRAINT = FormatConstraint()
79 
80 
81  class MultipleStaticVocabularyConstraint(StaticVocabularyConstraint):
@@ -465,15 +467,15 @@
82 
83  # base types checking functions ################################################
84 
85  def check_string(eschema, value):
86      """check value is an unicode string"""
87 -    return isinstance(value, unicode)
88 +    return isinstance(value, text_type)
89 
90  def check_password(eschema, value):
91      """check value is an encoded string"""
92 -    return isinstance(value, (str, StringIO))
93 +    return isinstance(value, (binary_type, StringIO))
94 
95  def check_int(eschema, value):
96      """check value is an integer"""
97      try:
98          int(value)
@@ -526,12 +528,12 @@
99      'Password' : check_password,
100      'Bytes' :    check_file,
101      }
102 
103  BASE_CONVERTERS = {
104 -    'String' :  unicode,
105 -    'Password':  str,
106 +    'String' :   text_type,
107 +    'Password':  binary_type,
108      'Int' :      int,
109      'BigInt' :   int,
110      'Float' :    float,
111      'Boolean' :  bool,
112      'Decimal' :  decimal.Decimal,