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   
26 -class autoencode(unicode):
27
28 - def __new__(newtype, string=u"", encoding=None, errors=None):
29 if isinstance(string, unicode): 30 if errors is None: 31 newstring = unicode.__new__(newtype, string) 32 else: 33 newstring = unicode.__new__(newtype, string, errors=errors) 34 if encoding is None and isinstance(string, autoencode): 35 newstring.encoding = string.encoding 36 else: 37 newstring.encoding = encoding 38 else: 39 if errors is None and encoding is None: 40 newstring = unicode.__new__(newtype, string) 41 elif errors is None: 42 try: 43 newstring = unicode.__new__(newtype, string, encoding) 44 except LookupError, e: 45 raise ValueError(str(e)) 46 elif encoding is None: 47 newstring = unicode.__new__(newtype, string, errors) 48 else: 49 newstring = unicode.__new__(newtype, string, encoding, errors) 50 newstring.encoding = encoding 51 return newstring
52
53 - def join(self, seq):
54 return autoencode(super(autoencode, self).join(seq))
55
56 - def __str__(self):
57 if self.encoding is None: 58 return super(autoencode, self).__str__() 59 else: 60 return self.encode(self.encoding)
61