Commit be20ec70 authored by Carl Meyer's avatar Carl Meyer

Handle __str__/__unicode__ correctly for Python 2/3.

parent eb17f1bd
......@@ -2,7 +2,7 @@ from django.core.cache.backends.base import BaseCache, InvalidCacheBackendError
from django.core.exceptions import ImproperlyConfigured
from django.utils import importlib
from django.utils.datastructures import SortedDict
from .compat import smart_text, smart_bytes
from .compat import smart_text, smart_bytes, python_2_unicode_compatible
try:
import cPickle as pickle
......@@ -18,6 +18,7 @@ from redis.connection import UnixDomainSocketConnection, Connection
from redis.connection import DefaultParser
@python_2_unicode_compatible
class CacheKey(object):
"""
A stub string class that we can use to check if a key was created already.
......@@ -29,13 +30,10 @@ class CacheKey(object):
return self._key == other
def __str__(self):
return self.__unicode__()
return smart_text(self._key)
def __repr__(self):
return self.__unicode__()
def __unicode__(self):
return smart_text(self._key)
return repr(self._key)
def __hash__(self):
return hash(self._key)
......
import sys
PY3 = (sys.version_info >= (3,))
try:
# Django 1.5+
from django.utils.encoding import smart_text, smart_bytes
......@@ -6,3 +10,19 @@ except ImportError:
from django.utils.encoding import smart_unicode, smart_str
smart_text = smart_unicode
smart_bytes = smart_str
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.
Backported from Django 1.5+.
"""
if not PY3:
klass.__unicode__ = klass.__str__
klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
return klass
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment