Dekodieren, wenn es nicht in unicode

Möchte ich meine Funktion zu nutzen, ein argument, das könnte ein unicode-Objekt oder ein utf-8-codierte Zeichenfolge. In meiner Funktion möchte ich konvertiert das argument in unicode. Ich habe so etwas wie dieses:

def myfunction(text):
    if not isinstance(text, unicode):
        text = unicode(text, 'utf-8')

    ...

Ist es möglich, zu vermeiden isinstance? Ich war auf der Suche nach etwas mehr duck-typing freundlich.

Während meiner Experimente mit der Dekodierung, ich habe laufen in mehrere seltsame Verhaltensweisen von Python. Zum Beispiel:

>>> u'hello'.decode('utf-8')
u'hello'
>>> u'cer\xf3n'.decode('utf-8')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/usr/lib/python2.6/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf3' in po
sition 3: ordinal not in range(128)

Oder

>>> u'hello'.decode('utf-8')
u'hello' 12:11
>>> unicode(u'hello', 'utf-8')
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: decoding Unicode is not supported

Durch die Art und Weise. Ich bin mit Python 2.6

InformationsquelleAutor Manuel Ceron | 2010-10-04
Schreibe einen Kommentar