def python_2_unicode_compatible(klass):
"""
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class.
"""
if six.PY2:
if '__str__' not in klass.__dict__:
raise ValueError("@python_2_unicode_compatible cannot be applied "
"to %s because it doesn't define __str__()." %
klass.__name__)
klass.__unicode__ = klass.__str__
klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
return klass
您可以使用
%s
格式来获得2.7中的unicode()和3.5中的str(),只要您导入unicode_literals
,每个人都应该这样做。在我发现这个技巧非常有用,它不需要到处导入compat库。在
PY 2.7倍
第3.5页
^{pr2}$在这里添加这个,因为这是我在寻找
six.text_type(value)
或其他compat库之外的东西时在google中出现的第一个结果。在由于在从Python2迁移到Python3时,}),所以在python2和python3中运行时,解决这个问题的一种方法是在python3中运行时将}等效。这通常是在需要同时支持这两个Python版本的库中完成的,可以在^{} 或^{} (其中包括更全面的兼容性层)找到示例。任何对该库的内部调用都将在需要时引用该类型,以确保在检查不变量/断言、强制转换等时需要}。在
unicode
被转换为标准的str
类型(其中str
会变成{unicode
定义为与{bytes
或{Django有一个很好的解决方案,他们为用户提供了一个可以应用于类的decorator。在
但这取决于python库6。(请注意代码许可证!)在
相关问题 更多 >
编程相关推荐