46 lines
1.2 KiB
Python
46 lines
1.2 KiB
Python
"""Compatibility with Python 2 (taken from 'django.utils.six')"""
|
|
import sys
|
|
|
|
PY2 = sys.version_info[0] == 2
|
|
PY3 = sys.version_info[0] == 3
|
|
|
|
|
|
if PY3:
|
|
string_types = (str,)
|
|
integer_types = (int,)
|
|
class_types = (type,)
|
|
text_type = str
|
|
binary_type = bytes
|
|
|
|
MAXSIZE = sys.maxsize
|
|
else:
|
|
string_types = (basestring,)
|
|
integer_types = (int, long)
|
|
|
|
|
|
def with_metaclass(meta, *bases):
|
|
class metaclass(type):
|
|
def __new__(cls, name, this_bases, d):
|
|
return meta(name, bases, d)
|
|
|
|
return type.__new__(metaclass, "temporary_class", (), {})
|
|
|
|
|
|
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 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
|