![](/img/trans.png)
[英]How to define a binary string in Python in a way that works with both py2 and py3?
[英]How to convert an object to Unicode in a way that works in both py2 and py3?
我正在嘗試修復Python庫中的錯誤,該錯誤在我嘗試將對象轉換為字符串時發生。
str(obj) # fails on py2 when the object return unicode
unicode(obj) # works perfectly on py2 but fails on py3
由於從Python 2移至Python 3時unicode
轉換為標准str
類型( str
轉換為bytes
),因此以在Python 2和3中運行的方式解決此問題的一種方法是將unicode
定義為等效到str
在Python 3.運行時,這是在需要支持這兩個Python版本庫通常完成,實例可以在以下網址找到oauthlib.common
或requests.compat
(其包括一個更全面的兼容性層)。 每當他們需要確保他們需要在內部對該庫的任何調用將引用該類型bytes
或str
為不變量/斷言,鑄造等檢查時。
Django為此提供了一個簡潔的解決方案,他們為用戶提供了可以應用於該類的裝飾器。
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
雖然這取決於python庫6。 (請注意代碼許可證!)
您可以使用%s
格式在2.7中獲得unicode()並在3.5中獲得str(),只要您導入unicode_literals
,每個人都應該這樣做。
我發現這個技巧很有幫助,不需要到處都導入compat庫。
PY 2.7倍
>>> from __future__ import unicode_literals
>>> "%s" % 32
u'32' (<type 'unicode'>)
PY 3.5
>>> ("%s" % (42)).__class__
<class 'str'>
在此處添加此內容是因為它是我尋找除six.text_type(value)
或其他compat庫之外的其他東西時在google中出現的第一個結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.