translate.misc.typecheck.sets

Package translate :: Package misc :: Package typecheck :: Module sets |
[hide private]
[frames] | no frames]

# Source Code for Module translate.misc.typecheck.sets

     1  from translate.misc.typecheck import CheckType, _TC_TypeError, check_type, Type
     2  from translate.misc.typecheck import register_type, Or, _TC_Exception, _TC_KeyError
     3  from translate.misc.typecheck import _TC_LengthError
     4
     5  ### Provide typechecking for the built-in set() class
     6  ###
     7  ### XXX: Investigate rewriting this in terms of
     8  ### UnorderedIteratorMixin or Or()
     9 -class Set(CheckType):
    10 -    def __init__(self, set_list):
    11          self.type = set(set_list)
    12          self._types = [Type(t) for t in self.type]
    13
    14          # self._type is used to build _TC_TypeError
    15          if len(self._types) > 1:
    16              self._type = Or(*self.type)
    17          elif len(self._types) == 1:
    18              # XXX Is there an easier way to get this?
    19              t = self.type.pop()
    20              self._type = t
    21              self.type.add(t)
    22
    23 -    def __str__(self):
    24          return "Set(" + str([e for e in self.type]) + ")"
    25
    26      __repr__ = __str__
    27
    28 -    def __typecheck__(self, func, to_check):
    29          if not isinstance(to_check, set):
    30              raise _TC_TypeError(to_check, self.type)
    31
    32          if len(self._types) == 0 and len(to_check) > 0:
    33              raise _TC_LengthError(len(to_check), 0)
    34
    35          for obj in to_check:
    36              error = False
    37              for type in self._types:
    38                  try:
    39                      check_type(type, func, obj)
    40                  except _TC_Exception:
    41                      error = True
    42                      continue
    43                  else:
    44                      error = False
    45                      break
    46              if error:
    47                  raise _TC_KeyError(obj, _TC_TypeError(obj, self._type))
    48
    49 -    def __eq__(self, other):
    50          if self.__class__ is not other.__class__:
    51              return False
    52          return self.type == other.type
    53
    54 -    def __hash__(self):
    55          return hash(str(hash(self.__class__)) + str(hash(frozenset(self.type))))
    56
    57      @classmethod
    58 -    def __typesig__(self, obj):
    59          if isinstance(obj, set):
    60              return Set(obj)
    61
    62  register_type(Set)
    63