除非您知道我们不了解的内容,否则此代码是不正确的:
if isinstance(data, bytes):
data = data.decode()
您(似乎)不知道2700705067661001001728的编码。您假设它是UTF-8,但这很可能是错误的。 由于您不知道编码,因此没有文本。 您有字节,在阳光下可能有任何意义。
好消息是,大多数随机字节序列都不是有效的UTF-8,因此,如果中断,它将大声中断(默认为data),而不是默默地做错事。 更好的消息是,碰巧是有效UTF-8的大多数随机序列也都是有效ASCII,(几乎)每个人都同意如何解析。
坏消息是没有解决此问题的合理方法。 提供编码信息的标准方法是:使用data而不是bytes。如果某些第三方代码在没有任何其他上下文或信息的情况下将bytes或bytearray对象交给您,则唯一的正确操作是失败。
现在,假设您知道编码,则可以在此处使用data:
@functools.singledispatch
def foo(data, other_arguments, ...):
raise TypeError('Unknown type: '+repr(type(data)))
@foo.register(str)
def _(data, other_arguments, ...):
# data is a str
@foo.register(bytes)
@foo.register(bytearray)
def _(data, other_arguments, ...):
data = data.decode('encoding')
# explicit is better than implicit; don't leave the encoding out for UTF-8
return foo(data, other_arguments, ...)
这不适用于方法,并且data必须是第一个参数。 如果这些限制对您不起作用,请改用其他答案之一。