Decoding wenn es nicht Unicode ist

Ich möchte, dass meine Funktion ein Argument akzeptiert, das ein Unicode-Objekt oder eine utf-8-codierte Zeichenfolge sein kann. In meiner Funktion möchte ich das Argument in Unicode konvertieren. Ich habe so etwas:

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

    ...

Ist es möglich, die Verwendung von isinstance zu vermeiden? Ich war auf der Suche nach etwas Entenfreundlicherem.

Während meiner Dekodierungsexperimente bin ich auf einige seltsame Verhaltensweisen von Python gestoßen. 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)

Ode

>>> 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

Apropos. Ich benutze Python 2.6

Antworten auf die Frage(4)

Ihre Antwort auf die Frage