Package translate :: Package misc :: Module autoencode

[hide private]
[frames] | no frames]

# Source Code for Module translate.misc.autoencode

     1  #!/usr/bin/env python
     2  # -*- coding: utf-8 -*-
     3  #
     4  # Copyright 2006 Zuza Software Foundation
     5  #
     6  # This file is part of translate.
     7  #
     8  # translate is free software; you can redistribute it and/or modify
     9  # it under the terms of the GNU General Public License as published by
    10  # the Free Software Foundation; either version 2 of the License, or
    11  # (at your option) any later version.
    12  #
    13  # translate is distributed in the hope that it will be useful,
    14  # but WITHOUT ANY WARRANTY; without even the implied warranty of
    15  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    16  # GNU General Public License for more details.
    17  #
    18  # You should have received a copy of the GNU General Public License
    19  # along with translate; if not, write to the Free Software
    20  # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    21
    22  """Supports a hybrid Unicode string that knows which encoding is preferable,
    23  and uses this when converting to a string."""
    24
    25 -class autoencode(unicode):
    26 -    def __new__(newtype, string=u"", encoding=None, errors=None):
    27          if isinstance(string, unicode):
    28              if errors is None:
    29                  newstring = unicode.__new__(newtype, string)
    30              else:
    31                  newstring = unicode.__new__(newtype, string, errors=errors)
    32              if encoding is None and isinstance(string, autoencode):
    33                  newstring.encoding = string.encoding
    34              else:
    35                  newstring.encoding = encoding
    36          else:
    37              if errors is None and encoding is None:
    38                  newstring = unicode.__new__(newtype, string)
    39              elif errors is None:
    40                  try:
    41                      newstring = unicode.__new__(newtype, string, encoding)
    42                  except LookupError, e:
    43                      raise ValueError(str(e))
    44              elif encoding is None:
    45                  newstring = unicode.__new__(newtype, string, errors)
    46              else:
    47                  newstring = unicode.__new__(newtype, string, encoding, errors)
    48              newstring.encoding = encoding
    49          return newstring
    50
    51 -    def join(self, seq):
    52          return autoencode(super(autoencode, self).join(seq))
    53
    54 -    def __str__(self):
    55          if self.encoding is None:
    56              return super(autoencode, self).__str__()
    57          else:
    58              return self.encode(self.encoding)
    59