Skip to content

Commit

Permalink
Remove Python 2 (#27)
Browse files Browse the repository at this point in the history
* removed __future__ imports and explicit encodings
* removed six dependency and code
* fixed py2/3 specific imports
* removed python2 specific code
* don't mention unittest2 anymore
  • Loading branch information
venthur committed Aug 18, 2021
1 parent 4b9a12c commit 5e9e1af
Show file tree
Hide file tree
Showing 10 changed files with 87 additions and 630 deletions.
89 changes: 17 additions & 72 deletions feedgenerator/django/utils/encoding.py
@@ -1,17 +1,10 @@
from __future__ import unicode_literals

import codecs
import datetime
from decimal import Decimal
import locale
try:
from urllib.parse import quote
except ImportError: # Python 2
from urllib import quote
import warnings
from urllib.parse import quote

from .functional import Promise
from . import six

class DjangoUnicodeDecodeError(UnicodeDecodeError):
def __init__(self, obj, *args):
Expand All @@ -23,42 +16,6 @@ def __str__(self):
return '%s. You passed in %r (%s)' % (original, self.obj,
type(self.obj))

class StrAndUnicode(object):
"""
A class that derives __str__ from __unicode__.
On Python 2, __str__ returns the output of __unicode__ encoded as a UTF-8
bytestring. On Python 3, __str__ returns the output of __unicode__.
Useful as a mix-in. If you support Python 2 and 3 with a single code base,
you can inherit this mix-in and just define __unicode__.
"""
def __init__(self, *args, **kwargs):
warnings.warn("StrAndUnicode is deprecated. Define a __str__ method "
"and apply the @python_2_unicode_compatible decorator "
"instead.", PendingDeprecationWarning, stacklevel=2)
super(StrAndUnicode, self).__init__(*args, **kwargs)

if six.PY3:
def __str__(self):
return self.__unicode__()
else:
def __str__(self):
return self.__unicode__().encode('utf-8')

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 not six.PY3:
klass.__unicode__ = klass.__str__
klass.__str__ = lambda self: self.__unicode__().encode('utf-8')
return klass

def smart_text(s, encoding='utf-8', strings_only=False, errors='strict'):
"""
Returns a text object representing 's' -- unicode on Python 2 and str on
Expand All @@ -77,7 +34,7 @@ def is_protected_type(obj):
Objects of protected types are preserved as-is when passed to
force_text(strings_only=True).
"""
return isinstance(obj, six.integer_types + (type(None), float, Decimal,
return isinstance(obj, (int, ) + (type(None), float, Decimal,
datetime.datetime, datetime.date, datetime.time))

def force_text(s, encoding='utf-8', strings_only=False, errors='strict'):
Expand All @@ -87,25 +44,22 @@ def force_text(s, encoding='utf-8', strings_only=False, errors='strict'):
If strings_only is True, don't convert (some) non-string-like objects.
"""
# Handle the common case first, saves 30-40% when s is an instance of
# six.text_type. This function gets called often in that setting.
if isinstance(s, six.text_type):
# Handle the common case first, saves 30-40% when s is an instance
# of str. This function gets called often in that setting.
if isinstance(s, str):
return s
if strings_only and is_protected_type(s):
return s
try:
if not isinstance(s, six.string_types):
if not isinstance(s, str):
if hasattr(s, '__unicode__'):
s = s.__unicode__()
else:
try:
if six.PY3:
if isinstance(s, bytes):
s = six.text_type(s, encoding, errors)
else:
s = six.text_type(s)
if isinstance(s, bytes):
s = str(s, encoding, errors)
else:
s = six.text_type(bytes(s), encoding, errors)
s = str(s)
except UnicodeEncodeError:
if not isinstance(s, Exception):
raise
Expand All @@ -118,7 +72,7 @@ def force_text(s, encoding='utf-8', strings_only=False, errors='strict'):
s = ' '.join([force_text(arg, encoding, strings_only,
errors) for arg in s])
else:
# Note: We use .decode() here, instead of six.text_type(s, encoding,
# Note: We use .decode() here, instead of str(s, encoding,
# errors), so that if s is a SafeBytes, it ends up being a
# SafeText at the end.
s = s.decode(encoding, errors)
Expand Down Expand Up @@ -162,33 +116,24 @@ def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
if strings_only and (s is None or isinstance(s, int)):
return s
if isinstance(s, Promise):
return six.text_type(s).encode(encoding, errors)
if not isinstance(s, six.string_types):
return str.encode(encoding, errors)
if not isinstance(s, str):
try:
if six.PY3:
return six.text_type(s).encode(encoding)
else:
return bytes(s)
return str(s).encode(encoding)
except UnicodeEncodeError:
if isinstance(s, Exception):
# An Exception subclass containing non-ASCII data that doesn't
# know how to print itself properly. We shouldn't raise a
# further exception.
return ' '.join([smart_bytes(arg, encoding, strings_only,
errors) for arg in s])
return six.text_type(s).encode(encoding, errors)
return str(s).encode(encoding, errors)
else:
return s.encode(encoding, errors)

if six.PY3:
smart_str = smart_text
force_str = force_text
else:
smart_str = smart_bytes
force_str = force_bytes
# backwards compatibility for Python 2
smart_unicode = smart_text
force_unicode = force_text

smart_str = smart_text
force_str = force_text

smart_str.__doc__ = """\
Apply smart_text in Python 3 and smart_bytes in Python 2.
Expand Down
14 changes: 2 additions & 12 deletions feedgenerator/django/utils/feedgenerator.py
Expand Up @@ -21,18 +21,12 @@
For definitions of the different versions of RSS, see:
http://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004/02/04/incompatible-rss
"""
from __future__ import unicode_literals

import datetime
try:
from urllib.parse import urlparse
except ImportError: # Python 2
from urlparse import urlparse
from urllib.parse import urlparse
from .xmlutils import SimplerXMLGenerator
from .encoding import force_text, iri_to_uri
from . import datetime_safe
from . import six
from .six import StringIO
from io import StringIO
from .timezone import is_aware

def rfc2822_date(date):
Expand All @@ -46,8 +40,6 @@ def rfc2822_date(date):
dow = days[date.weekday()]
month = months[date.month - 1]
time_str = date.strftime('%s, %%d %s %%Y %%H:%%M:%%S ' % (dow, month))
if not six.PY3: # strftime returns a byte string in Python 2
time_str = time_str.decode('utf-8')
if is_aware(date):
offset = date.tzinfo.utcoffset(date)
timezone = (offset.days * 24 * 60) + (offset.seconds // 60)
Expand All @@ -60,8 +52,6 @@ def rfc3339_date(date):
# Support datetime objects older than 1900
date = datetime_safe.new_datetime(date)
time_str = date.strftime('%Y-%m-%dT%H:%M:%S')
if not six.PY3: # strftime returns a byte string in Python 2
time_str = time_str.decode('utf-8')
if is_aware(date):
offset = date.tzinfo.utcoffset(date)
timezone = (offset.days * 24 * 60) + (offset.seconds // 60)
Expand Down
64 changes: 9 additions & 55 deletions feedgenerator/django/utils/functional.py
Expand Up @@ -3,8 +3,6 @@
from functools import wraps, update_wrapper
import sys

from . import six

# You can't trivially replace this `functools.partial` because this binds to
# classes and returns bound instances, whereas functools.partial (on CPython)
# is a type and its instances don't bind.
Expand Down Expand Up @@ -94,18 +92,12 @@ def __prepare_class__(cls):
continue
setattr(cls, k, meth)
cls._delegate_bytes = bytes in resultclasses
cls._delegate_text = six.text_type in resultclasses
cls._delegate_text = str in resultclasses
assert not (cls._delegate_bytes and cls._delegate_text), "Cannot call lazy() with both bytes and text return types."
if cls._delegate_text:
if six.PY3:
cls.__str__ = cls.__text_cast
else:
cls.__unicode__ = cls.__text_cast
cls.__str__ = cls.__text_cast
elif cls._delegate_bytes:
if six.PY3:
cls.__bytes__ = cls.__bytes_cast
else:
cls.__str__ = cls.__bytes_cast
cls.__bytes__ = cls.__bytes_cast
__prepare_class__ = classmethod(__prepare_class__)

def __promise__(cls, klass, funcname, method):
Expand Down Expand Up @@ -153,10 +145,8 @@ def __lt__(self, other):
__hash__ = object.__hash__

def __mod__(self, rhs):
if self._delegate_bytes and not six.PY3:
return bytes(self) % rhs
elif self._delegate_text:
return six.text_type(self) % rhs
if self._delegate_text:
return str(self) % rhs
else:
raise AssertionError('__mod__ not supported for non-string types')

Expand Down Expand Up @@ -186,7 +176,7 @@ def allow_lazy(func, *resultclasses):
"""
@wraps(func)
def wrapper(*args, **kwargs):
for arg in list(args) + list(six.itervalues(kwargs)):
for arg in list(args) + list(kwargs.values()):
if isinstance(arg, Promise):
break
else:
Expand Down Expand Up @@ -266,12 +256,8 @@ def __init__(self, func):
def _setup(self):
self._wrapped = self._setupfunc()

if six.PY3:
__bytes__ = new_method_proxy(bytes)
__str__ = new_method_proxy(str)
else:
__str__ = new_method_proxy(str)
__unicode__ = new_method_proxy(unicode)
__bytes__ = new_method_proxy(bytes)
__str__ = new_method_proxy(str)

def __deepcopy__(self, memo):
if self._wrapped is empty:
Expand Down Expand Up @@ -335,36 +321,4 @@ def partition(predicate, values):
results[predicate(item)].append(item)
return results

if sys.version_info >= (2,7,2):
from functools import total_ordering
else:
# For Python < 2.7.2. Python 2.6 does not have total_ordering, and
# total_ordering in 2.7 versions prior to 2.7.2 is buggy. See
# http://bugs.python.org/issue10042 for details. For these versions use
# code borrowed from Python 2.7.3.
def total_ordering(cls):
"""Class decorator that fills in missing ordering methods"""
convert = {
'__lt__': [('__gt__', lambda self, other: not (self < other or self == other)),
('__le__', lambda self, other: self < other or self == other),
('__ge__', lambda self, other: not self < other)],
'__le__': [('__ge__', lambda self, other: not self <= other or self == other),
('__lt__', lambda self, other: self <= other and not self == other),
('__gt__', lambda self, other: not self <= other)],
'__gt__': [('__lt__', lambda self, other: not (self > other or self == other)),
('__ge__', lambda self, other: self > other or self == other),
('__le__', lambda self, other: not self > other)],
'__ge__': [('__le__', lambda self, other: (not self >= other) or self == other),
('__gt__', lambda self, other: self >= other and not self == other),
('__lt__', lambda self, other: not self >= other)]
}
roots = set(dir(cls)) & set(convert)
if not roots:
raise ValueError('must define at least one ordering operation: < > <= >=')
root = max(roots) # prefer __lt__ to __le__ to __gt__ to __ge__
for opname, opfunc in convert[root]:
if opname not in roots:
opfunc.__name__ = opname
opfunc.__doc__ = getattr(int, opname).__doc__
setattr(cls, opname, opfunc)
return cls
from functools import total_ordering

0 comments on commit 5e9e1af

Please sign in to comment.