You'll have to test for the type, I am afraid:
def to_utf8_string(val):
if not isinstance(val, basestring):
return str(val)
if not isinstance(val, str):
val = val.encode('utf8')
return val
This is pretty much what the print()
command does, albeit that it detects what encoding to use from the sys.stdout
stream before encoding.