2 # -*- coding: utf-8 -*-
4 # Copyright 2006 Zuza Software Foundation
6 # This file is part of translate.
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.
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.
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
22 """Supports a hybrid Unicode string that knows which encoding is preferable,
23 and uses this when converting to a string."""
25 class autoencode(unicode):
26 def __new__(newtype
, string
=u
"", encoding
=None, errors
=None):
27 if isinstance(string
, unicode):
29 newstring
= unicode.__new
__(newtype
, string
)
31 newstring
= unicode.__new
__(newtype
, string
, errors
=errors
)
32 if encoding
is None and isinstance(string
, autoencode
):
33 newstring
.encoding
= string
.encoding
35 newstring
.encoding
= encoding
37 if errors
is None and encoding
is None:
38 newstring
= unicode.__new
__(newtype
, string
)
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
)
47 newstring
= unicode.__new
__(newtype
, string
, encoding
, errors
)
48 newstring
.encoding
= encoding
52 return autoencode(super(autoencode
, self
).join(seq
))
55 if self
.encoding
is None:
56 return super(autoencode
, self
).__str
__()
58 return self
.encode(self
.encoding
)