diff --git a/django/conf/urls/__init__.py b/django/conf/urls/__init__.py
index 45af3a10d2..16db0f2fea 100644
--- a/django/conf/urls/__init__.py
+++ b/django/conf/urls/__init__.py
@@ -4,7 +4,6 @@ from django.core.exceptions import ImproperlyConfigured
from django.urls import (
LocaleRegexURLResolver, RegexURLPattern, RegexURLResolver,
)
-from django.utils import six
__all__ = ['handler400', 'handler403', 'handler404', 'handler500', 'include', 'url']
@@ -34,7 +33,7 @@ def include(arg, namespace=None):
# No namespace hint - use manually provided namespace
urlconf_module = arg
- if isinstance(urlconf_module, six.string_types):
+ if isinstance(urlconf_module, str):
urlconf_module = import_module(urlconf_module)
patterns = getattr(urlconf_module, 'urlpatterns', urlconf_module)
app_name = getattr(urlconf_module, 'app_name', app_name)
diff --git a/django/contrib/admin/helpers.py b/django/contrib/admin/helpers.py
index ea56840445..628788b3fa 100644
--- a/django/contrib/admin/helpers.py
+++ b/django/contrib/admin/helpers.py
@@ -10,7 +10,6 @@ from django.core.exceptions import ObjectDoesNotExist
from django.db.models.fields.related import ManyToManyRel
from django.forms.utils import flatatt
from django.template.defaultfilters import capfirst, linebreaksbr
-from django.utils import six
from django.utils.encoding import force_text
from django.utils.html import conditional_escape, format_html
from django.utils.safestring import mark_safe
@@ -99,7 +98,7 @@ class Fieldset(object):
class Fieldline(object):
def __init__(self, form, field, readonly_fields=None, model_admin=None):
self.form = form # A django.forms.Form instance
- if not hasattr(field, "__iter__") or isinstance(field, six.text_type):
+ if not hasattr(field, "__iter__") or isinstance(field, str):
self.fields = [field]
else:
self.fields = field
@@ -217,7 +216,7 @@ class AdminReadonlyField(object):
result_repr = linebreaksbr(force_text(value))
else:
if isinstance(f.remote_field, ManyToManyRel) and value is not None:
- result_repr = ", ".join(map(six.text_type, value.all()))
+ result_repr = ", ".join(map(str, value.all()))
else:
result_repr = display_for_field(value, f, self.empty_value_display)
result_repr = linebreaksbr(result_repr)
diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py
index bb871513d7..eaa9916056 100644
--- a/django/contrib/admin/options.py
+++ b/django/contrib/admin/options.py
@@ -1068,8 +1068,8 @@ class ModelAdmin(BaseModelAdmin):
attr = obj._meta.pk.attname
value = obj.serializable_value(attr)
popup_response_data = json.dumps({
- 'value': six.text_type(value),
- 'obj': six.text_type(obj),
+ 'value': str(value),
+ 'obj': str(obj),
})
return TemplateResponse(request, self.popup_response_template or [
'admin/%s/%s/popup_response.html' % (opts.app_label, opts.model_name),
@@ -1129,9 +1129,9 @@ class ModelAdmin(BaseModelAdmin):
new_value = obj.serializable_value(attr)
popup_response_data = json.dumps({
'action': 'change',
- 'value': six.text_type(value),
- 'obj': six.text_type(obj),
- 'new_value': six.text_type(new_value),
+ 'value': str(value),
+ 'obj': str(obj),
+ 'new_value': str(new_value),
})
return TemplateResponse(request, self.popup_response_template or [
'admin/%s/%s/popup_response.html' % (opts.app_label, opts.model_name),
diff --git a/django/contrib/admin/utils.py b/django/contrib/admin/utils.py
index cf17381548..297796254d 100644
--- a/django/contrib/admin/utils.py
+++ b/django/contrib/admin/utils.py
@@ -10,7 +10,7 @@ from django.db.models.deletion import Collector
from django.db.models.sql.constants import QUERY_TERMS
from django.forms.utils import pretty_name
from django.urls import NoReverseMatch, reverse
-from django.utils import formats, six, timezone
+from django.utils import formats, timezone
from django.utils.encoding import force_str, force_text, smart_text
from django.utils.html import format_html
from django.utils.text import capfirst
@@ -68,7 +68,7 @@ def quote(s):
Similar to urllib.quote, except that the quoting is slightly different so
that it doesn't get automatically unquoted by the Web browser.
"""
- if not isinstance(s, six.string_types):
+ if not isinstance(s, str):
return s
res = list(s)
for i in range(len(res)):
@@ -342,7 +342,7 @@ def label_for_field(name, model, model_admin=None, return_attr=False):
except FieldDoesNotExist:
if name == "__unicode__":
label = force_text(model._meta.verbose_name)
- attr = six.text_type
+ attr = str
elif name == "__str__":
label = force_str(model._meta.verbose_name)
attr = bytes
@@ -430,7 +430,7 @@ def display_for_value(value, empty_value_display, boolean=False):
return formats.localize(timezone.template_localtime(value))
elif isinstance(value, (datetime.date, datetime.time)):
return formats.localize(value)
- elif isinstance(value, six.integer_types + (decimal.Decimal, float)):
+ elif isinstance(value, (int, decimal.Decimal, float)):
return formats.number_format(value)
elif isinstance(value, (list, tuple)):
return ', '.join(force_text(v) for v in value)
diff --git a/django/contrib/admin/widgets.py b/django/contrib/admin/widgets.py
index 9f93ae3a42..9f6fb412b2 100644
--- a/django/contrib/admin/widgets.py
+++ b/django/contrib/admin/widgets.py
@@ -7,7 +7,6 @@ from django import forms
from django.db.models.deletion import CASCADE
from django.urls import reverse
from django.urls.exceptions import NoReverseMatch
-from django.utils import six
from django.utils.encoding import force_text
from django.utils.html import smart_urlquote
from django.utils.safestring import mark_safe
@@ -111,7 +110,7 @@ def url_params_from_lookup_dict(lookups):
elif isinstance(v, bool):
v = ('0', '1')[v]
else:
- v = six.text_type(v)
+ v = str(v)
items.append((k, v))
params.update(dict(items))
return params
diff --git a/django/contrib/auth/decorators.py b/django/contrib/auth/decorators.py
index 9c44108c89..f6e4c1d5b2 100644
--- a/django/contrib/auth/decorators.py
+++ b/django/contrib/auth/decorators.py
@@ -4,7 +4,6 @@ from django.conf import settings
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.core.exceptions import PermissionDenied
from django.shortcuts import resolve_url
-from django.utils import six
from django.utils.decorators import available_attrs
from django.utils.six.moves.urllib.parse import urlparse
@@ -60,7 +59,7 @@ def permission_required(perm, login_url=None, raise_exception=False):
is raised.
"""
def check_perms(user):
- if isinstance(perm, six.string_types):
+ if isinstance(perm, str):
perms = (perm, )
else:
perms = perm
diff --git a/django/contrib/auth/mixins.py b/django/contrib/auth/mixins.py
index 4a7759435b..c52b573658 100644
--- a/django/contrib/auth/mixins.py
+++ b/django/contrib/auth/mixins.py
@@ -2,7 +2,6 @@ from django.conf import settings
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.views import redirect_to_login
from django.core.exceptions import ImproperlyConfigured, PermissionDenied
-from django.utils import six
from django.utils.encoding import force_text
@@ -73,7 +72,7 @@ class PermissionRequiredMixin(AccessMixin):
'{0} is missing the permission_required attribute. Define {0}.permission_required, or override '
'{0}.get_permission_required().'.format(self.__class__.__name__)
)
- if isinstance(self.permission_required, six.string_types):
+ if isinstance(self.permission_required, str):
perms = (self.permission_required, )
else:
perms = self.permission_required
diff --git a/django/contrib/auth/models.py b/django/contrib/auth/models.py
index 7155bd1199..0fc2ab41da 100644
--- a/django/contrib/auth/models.py
+++ b/django/contrib/auth/models.py
@@ -6,7 +6,7 @@ from django.core.exceptions import PermissionDenied
from django.core.mail import send_mail
from django.db import models
from django.db.models.manager import EmptyManager
-from django.utils import six, timezone
+from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from .validators import UnicodeUsernameValidator
@@ -75,9 +75,10 @@ class Permission(models.Model):
def __str__(self):
return "%s | %s | %s" % (
- six.text_type(self.content_type.app_label),
- six.text_type(self.content_type),
- six.text_type(self.name))
+ self.content_type.app_label,
+ self.content_type,
+ self.name,
+ )
def natural_key(self):
return (self.codename,) + self.content_type.natural_key()
diff --git a/django/contrib/auth/password_validation.py b/django/contrib/auth/password_validation.py
index d802a5f5fd..1cf32e0219 100644
--- a/django/contrib/auth/password_validation.py
+++ b/django/contrib/auth/password_validation.py
@@ -13,7 +13,6 @@ from django.utils.encoding import force_text
from django.utils.functional import lazy
from django.utils.html import format_html
from django.utils.module_loading import import_string
-from django.utils.six import string_types, text_type
from django.utils.translation import ugettext as _, ungettext
@@ -88,7 +87,7 @@ def _password_validators_help_text_html(password_validators=None):
return '
%s
' % ''.join(help_items) if help_items else ''
-password_validators_help_text_html = lazy(_password_validators_help_text_html, text_type)
+password_validators_help_text_html = lazy(_password_validators_help_text_html, str)
class MinimumLengthValidator(object):
@@ -141,7 +140,7 @@ class UserAttributeSimilarityValidator(object):
for attribute_name in self.user_attributes:
value = getattr(user, attribute_name, None)
- if not value or not isinstance(value, string_types):
+ if not value or not isinstance(value, str):
continue
value_parts = re.split(r'\W+', value) + [value]
for value_part in value_parts:
diff --git a/django/contrib/auth/tokens.py b/django/contrib/auth/tokens.py
index 6cf694cebb..18ff42f192 100644
--- a/django/contrib/auth/tokens.py
+++ b/django/contrib/auth/tokens.py
@@ -1,7 +1,6 @@
from datetime import date
from django.conf import settings
-from django.utils import six
from django.utils.crypto import constant_time_compare, salted_hmac
from django.utils.http import base36_to_int, int_to_base36
@@ -68,10 +67,7 @@ class PasswordResetTokenGenerator(object):
def _make_hash_value(self, user, timestamp):
# Ensure results are consistent across DB backends
login_timestamp = '' if user.last_login is None else user.last_login.replace(microsecond=0, tzinfo=None)
- return (
- six.text_type(user.pk) + user.password +
- six.text_type(login_timestamp) + six.text_type(timestamp)
- )
+ return str(user.pk) + user.password + str(login_timestamp) + str(timestamp)
def _num_days(self, dt):
return (dt - date(2001, 1, 1)).days
diff --git a/django/contrib/gis/admin/widgets.py b/django/contrib/gis/admin/widgets.py
index 014b3ad818..b76e860324 100644
--- a/django/contrib/gis/admin/widgets.py
+++ b/django/contrib/gis/admin/widgets.py
@@ -3,7 +3,7 @@ import logging
from django.contrib.gis.gdal import GDALException
from django.contrib.gis.geos import GEOSException, GEOSGeometry
from django.forms.widgets import Textarea
-from django.utils import six, translation
+from django.utils import translation
# Creating a template context that contains Django settings
# values needed by admin map templates.
@@ -30,7 +30,7 @@ class OpenLayersWidget(Textarea):
# If a string reaches here (via a validation error on another
# field) then just reconstruct the Geometry.
- if value and isinstance(value, six.string_types):
+ if value and isinstance(value, str):
try:
value = GEOSGeometry(value)
except (GEOSException, ValueError) as err:
diff --git a/django/contrib/gis/db/backends/base/models.py b/django/contrib/gis/db/backends/base/models.py
index 8c8bdc6346..8388a27f25 100644
--- a/django/contrib/gis/db/backends/base/models.py
+++ b/django/contrib/gis/db/backends/base/models.py
@@ -1,5 +1,4 @@
from django.contrib.gis import gdal
-from django.utils import six
class SpatialRefSysMixin(object):
@@ -134,4 +133,4 @@ class SpatialRefSysMixin(object):
"""
Returns the string representation, a 'pretty' OGC WKT.
"""
- return six.text_type(self.srs)
+ return str(self.srs)
diff --git a/django/contrib/gis/db/backends/oracle/operations.py b/django/contrib/gis/db/backends/oracle/operations.py
index 013ffa74f6..a431b916be 100644
--- a/django/contrib/gis/db/backends/oracle/operations.py
+++ b/django/contrib/gis/db/backends/oracle/operations.py
@@ -17,7 +17,6 @@ from django.contrib.gis.db.models import aggregates
from django.contrib.gis.geometry.backend import Geometry
from django.contrib.gis.measure import Distance
from django.db.backends.oracle.operations import DatabaseOperations
-from django.utils import six
from django.utils.functional import cached_property
DEFAULT_TOLERANCE = '0.05'
@@ -45,7 +44,7 @@ class SDORelate(SpatialOperator):
def check_relate_argument(self, arg):
masks = 'TOUCH|OVERLAPBDYDISJOINT|OVERLAPBDYINTERSECT|EQUAL|INSIDE|COVEREDBY|CONTAINS|COVERS|ANYINTERACT|ON'
mask_regex = re.compile(r'^(%s)(\+(%s))*$' % (masks, masks), re.I)
- if not isinstance(arg, six.string_types) or not mask_regex.match(arg):
+ if not isinstance(arg, str) or not mask_regex.match(arg):
raise ValueError('Invalid SDO_RELATE mask: "%s"' % arg)
def as_sql(self, connection, lookup, template_params, sql_params):
diff --git a/django/contrib/gis/db/backends/postgis/operations.py b/django/contrib/gis/db/backends/postgis/operations.py
index ae0821694a..678c420c23 100644
--- a/django/contrib/gis/db/backends/postgis/operations.py
+++ b/django/contrib/gis/db/backends/postgis/operations.py
@@ -9,7 +9,6 @@ from django.contrib.gis.measure import Distance
from django.core.exceptions import ImproperlyConfigured
from django.db.backends.postgresql.operations import DatabaseOperations
from django.db.utils import ProgrammingError
-from django.utils import six
from django.utils.functional import cached_property
from .adapter import PostGISAdapter
@@ -337,7 +336,7 @@ class PostGISOperations(BaseSpatialOperations, DatabaseOperations):
# Get the srid for this object
if value is None:
value_srid = None
- elif f.geom_type == 'RASTER' and isinstance(value, six.string_types):
+ elif f.geom_type == 'RASTER' and isinstance(value, str):
value_srid = get_pgraster_srid(value)
else:
value_srid = value.srid
@@ -346,7 +345,7 @@ class PostGISOperations(BaseSpatialOperations, DatabaseOperations):
# is not equal to the field srid.
if value_srid is None or value_srid == f.srid:
placeholder = '%s'
- elif f.geom_type == 'RASTER' and isinstance(value, six.string_types):
+ elif f.geom_type == 'RASTER' and isinstance(value, str):
placeholder = '%s((%%s)::raster, %s)' % (self.transform, f.srid)
else:
placeholder = '%s(%%s, %s)' % (self.transform, f.srid)
diff --git a/django/contrib/gis/db/backends/spatialite/introspection.py b/django/contrib/gis/db/backends/spatialite/introspection.py
index 6c3ed1864c..467e3a44f7 100644
--- a/django/contrib/gis/db/backends/spatialite/introspection.py
+++ b/django/contrib/gis/db/backends/spatialite/introspection.py
@@ -2,7 +2,6 @@ from django.contrib.gis.gdal import OGRGeomType
from django.db.backends.sqlite3.introspection import (
DatabaseIntrospection, FlexibleFieldLookupDict,
)
-from django.utils import six
class GeoFlexibleFieldLookupDict(FlexibleFieldLookupDict):
@@ -41,7 +40,7 @@ class SpatiaLiteIntrospection(DatabaseIntrospection):
# OGRGeomType does not require GDAL and makes it easy to convert
# from OGC geom type name to Django field.
ogr_type = row[2]
- if isinstance(ogr_type, six.integer_types) and ogr_type > 1000:
+ if isinstance(ogr_type, int) and ogr_type > 1000:
# SpatiaLite versions >= 4 use the new SFSQL 1.2 offsets
# 1000 (Z), 2000 (M), and 3000 (ZM) to indicate the presence of
# higher dimensional coordinates (M not yet supported by Django).
@@ -54,7 +53,7 @@ class SpatiaLiteIntrospection(DatabaseIntrospection):
field_params = {}
if srid != 4326:
field_params['srid'] = srid
- if (isinstance(dim, six.string_types) and 'Z' in dim) or dim == 3:
+ if (isinstance(dim, str) and 'Z' in dim) or dim == 3:
field_params['dim'] = 3
finally:
cursor.close()
diff --git a/django/contrib/gis/db/models/fields.py b/django/contrib/gis/db/models/fields.py
index 215a17b6b5..6435dc4077 100644
--- a/django/contrib/gis/db/models/fields.py
+++ b/django/contrib/gis/db/models/fields.py
@@ -10,7 +10,6 @@ from django.contrib.gis.geometry.backend import Geometry, GeometryException
from django.core.exceptions import ImproperlyConfigured
from django.db.models.expressions import Expression
from django.db.models.fields import Field
-from django.utils import six
from django.utils.translation import ugettext_lazy as _
# Local cache of the spatial_ref_sys table, which holds SRID data for each
@@ -226,7 +225,7 @@ class BaseSpatialField(Field):
pass
else:
# Check if input is a candidate for conversion to raster or geometry.
- is_candidate = isinstance(obj, (bytes, six.string_types)) or hasattr(obj, '__geo_interface__')
+ is_candidate = isinstance(obj, (bytes, str)) or hasattr(obj, '__geo_interface__')
# Try to convert the input to raster.
raster = self.get_raster_prep_value(obj, is_candidate)
diff --git a/django/contrib/gis/db/models/functions.py b/django/contrib/gis/db/models/functions.py
index 8a4d54aac1..77628afa34 100644
--- a/django/contrib/gis/db/models/functions.py
+++ b/django/contrib/gis/db/models/functions.py
@@ -9,9 +9,8 @@ from django.contrib.gis.measure import (
from django.core.exceptions import FieldError
from django.db.models import BooleanField, FloatField, IntegerField, TextField
from django.db.models.expressions import Func, Value
-from django.utils import six
-NUMERIC_TYPES = six.integer_types + (float, Decimal)
+NUMERIC_TYPES = (int, float, Decimal)
class GeoFunc(Func):
@@ -161,7 +160,7 @@ class AsGeoJSON(GeoFunc):
def __init__(self, expression, bbox=False, crs=False, precision=8, **extra):
expressions = [expression]
if precision is not None:
- expressions.append(self._handle_param(precision, 'precision', six.integer_types))
+ expressions.append(self._handle_param(precision, 'precision', int))
options = 0
if crs and bbox:
options = 3
@@ -181,7 +180,7 @@ class AsGML(GeoFunc):
def __init__(self, expression, version=2, precision=8, **extra):
expressions = [version, expression]
if precision is not None:
- expressions.append(self._handle_param(precision, 'precision', six.integer_types))
+ expressions.append(self._handle_param(precision, 'precision', int))
super(AsGML, self).__init__(*expressions, **extra)
def as_oracle(self, compiler, connection, **extra_context):
@@ -208,7 +207,7 @@ class AsSVG(GeoFunc):
expressions = [
expression,
relative,
- self._handle_param(precision, 'precision', six.integer_types),
+ self._handle_param(precision, 'precision', int),
]
super(AsSVG, self).__init__(*expressions, **extra)
@@ -311,7 +310,7 @@ class GeoHash(GeoFunc):
def __init__(self, expression, precision=None, **extra):
expressions = [expression]
if precision is not None:
- expressions.append(self._handle_param(precision, 'precision', six.integer_types))
+ expressions.append(self._handle_param(precision, 'precision', int))
super(GeoHash, self).__init__(*expressions, **extra)
@@ -458,7 +457,7 @@ class Transform(GeoFunc):
def __init__(self, expression, srid, **extra):
expressions = [
expression,
- self._handle_param(srid, 'srid', six.integer_types),
+ self._handle_param(srid, 'srid', int),
]
if 'output_field' not in extra:
extra['output_field'] = GeometryField(srid=srid)
diff --git a/django/contrib/gis/db/models/lookups.py b/django/contrib/gis/db/models/lookups.py
index b707a9cbff..3b2d4b8497 100644
--- a/django/contrib/gis/db/models/lookups.py
+++ b/django/contrib/gis/db/models/lookups.py
@@ -5,7 +5,6 @@ from django.db.models.constants import LOOKUP_SEP
from django.db.models.expressions import Col, Expression
from django.db.models.lookups import Lookup, Transform
from django.db.models.sql.query import Query
-from django.utils import six
gis_lookups = {}
@@ -389,7 +388,7 @@ class RelateLookup(GISLookup):
backend_op.check_relate_argument(value[1])
else:
pattern = value[1]
- if not isinstance(pattern, six.string_types) or not self.pattern_regex.match(pattern):
+ if not isinstance(pattern, str) or not self.pattern_regex.match(pattern):
raise ValueError('Invalid intersection matrix pattern "%s".' % pattern)
return super(RelateLookup, self).get_db_prep_lookup(value, connection)
diff --git a/django/contrib/gis/db/models/proxy.py b/django/contrib/gis/db/models/proxy.py
index 340e76f4bf..86221daca7 100644
--- a/django/contrib/gis/db/models/proxy.py
+++ b/django/contrib/gis/db/models/proxy.py
@@ -6,7 +6,6 @@ objects corresponding to geographic model fields.
Thanks to Robert Coup for providing this functionality (see #4322).
"""
from django.db.models.query_utils import DeferredAttribute
-from django.utils import six
class SpatialProxy(DeferredAttribute):
@@ -58,7 +57,7 @@ class SpatialProxy(DeferredAttribute):
# The geographic type of the field.
gtype = self._field.geom_type
- if gtype == 'RASTER' and (value is None or isinstance(value, six.string_types + (dict, self._klass))):
+ if gtype == 'RASTER' and (value is None or isinstance(value, (str, dict, self._klass))):
# For raster fields, assure input is None or a string, dict, or
# raster instance.
pass
@@ -68,7 +67,7 @@ class SpatialProxy(DeferredAttribute):
if value.srid is None:
# Assigning the field SRID if the geometry has no SRID.
value.srid = self._field.srid
- elif value is None or isinstance(value, six.string_types + (six.memoryview,)):
+ elif value is None or isinstance(value, (str, memoryview)):
# Set geometries with None, WKT, HEX, or WKB
pass
else:
diff --git a/django/contrib/gis/forms/widgets.py b/django/contrib/gis/forms/widgets.py
index 2e7e530cc2..0c1fc23c81 100644
--- a/django/contrib/gis/forms/widgets.py
+++ b/django/contrib/gis/forms/widgets.py
@@ -4,7 +4,7 @@ from django.conf import settings
from django.contrib.gis import gdal
from django.contrib.gis.geos import GEOSException, GEOSGeometry
from django.forms.widgets import Widget
-from django.utils import six, translation
+from django.utils import translation
logger = logging.getLogger('django.contrib.gis')
@@ -43,7 +43,7 @@ class BaseGeometryWidget(Widget):
def get_context(self, name, value, attrs=None):
# If a string reaches here (via a validation error on another
# field) then just reconstruct the Geometry.
- if value and isinstance(value, six.string_types):
+ if value and isinstance(value, str):
value = self.deserialize(value)
if value:
diff --git a/django/contrib/gis/gdal/datasource.py b/django/contrib/gis/gdal/datasource.py
index 4588a1731a..1ff2326a63 100644
--- a/django/contrib/gis/gdal/datasource.py
+++ b/django/contrib/gis/gdal/datasource.py
@@ -40,7 +40,6 @@ from django.contrib.gis.gdal.driver import Driver
from django.contrib.gis.gdal.error import GDALException, OGRIndexError
from django.contrib.gis.gdal.layer import Layer
from django.contrib.gis.gdal.prototypes import ds as capi
-from django.utils import six
from django.utils.encoding import force_bytes, force_text
from django.utils.six.moves import range
@@ -64,7 +63,7 @@ class DataSource(GDALBase):
Driver.ensure_registered()
- if isinstance(ds_input, six.string_types):
+ if isinstance(ds_input, str):
# The data source driver is a void pointer.
ds_driver = Driver.ptr_type()
try:
@@ -93,7 +92,7 @@ class DataSource(GDALBase):
def __getitem__(self, index):
"Allows use of the index [] operator to get a layer at the index."
- if isinstance(index, six.string_types):
+ if isinstance(index, str):
layer = capi.get_layer_by_name(self.ptr, force_bytes(index))
if not layer:
raise OGRIndexError('invalid OGR Layer name given: "%s"' % index)
diff --git a/django/contrib/gis/gdal/driver.py b/django/contrib/gis/gdal/driver.py
index 7ed4587073..20ebaeff20 100644
--- a/django/contrib/gis/gdal/driver.py
+++ b/django/contrib/gis/gdal/driver.py
@@ -3,7 +3,6 @@ from ctypes import c_void_p
from django.contrib.gis.gdal.base import GDALBase
from django.contrib.gis.gdal.error import GDALException
from django.contrib.gis.gdal.prototypes import ds as vcapi, raster as rcapi
-from django.utils import six
from django.utils.encoding import force_bytes, force_text
@@ -36,7 +35,7 @@ class Driver(GDALBase):
"""
Initializes an GDAL/OGR driver on either a string or integer input.
"""
- if isinstance(dr_input, six.string_types):
+ if isinstance(dr_input, str):
# If a string name of the driver was passed in
self.ensure_registered()
diff --git a/django/contrib/gis/gdal/feature.py b/django/contrib/gis/gdal/feature.py
index 2335df733b..8975b9c076 100644
--- a/django/contrib/gis/gdal/feature.py
+++ b/django/contrib/gis/gdal/feature.py
@@ -3,7 +3,6 @@ from django.contrib.gis.gdal.error import GDALException, OGRIndexError
from django.contrib.gis.gdal.field import Field
from django.contrib.gis.gdal.geometries import OGRGeometry, OGRGeomType
from django.contrib.gis.gdal.prototypes import ds as capi, geom as geom_api
-from django.utils import six
from django.utils.encoding import force_bytes, force_text
from django.utils.six.moves import range
@@ -35,7 +34,7 @@ class Feature(GDALBase):
is not the field's _value_ -- use the `get` method instead to
retrieve the value (e.g. an integer) instead of a Field instance.
"""
- if isinstance(index, six.string_types):
+ if isinstance(index, str):
i = self.index(index)
else:
if index < 0 or index > self.num_fields:
diff --git a/django/contrib/gis/gdal/geometries.py b/django/contrib/gis/gdal/geometries.py
index 08d0a23767..28ef2907ac 100644
--- a/django/contrib/gis/gdal/geometries.py
+++ b/django/contrib/gis/gdal/geometries.py
@@ -67,7 +67,7 @@ class OGRGeometry(GDALBase):
def __init__(self, geom_input, srs=None):
"Initializes Geometry on either WKT or an OGR pointer as input."
- str_instance = isinstance(geom_input, six.string_types)
+ str_instance = isinstance(geom_input, str)
# If HEX, unpack input to a binary buffer.
if str_instance and hex_regex.match(geom_input):
@@ -276,7 +276,7 @@ class OGRGeometry(GDALBase):
# (decremented) when this geometry's destructor is called.
if isinstance(srs, SpatialReference):
srs_ptr = srs.ptr
- elif isinstance(srs, six.integer_types + six.string_types):
+ elif isinstance(srs, (int, str)):
sr = SpatialReference(srs)
srs_ptr = sr.ptr
elif srs is None:
@@ -295,7 +295,7 @@ class OGRGeometry(GDALBase):
return None
def _set_srid(self, srid):
- if isinstance(srid, six.integer_types) or srid is None:
+ if isinstance(srid, int) or srid is None:
self.srs = srid
else:
raise TypeError('SRID must be set with an integer.')
@@ -403,7 +403,7 @@ class OGRGeometry(GDALBase):
capi.geom_transform(self.ptr, coord_trans.ptr)
elif isinstance(coord_trans, SpatialReference):
capi.geom_transform_to(self.ptr, coord_trans.ptr)
- elif isinstance(coord_trans, six.integer_types + six.string_types):
+ elif isinstance(coord_trans, (int, str)):
sr = SpatialReference(coord_trans)
capi.geom_transform_to(self.ptr, sr.ptr)
else:
@@ -675,7 +675,7 @@ class GeometryCollection(OGRGeometry):
capi.add_geom(self.ptr, g.ptr)
else:
capi.add_geom(self.ptr, geom.ptr)
- elif isinstance(geom, six.string_types):
+ elif isinstance(geom, str):
tmp = OGRGeometry(geom)
capi.add_geom(self.ptr, tmp.ptr)
else:
diff --git a/django/contrib/gis/gdal/geomtype.py b/django/contrib/gis/gdal/geomtype.py
index 0ed7e66343..79c3356f5e 100644
--- a/django/contrib/gis/gdal/geomtype.py
+++ b/django/contrib/gis/gdal/geomtype.py
@@ -1,5 +1,4 @@
from django.contrib.gis.gdal.error import GDALException
-from django.utils import six
class OGRGeomType(object):
@@ -34,7 +33,7 @@ class OGRGeomType(object):
"Figures out the correct OGR Type based upon the input."
if isinstance(type_input, OGRGeomType):
num = type_input.num
- elif isinstance(type_input, six.string_types):
+ elif isinstance(type_input, str):
type_input = type_input.lower()
if type_input == 'geometry':
type_input = 'unknown'
@@ -62,7 +61,7 @@ class OGRGeomType(object):
"""
if isinstance(other, OGRGeomType):
return self.num == other.num
- elif isinstance(other, six.string_types):
+ elif isinstance(other, str):
return self.name.lower() == other.lower()
elif isinstance(other, int):
return self.num == other
diff --git a/django/contrib/gis/gdal/layer.py b/django/contrib/gis/gdal/layer.py
index e7e13f9468..fbbede81b0 100644
--- a/django/contrib/gis/gdal/layer.py
+++ b/django/contrib/gis/gdal/layer.py
@@ -13,7 +13,6 @@ from django.contrib.gis.gdal.prototypes import (
ds as capi, geom as geom_api, srs as srs_api,
)
from django.contrib.gis.gdal.srs import SpatialReference
-from django.utils import six
from django.utils.encoding import force_bytes, force_text
from django.utils.six.moves import range
@@ -42,7 +41,7 @@ class Layer(GDALBase):
def __getitem__(self, index):
"Gets the Feature at the specified index."
- if isinstance(index, six.integer_types):
+ if isinstance(index, int):
# An integer index was given -- we cannot do a check based on the
# number of features because the beginning and ending feature IDs
# are not guaranteed to be 0 and len(layer)-1, respectively.
diff --git a/django/contrib/gis/gdal/prototypes/errcheck.py b/django/contrib/gis/gdal/prototypes/errcheck.py
index a721087654..9b83095131 100644
--- a/django/contrib/gis/gdal/prototypes/errcheck.py
+++ b/django/contrib/gis/gdal/prototypes/errcheck.py
@@ -8,7 +8,6 @@ from django.contrib.gis.gdal.error import (
GDALException, SRSException, check_err,
)
from django.contrib.gis.gdal.libgdal import lgdal
-from django.utils import six
# Helper routines for retrieving pointers and/or values from
@@ -79,7 +78,7 @@ def check_geom(result, func, cargs):
"Checks a function that returns a geometry."
# OGR_G_Clone may return an integer, even though the
# restype is set to c_void_p
- if isinstance(result, six.integer_types):
+ if isinstance(result, int):
result = c_void_p(result)
if not result:
raise GDALException('Invalid geometry pointer returned from "%s".' % func.__name__)
@@ -95,7 +94,7 @@ def check_geom_offset(result, func, cargs, offset=-1):
# ### Spatial Reference error-checking routines ###
def check_srs(result, func, cargs):
- if isinstance(result, six.integer_types):
+ if isinstance(result, int):
result = c_void_p(result)
if not result:
raise SRSException('Invalid spatial reference pointer returned from "%s".' % func.__name__)
@@ -121,7 +120,7 @@ def check_errcode(result, func, cargs, cpl=False):
def check_pointer(result, func, cargs):
"Makes sure the result pointer is valid."
- if isinstance(result, six.integer_types):
+ if isinstance(result, int):
result = c_void_p(result)
if result:
return result
diff --git a/django/contrib/gis/gdal/raster/source.py b/django/contrib/gis/gdal/raster/source.py
index f3a565ddc8..3cafe738a4 100644
--- a/django/contrib/gis/gdal/raster/source.py
+++ b/django/contrib/gis/gdal/raster/source.py
@@ -10,7 +10,6 @@ from django.contrib.gis.gdal.raster.band import BandList
from django.contrib.gis.gdal.raster.const import GDAL_RESAMPLE_ALGORITHMS
from django.contrib.gis.gdal.srs import SpatialReference, SRSException
from django.contrib.gis.geometry.regex import json_regex
-from django.utils import six
from django.utils.encoding import force_bytes, force_text
from django.utils.functional import cached_property
@@ -62,11 +61,11 @@ class GDALRaster(GDALBase):
# Preprocess json inputs. This converts json strings to dictionaries,
# which are parsed below the same way as direct dictionary inputs.
- if isinstance(ds_input, six.string_types) and json_regex.match(ds_input):
+ if isinstance(ds_input, str) and json_regex.match(ds_input):
ds_input = json.loads(ds_input)
# If input is a valid file path, try setting file as source.
- if isinstance(ds_input, six.string_types):
+ if isinstance(ds_input, str):
if not os.path.exists(ds_input):
raise GDALException('Unable to read raster source input "{}"'.format(ds_input))
try:
@@ -215,7 +214,7 @@ class GDALRaster(GDALBase):
"""
if isinstance(value, SpatialReference):
srs = value
- elif isinstance(value, six.integer_types + six.string_types):
+ elif isinstance(value, (int, str)):
srs = SpatialReference(value)
else:
raise ValueError('Could not create a SpatialReference from input.')
diff --git a/django/contrib/gis/gdal/srs.py b/django/contrib/gis/gdal/srs.py
index 635cdc2b5a..9dc9080de7 100644
--- a/django/contrib/gis/gdal/srs.py
+++ b/django/contrib/gis/gdal/srs.py
@@ -31,7 +31,6 @@ from ctypes import byref, c_char_p, c_int
from django.contrib.gis.gdal.base import GDALBase
from django.contrib.gis.gdal.error import SRSException
from django.contrib.gis.gdal.prototypes import srs as capi
-from django.utils import six
from django.utils.encoding import force_bytes, force_text
@@ -55,7 +54,7 @@ class SpatialReference(GDALBase):
self.ptr = capi.new_srs(c_char_p(b''))
self.import_wkt(srs_input)
return
- elif isinstance(srs_input, six.string_types):
+ elif isinstance(srs_input, str):
try:
# If SRID is a string, e.g., '4326', then make acceptable
# as user input.
@@ -63,7 +62,7 @@ class SpatialReference(GDALBase):
srs_input = 'EPSG:%d' % srid
except ValueError:
pass
- elif isinstance(srs_input, six.integer_types):
+ elif isinstance(srs_input, int):
# EPSG integer code was input.
srs_type = 'epsg'
elif isinstance(srs_input, self.ptr_type):
@@ -130,7 +129,7 @@ class SpatialReference(GDALBase):
The attribute value for the given target node (e.g. 'PROJCS'). The index
keyword specifies an index of the child node to return.
"""
- if not isinstance(target, six.string_types) or not isinstance(index, int):
+ if not isinstance(target, str) or not isinstance(index, int):
raise TypeError
return capi.get_attr_value(self.ptr, force_bytes(target), index)
diff --git a/django/contrib/gis/geoip2/base.py b/django/contrib/gis/geoip2/base.py
index 44164f1d71..1d1e2e00dc 100644
--- a/django/contrib/gis/geoip2/base.py
+++ b/django/contrib/gis/geoip2/base.py
@@ -5,7 +5,6 @@ import geoip2.database
from django.conf import settings
from django.core.validators import ipv4_re
-from django.utils import six
from django.utils.ipv6 import is_valid_ipv6_address
from .resources import City, Country
@@ -78,7 +77,7 @@ class GeoIP2(object):
path = GEOIP_SETTINGS['GEOIP_PATH']
if not path:
raise GeoIP2Exception('GeoIP path must be provided via parameter or the GEOIP_PATH setting.')
- if not isinstance(path, six.string_types):
+ if not isinstance(path, str):
raise TypeError('Invalid path type: %s' % type(path).__name__)
if os.path.isdir(path):
@@ -146,7 +145,7 @@ class GeoIP2(object):
def _check_query(self, query, country=False, city=False, city_or_country=False):
"Helper routine for checking the query and database availability."
# Making sure a string was passed in for the query.
- if not isinstance(query, six.string_types):
+ if not isinstance(query, str):
raise TypeError('GeoIP query must be a string, not type %s' % type(query).__name__)
# Extra checks for the existence of country and city databases.
diff --git a/django/contrib/gis/geos/factory.py b/django/contrib/gis/geos/factory.py
index eb06da2c00..42cd10c756 100644
--- a/django/contrib/gis/geos/factory.py
+++ b/django/contrib/gis/geos/factory.py
@@ -8,7 +8,7 @@ def fromfile(file_h):
WKT, or HEX.
"""
# If given a file name, get a real handle.
- if isinstance(file_h, six.string_types):
+ if isinstance(file_h, str):
with open(file_h, 'rb') as file_h:
buf = file_h.read()
else:
diff --git a/django/contrib/gis/geos/geometry.py b/django/contrib/gis/geos/geometry.py
index deadbfaaf2..f7bdf8937f 100644
--- a/django/contrib/gis/geos/geometry.py
+++ b/django/contrib/gis/geos/geometry.py
@@ -49,7 +49,7 @@ class GEOSGeometry(GEOSBase, ListMixin):
"""
if isinstance(geo_input, bytes):
geo_input = force_text(geo_input)
- if isinstance(geo_input, six.string_types):
+ if isinstance(geo_input, str):
wkt_m = wkt_regex.match(geo_input)
if wkt_m:
# Handling WKT input.
@@ -63,7 +63,7 @@ class GEOSGeometry(GEOSBase, ListMixin):
# Handling GeoJSON input.
g = wkb_r().read(gdal.OGRGeometry(geo_input).wkb)
else:
- raise ValueError('String or unicode input unrecognized as WKT EWKT, and HEXEWKB.')
+ raise ValueError('String input unrecognized as WKT EWKT, and HEXEWKB.')
elif isinstance(geo_input, GEOM_PTR):
# When the input is a pointer to a geometry (GEOM_PTR).
g = geo_input
@@ -169,7 +169,7 @@ class GEOSGeometry(GEOSBase, ListMixin):
Equivalence testing, a Geometry may be compared with another Geometry
or an EWKT representation.
"""
- if isinstance(other, six.string_types):
+ if isinstance(other, str):
if other.startswith('SRID=0;'):
return self.ewkt == other[7:] # Test only WKT part of other
return self.ewkt == other
@@ -348,7 +348,7 @@ class GEOSGeometry(GEOSBase, ListMixin):
Returns true if the elements in the DE-9IM intersection matrix for the
two Geometries match the elements in pattern.
"""
- if not isinstance(pattern, six.string_types) or len(pattern) > 9:
+ if not isinstance(pattern, str) or len(pattern) > 9:
raise GEOSException('invalid intersection matrix pattern')
return capi.geos_relatepattern(self.ptr, other.ptr, force_bytes(pattern))
diff --git a/django/contrib/gis/geos/mutable_list.py b/django/contrib/gis/geos/mutable_list.py
index 8a613600c0..8896ebc518 100644
--- a/django/contrib/gis/geos/mutable_list.py
+++ b/django/contrib/gis/geos/mutable_list.py
@@ -10,7 +10,6 @@ Author: Aryeh Leib Taurog.
"""
from functools import total_ordering
-from django.utils import six
from django.utils.six.moves import range
@@ -82,12 +81,12 @@ class ListMixin(object):
def __delitem__(self, index):
"Delete the item(s) at the specified index/slice."
- if not isinstance(index, six.integer_types + (slice,)):
+ if not isinstance(index, (int, slice)):
raise TypeError("%s is not a legal index" % index)
# calculate new length and dimensions
origLen = len(self)
- if isinstance(index, six.integer_types):
+ if isinstance(index, int):
index = self._checkindex(index)
indexRange = [index]
else:
@@ -195,7 +194,7 @@ class ListMixin(object):
def insert(self, index, val):
"Standard list insert method"
- if not isinstance(index, six.integer_types):
+ if not isinstance(index, int):
raise TypeError("%s is not a legal index" % index)
self[index:index] = [val]
diff --git a/django/contrib/gis/geos/point.py b/django/contrib/gis/geos/point.py
index ec95cf1f63..fadf5eb414 100644
--- a/django/contrib/gis/geos/point.py
+++ b/django/contrib/gis/geos/point.py
@@ -4,7 +4,6 @@ from django.contrib.gis import gdal
from django.contrib.gis.geos import prototypes as capi
from django.contrib.gis.geos.error import GEOSException
from django.contrib.gis.geos.geometry import GEOSGeometry
-from django.utils import six
from django.utils.six.moves import range
@@ -27,9 +26,9 @@ class Point(GEOSGeometry):
elif isinstance(x, (tuple, list)):
# Here a tuple or list was passed in under the `x` parameter.
coords = x
- elif isinstance(x, six.integer_types + (float,)) and isinstance(y, six.integer_types + (float,)):
+ elif isinstance(x, (float, int)) and isinstance(y, (float, int)):
# Here X, Y, and (optionally) Z were passed in individually, as parameters.
- if isinstance(z, six.integer_types + (float,)):
+ if isinstance(z, (float, int)):
coords = [x, y, z]
else:
coords = [x, y]
diff --git a/django/contrib/gis/geos/polygon.py b/django/contrib/gis/geos/polygon.py
index 434e27b4d9..0b4de0d3c3 100644
--- a/django/contrib/gis/geos/polygon.py
+++ b/django/contrib/gis/geos/polygon.py
@@ -4,7 +4,6 @@ from django.contrib.gis.geos import prototypes as capi
from django.contrib.gis.geos.geometry import GEOSGeometry
from django.contrib.gis.geos.libgeos import GEOM_PTR, get_pointer_arr
from django.contrib.gis.geos.linestring import LinearRing
-from django.utils import six
from django.utils.six.moves import range
@@ -63,7 +62,7 @@ class Polygon(GEOSGeometry):
"Constructs a Polygon from a bounding box (4-tuple)."
x0, y0, x1, y1 = bbox
for z in bbox:
- if not isinstance(z, six.integer_types + (float,)):
+ if not isinstance(z, (float, int)):
return GEOSGeometry('POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))' %
(x0, y0, x0, y1, x1, y1, x1, y0, x0, y0))
return Polygon(((x0, y0), (x0, y1), (x1, y1), (x1, y0), (x0, y0)))
diff --git a/django/contrib/gis/geos/prototypes/io.py b/django/contrib/gis/geos/prototypes/io.py
index c932a1a15f..1cc0ccb8f3 100644
--- a/django/contrib/gis/geos/prototypes/io.py
+++ b/django/contrib/gis/geos/prototypes/io.py
@@ -135,7 +135,7 @@ class _WKTReader(IOBase):
destructor = wkt_reader_destroy
def read(self, wkt):
- if not isinstance(wkt, (bytes, six.string_types)):
+ if not isinstance(wkt, (bytes, str)):
raise TypeError
return wkt_reader_read(self.ptr, force_bytes(wkt))
@@ -150,7 +150,7 @@ class _WKBReader(IOBase):
if isinstance(wkb, six.memoryview):
wkb_s = bytes(wkb)
return wkb_reader_read(self.ptr, wkb_s, len(wkb_s))
- elif isinstance(wkb, (bytes, six.string_types)):
+ elif isinstance(wkb, (bytes, str)):
return wkb_reader_read_hex(self.ptr, wkb, len(wkb))
else:
raise TypeError
diff --git a/django/contrib/gis/measure.py b/django/contrib/gis/measure.py
index 71bc5ff83b..8691d009a6 100644
--- a/django/contrib/gis/measure.py
+++ b/django/contrib/gis/measure.py
@@ -42,7 +42,7 @@ from django.utils import six
__all__ = ['A', 'Area', 'D', 'Distance']
-NUMERIC_TYPES = six.integer_types + (float, Decimal)
+NUMERIC_TYPES = (int, float, Decimal)
AREA_PREFIX = "sq_"
@@ -60,7 +60,7 @@ class MeasureBase(object):
def __init__(self, default_unit=None, **kwargs):
value, self._default_unit = self.default_units(kwargs)
setattr(self, self.STANDARD_UNIT, value)
- if default_unit and isinstance(default_unit, six.string_types):
+ if default_unit and isinstance(default_unit, str):
self._default_unit = default_unit
def _get_standard(self):
diff --git a/django/contrib/gis/utils/layermapping.py b/django/contrib/gis/utils/layermapping.py
index 22d7dd2579..a10e9bbeb8 100644
--- a/django/contrib/gis/utils/layermapping.py
+++ b/django/contrib/gis/utils/layermapping.py
@@ -89,7 +89,7 @@ class LayerMapping(object):
argument usage.
"""
# Getting the DataSource and the associated Layer.
- if isinstance(data, six.string_types):
+ if isinstance(data, str):
self.ds = DataSource(data, encoding=encoding)
else:
self.ds = data
@@ -266,7 +266,7 @@ class LayerMapping(object):
sr = source_srs
elif isinstance(source_srs, self.spatial_backend.spatial_ref_sys()):
sr = source_srs.srs
- elif isinstance(source_srs, (int, six.string_types)):
+ elif isinstance(source_srs, (int, str)):
sr = SpatialReference(source_srs)
else:
# Otherwise just pulling the SpatialReference from the layer
@@ -284,7 +284,7 @@ class LayerMapping(object):
for attr in unique:
if attr not in self.mapping:
raise ValueError
- elif isinstance(unique, six.string_types):
+ elif isinstance(unique, str):
# Only a single field passed in.
if unique not in self.mapping:
raise ValueError
@@ -331,7 +331,7 @@ class LayerMapping(object):
will construct and return the uniqueness keyword arguments -- a subset
of the feature kwargs.
"""
- if isinstance(self.unique, six.string_types):
+ if isinstance(self.unique, str):
return {self.unique: kwargs[self.unique]}
else:
return {fld: kwargs[fld] for fld in self.unique}
diff --git a/django/contrib/gis/utils/ogrinspect.py b/django/contrib/gis/utils/ogrinspect.py
index 71e4c64878..c10364491d 100644
--- a/django/contrib/gis/utils/ogrinspect.py
+++ b/django/contrib/gis/utils/ogrinspect.py
@@ -8,7 +8,6 @@ from django.contrib.gis.gdal.field import (
OFTDate, OFTDateTime, OFTInteger, OFTInteger64, OFTReal, OFTString,
OFTTime,
)
-from django.utils import six
from django.utils.six.moves import zip
@@ -26,7 +25,7 @@ def mapping(data_source, geom_name='geom', layer_key=0, multi_geom=False):
`multi_geom` => Boolean (default: False) - specify as multigeometry.
"""
- if isinstance(data_source, six.string_types):
+ if isinstance(data_source, str):
# Instantiating the DataSource from the string.
data_source = DataSource(data_source)
elif isinstance(data_source, DataSource):
@@ -129,7 +128,7 @@ def _ogrinspect(data_source, model_name, geom_name='geom', layer_key=0, srid=Non
to the given data source. See the `ogrinspect` docstring for more details.
"""
# Getting the DataSource
- if isinstance(data_source, six.string_types):
+ if isinstance(data_source, str):
data_source = DataSource(data_source)
elif isinstance(data_source, DataSource):
pass
diff --git a/django/contrib/messages/storage/session.py b/django/contrib/messages/storage/session.py
index 624de42b8c..2eb8024bfa 100644
--- a/django/contrib/messages/storage/session.py
+++ b/django/contrib/messages/storage/session.py
@@ -5,7 +5,6 @@ from django.contrib.messages.storage.base import BaseStorage
from django.contrib.messages.storage.cookie import (
MessageDecoder, MessageEncoder,
)
-from django.utils import six
class SessionStorage(BaseStorage):
@@ -44,6 +43,6 @@ class SessionStorage(BaseStorage):
return encoder.encode(messages)
def deserialize_messages(self, data):
- if data and isinstance(data, six.string_types):
+ if data and isinstance(data, str):
return json.loads(data, cls=MessageDecoder)
return data
diff --git a/django/contrib/postgres/fields/array.py b/django/contrib/postgres/fields/array.py
index b70ae37a3a..dc5b9b8d6b 100644
--- a/django/contrib/postgres/fields/array.py
+++ b/django/contrib/postgres/fields/array.py
@@ -6,7 +6,6 @@ from django.contrib.postgres.validators import ArrayMaxLengthValidator
from django.core import checks, exceptions
from django.db.models import Field, IntegerField, Transform
from django.db.models.lookups import Exact, In
-from django.utils import six
from django.utils.translation import ugettext_lazy as _
from ..utils import prefix_validation_error
@@ -98,7 +97,7 @@ class ArrayField(Field):
return name, path, args, kwargs
def to_python(self, value):
- if isinstance(value, six.string_types):
+ if isinstance(value, str):
# Assume we're deserializing
vals = json.loads(value)
value = [self.base_field.to_python(val) for val in vals]
diff --git a/django/contrib/postgres/fields/hstore.py b/django/contrib/postgres/fields/hstore.py
index 605deaf62c..fcd212bc4a 100644
--- a/django/contrib/postgres/fields/hstore.py
+++ b/django/contrib/postgres/fields/hstore.py
@@ -4,7 +4,6 @@ from django.contrib.postgres import forms, lookups
from django.contrib.postgres.fields.array import ArrayField
from django.core import exceptions
from django.db.models import Field, TextField, Transform
-from django.utils import six
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
@@ -30,7 +29,7 @@ class HStoreField(Field):
def validate(self, value, model_instance):
super(HStoreField, self).validate(value, model_instance)
for key, val in value.items():
- if not isinstance(val, six.string_types) and val is not None:
+ if not isinstance(val, str) and val is not None:
raise exceptions.ValidationError(
self.error_messages['not_a_string'],
code='not_a_string',
@@ -38,7 +37,7 @@ class HStoreField(Field):
)
def to_python(self, value):
- if isinstance(value, six.string_types):
+ if isinstance(value, str):
value = json.loads(value)
return value
diff --git a/django/contrib/postgres/fields/ranges.py b/django/contrib/postgres/fields/ranges.py
index ab7708d288..840417a58f 100644
--- a/django/contrib/postgres/fields/ranges.py
+++ b/django/contrib/postgres/fields/ranges.py
@@ -4,7 +4,6 @@ from psycopg2.extras import DateRange, DateTimeTZRange, NumericRange, Range
from django.contrib.postgres import forms, lookups
from django.db import models
-from django.utils import six
from .utils import AttributeSetter
@@ -45,7 +44,7 @@ class RangeField(models.Field):
return value
def to_python(self, value):
- if isinstance(value, six.string_types):
+ if isinstance(value, str):
# Assume we're deserializing
vals = json.loads(value)
for end in ('lower', 'upper'):
diff --git a/django/contrib/postgres/forms/array.py b/django/contrib/postgres/forms/array.py
index 9830c8de48..9a9e871a43 100644
--- a/django/contrib/postgres/forms/array.py
+++ b/django/contrib/postgres/forms/array.py
@@ -6,7 +6,6 @@ from django.contrib.postgres.validators import (
ArrayMaxLengthValidator, ArrayMinLengthValidator,
)
from django.core.exceptions import ValidationError
-from django.utils import six
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
@@ -31,7 +30,7 @@ class SimpleArrayField(forms.CharField):
def prepare_value(self, value):
if isinstance(value, list):
- return self.delimiter.join(six.text_type(self.base_field.prepare_value(v)) for v in value)
+ return self.delimiter.join(str(self.base_field.prepare_value(v)) for v in value)
return value
def to_python(self, value):
diff --git a/django/contrib/postgres/forms/hstore.py b/django/contrib/postgres/forms/hstore.py
index 76d362999d..25dceb9fb0 100644
--- a/django/contrib/postgres/forms/hstore.py
+++ b/django/contrib/postgres/forms/hstore.py
@@ -2,7 +2,6 @@ import json
from django import forms
from django.core.exceptions import ValidationError
-from django.utils import six
from django.utils.translation import ugettext_lazy as _
__all__ = ['HStoreField']
@@ -44,7 +43,7 @@ class HStoreField(forms.CharField):
# Cast everything to strings for ease.
for key, val in value.items():
if val is not None:
- val = six.text_type(val)
+ val = str(val)
value[key] = val
return value
diff --git a/django/contrib/postgres/forms/jsonb.py b/django/contrib/postgres/forms/jsonb.py
index 719de3ae66..28429c7172 100644
--- a/django/contrib/postgres/forms/jsonb.py
+++ b/django/contrib/postgres/forms/jsonb.py
@@ -1,17 +1,16 @@
import json
from django import forms
-from django.utils import six
from django.utils.translation import ugettext_lazy as _
__all__ = ['JSONField']
-class InvalidJSONInput(six.text_type):
+class InvalidJSONInput(str):
pass
-class JSONString(six.text_type):
+class JSONString(str):
pass
@@ -36,7 +35,7 @@ class JSONField(forms.CharField):
code='invalid',
params={'value': value},
)
- if isinstance(converted, six.text_type):
+ if isinstance(converted, str):
return JSONString(converted)
else:
return converted
diff --git a/django/core/cache/backends/memcached.py b/django/core/cache/backends/memcached.py
index 4cf25fb4c6..82589a82b0 100644
--- a/django/core/cache/backends/memcached.py
+++ b/django/core/cache/backends/memcached.py
@@ -6,7 +6,6 @@ import time
import warnings
from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache
-from django.utils import six
from django.utils.deprecation import RemovedInDjango21Warning
from django.utils.encoding import force_str
from django.utils.functional import cached_property
@@ -15,7 +14,7 @@ from django.utils.functional import cached_property
class BaseMemcachedCache(BaseCache):
def __init__(self, server, params, library, value_not_found_exception):
super(BaseMemcachedCache, self).__init__(params)
- if isinstance(server, six.string_types):
+ if isinstance(server, str):
self._servers = re.split('[;,]', server)
else:
self._servers = server
diff --git a/django/core/checks/templates.py b/django/core/checks/templates.py
index bf526c871e..6f60d33bd0 100644
--- a/django/core/checks/templates.py
+++ b/django/core/checks/templates.py
@@ -1,7 +1,6 @@
import copy
from django.conf import settings
-from django.utils import six
from . import Error, Tags, register
@@ -32,7 +31,7 @@ def check_string_if_invalid_is_string(app_configs, **kwargs):
errors = []
for conf in settings.TEMPLATES:
string_if_invalid = conf.get('OPTIONS', {}).get('string_if_invalid', '')
- if not isinstance(string_if_invalid, six.string_types):
+ if not isinstance(string_if_invalid, str):
error = copy.copy(E002)
error.msg = error.msg.format(string_if_invalid, type(string_if_invalid).__name__)
errors.append(error)
diff --git a/django/core/checks/urls.py b/django/core/checks/urls.py
index d721bc901f..c39010fb7d 100644
--- a/django/core/checks/urls.py
+++ b/django/core/checks/urls.py
@@ -1,7 +1,6 @@
from collections import Counter
from django.conf import settings
-from django.utils import six
from . import Error, Tags, Warning, register
@@ -72,7 +71,7 @@ def get_warning_for_invalid_pattern(pattern):
describe_pattern() cannot be used here, because we cannot rely on the
urlpattern having regex or name attributes.
"""
- if isinstance(pattern, six.string_types):
+ if isinstance(pattern, str):
hint = (
"Try removing the string '{}'. The list of urlpatterns should not "
"have a prefix string as the first element.".format(pattern)
diff --git a/django/core/files/base.py b/django/core/files/base.py
index dd07bc959a..df29c94eee 100644
--- a/django/core/files/base.py
+++ b/django/core/files/base.py
@@ -2,7 +2,6 @@ import os
from io import BytesIO, StringIO, UnsupportedOperation
from django.core.files.utils import FileProxyMixin
-from django.utils import six
from django.utils.encoding import force_str, force_text
@@ -140,7 +139,7 @@ class ContentFile(File):
A File-like object that takes just raw content, rather than an actual file.
"""
def __init__(self, content, name=None):
- stream_class = StringIO if isinstance(content, six.text_type) else BytesIO
+ stream_class = StringIO if isinstance(content, str) else BytesIO
super(ContentFile, self).__init__(stream_class(content), name=name)
self.size = len(content)
@@ -164,18 +163,18 @@ def endswith_cr(line):
"""
Return True if line (a text or byte string) ends with '\r'.
"""
- return line.endswith('\r' if isinstance(line, six.text_type) else b'\r')
+ return line.endswith('\r' if isinstance(line, str) else b'\r')
def endswith_lf(line):
"""
Return True if line (a text or byte string) ends with '\n'.
"""
- return line.endswith('\n' if isinstance(line, six.text_type) else b'\n')
+ return line.endswith('\n' if isinstance(line, str) else b'\n')
def equals_lf(line):
"""
Return True if line (a text or byte string) equals '\n'.
"""
- return line == ('\n' if isinstance(line, six.text_type) else b'\n')
+ return line == ('\n' if isinstance(line, str) else b'\n')
diff --git a/django/core/handlers/base.py b/django/core/handlers/base.py
index b37716b62c..c45023d129 100644
--- a/django/core/handlers/base.py
+++ b/django/core/handlers/base.py
@@ -5,7 +5,6 @@ from django.conf import settings
from django.core.exceptions import ImproperlyConfigured, MiddlewareNotUsed
from django.db import connections, transaction
from django.urls import get_resolver, set_urlconf
-from django.utils import six
from django.utils.module_loading import import_string
from .exception import convert_exception_to_response, get_exception_response
@@ -42,7 +41,7 @@ class BaseHandler(object):
mw_instance = middleware(handler)
except MiddlewareNotUsed as exc:
if settings.DEBUG:
- if six.text_type(exc):
+ if str(exc):
logger.debug('MiddlewareNotUsed(%r): %s', middleware_path, exc)
else:
logger.debug('MiddlewareNotUsed: %r', middleware_path)
diff --git a/django/core/mail/backends/filebased.py b/django/core/mail/backends/filebased.py
index cfe033fb48..40dc9ff7cc 100644
--- a/django/core/mail/backends/filebased.py
+++ b/django/core/mail/backends/filebased.py
@@ -7,7 +7,6 @@ from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.mail.backends.console import \
EmailBackend as ConsoleEmailBackend
-from django.utils import six
class EmailBackend(ConsoleEmailBackend):
@@ -18,7 +17,7 @@ class EmailBackend(ConsoleEmailBackend):
else:
self.file_path = getattr(settings, 'EMAIL_FILE_PATH', None)
# Make sure self.file_path is a string.
- if not isinstance(self.file_path, six.string_types):
+ if not isinstance(self.file_path, str):
raise ImproperlyConfigured('Path for saving emails is invalid: %r' % self.file_path)
self.file_path = os.path.abspath(self.file_path)
# Make sure that self.file_path is an directory if it exists.
diff --git a/django/core/mail/message.py b/django/core/mail/message.py
index c4df44fa9d..a8ea1f0991 100644
--- a/django/core/mail/message.py
+++ b/django/core/mail/message.py
@@ -244,25 +244,25 @@ class EmailMessage(object):
necessary encoding conversions.
"""
if to:
- if isinstance(to, six.string_types):
+ if isinstance(to, str):
raise TypeError('"to" argument must be a list or tuple')
self.to = list(to)
else:
self.to = []
if cc:
- if isinstance(cc, six.string_types):
+ if isinstance(cc, str):
raise TypeError('"cc" argument must be a list or tuple')
self.cc = list(cc)
else:
self.cc = []
if bcc:
- if isinstance(bcc, six.string_types):
+ if isinstance(bcc, str):
raise TypeError('"bcc" argument must be a list or tuple')
self.bcc = list(bcc)
else:
self.bcc = []
if reply_to:
- if isinstance(reply_to, six.string_types):
+ if isinstance(reply_to, str):
raise TypeError('"reply_to" argument must be a list or tuple')
self.reply_to = list(reply_to)
else:
@@ -352,7 +352,7 @@ class EmailMessage(object):
basetype, subtype = mimetype.split('/', 1)
if basetype == 'text':
- if isinstance(content, six.binary_type):
+ if isinstance(content, bytes):
try:
content = content.decode('utf-8')
except UnicodeDecodeError:
diff --git a/django/core/management/utils.py b/django/core/management/utils.py
index 0fb8b0d25f..07a14bd731 100644
--- a/django/core/management/utils.py
+++ b/django/core/management/utils.py
@@ -55,7 +55,7 @@ def handle_extensions(extensions):
def find_command(cmd, path=None, pathext=None):
if path is None:
path = os.environ.get('PATH', '').split(os.pathsep)
- if isinstance(path, six.string_types):
+ if isinstance(path, str):
path = [path]
# check if there are funny path extensions for executables, e.g. Windows
if pathext is None:
diff --git a/django/core/paginator.py b/django/core/paginator.py
index c77a62a1fe..ae085bf837 100644
--- a/django/core/paginator.py
+++ b/django/core/paginator.py
@@ -130,7 +130,7 @@ class Page(collections.Sequence):
return len(self.object_list)
def __getitem__(self, index):
- if not isinstance(index, (slice,) + six.integer_types):
+ if not isinstance(index, (int, slice)):
raise TypeError
# The object_list is converted to a list so that if it was a QuerySet
# it won't be a database hit per __getitem__.
diff --git a/django/core/serializers/base.py b/django/core/serializers/base.py
index 46fb25ea78..2a10fbe19e 100644
--- a/django/core/serializers/base.py
+++ b/django/core/serializers/base.py
@@ -168,7 +168,7 @@ class Deserializer(six.Iterator):
Init this serializer given a stream or a string
"""
self.options = options
- if isinstance(stream_or_string, six.string_types):
+ if isinstance(stream_or_string, str):
self.stream = six.StringIO(stream_or_string)
else:
self.stream = stream_or_string
diff --git a/django/core/serializers/json.py b/django/core/serializers/json.py
index b335605785..b87d807571 100644
--- a/django/core/serializers/json.py
+++ b/django/core/serializers/json.py
@@ -69,7 +69,7 @@ def Deserializer(stream_or_string, **options):
"""
Deserialize a stream or string of JSON data.
"""
- if not isinstance(stream_or_string, (bytes, six.string_types)):
+ if not isinstance(stream_or_string, (bytes, str)):
stream_or_string = stream_or_string.read()
if isinstance(stream_or_string, bytes):
stream_or_string = stream_or_string.decode('utf-8')
@@ -108,11 +108,7 @@ class DjangoJSONEncoder(json.JSONEncoder):
return r
elif isinstance(o, datetime.timedelta):
return duration_iso_string(o)
- elif isinstance(o, decimal.Decimal):
+ elif isinstance(o, (decimal.Decimal, uuid.UUID, Promise)):
return str(o)
- elif isinstance(o, uuid.UUID):
- return str(o)
- elif isinstance(o, Promise):
- return six.text_type(o)
else:
return super(DjangoJSONEncoder, self).default(o)
diff --git a/django/core/serializers/python.py b/django/core/serializers/python.py
index a0cea14297..9db5c2e6a6 100644
--- a/django/core/serializers/python.py
+++ b/django/core/serializers/python.py
@@ -131,7 +131,7 @@ def Deserializer(object_list, **options):
model = field.remote_field.model
if hasattr(model._default_manager, 'get_by_natural_key'):
def m2m_convert(value):
- if hasattr(value, '__iter__') and not isinstance(value, six.text_type):
+ if hasattr(value, '__iter__') and not isinstance(value, str):
return model._default_manager.db_manager(db).get_by_natural_key(*value).pk
else:
return force_text(model._meta.pk.to_python(value), strings_only=True)
@@ -154,7 +154,7 @@ def Deserializer(object_list, **options):
default_manager = model._default_manager
field_name = field.remote_field.field_name
if hasattr(default_manager, 'get_by_natural_key'):
- if hasattr(field_value, '__iter__') and not isinstance(field_value, six.text_type):
+ if hasattr(field_value, '__iter__') and not isinstance(field_value, str):
obj = default_manager.db_manager(db).get_by_natural_key(*field_value)
value = getattr(obj, field.remote_field.field_name)
# If this is a natural foreign key to an object that
diff --git a/django/core/serializers/pyyaml.py b/django/core/serializers/pyyaml.py
index 5dc847d4f5..16583782b9 100644
--- a/django/core/serializers/pyyaml.py
+++ b/django/core/serializers/pyyaml.py
@@ -71,7 +71,7 @@ def Deserializer(stream_or_string, **options):
"""
if isinstance(stream_or_string, bytes):
stream_or_string = stream_or_string.decode('utf-8')
- if isinstance(stream_or_string, six.string_types):
+ if isinstance(stream_or_string, str):
stream = StringIO(stream_or_string)
else:
stream = stream_or_string
diff --git a/django/core/validators.py b/django/core/validators.py
index 221f3e0934..e2fcd6f72e 100644
--- a/django/core/validators.py
+++ b/django/core/validators.py
@@ -2,7 +2,6 @@ import os
import re
from django.core.exceptions import ValidationError
-from django.utils import six
from django.utils.deconstruct import deconstructible
from django.utils.encoding import force_text
from django.utils.functional import SimpleLazyObject
@@ -18,7 +17,7 @@ def _lazy_re_compile(regex, flags=0):
"""Lazily compile a regex with flags."""
def _compile():
# Compile the regex if it was not passed pre-compiled.
- if isinstance(regex, six.string_types):
+ if isinstance(regex, str):
return re.compile(regex, flags)
else:
assert not flags, "flags must be empty if regex is passed pre-compiled"
@@ -45,7 +44,7 @@ class RegexValidator(object):
self.inverse_match = inverse_match
if flags is not None:
self.flags = flags
- if self.flags and not isinstance(self.regex, six.string_types):
+ if self.flags and not isinstance(self.regex, str):
raise TypeError("If the flags are set, regex must be a regular expression string.")
self.regex = _lazy_re_compile(self.regex, self.flags)
diff --git a/django/db/backends/base/operations.py b/django/db/backends/base/operations.py
index 0539d71539..6f1248efc1 100644
--- a/django/db/backends/base/operations.py
+++ b/django/db/backends/base/operations.py
@@ -5,7 +5,7 @@ from importlib import import_module
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.db.backends import utils
-from django.utils import six, timezone
+from django.utils import timezone
from django.utils.dateparse import parse_duration
from django.utils.encoding import force_text
@@ -201,17 +201,17 @@ class BaseDatabaseOperations(object):
exists for database backends to provide a better implementation
according to their own quoting schemes.
"""
- # Convert params to contain Unicode values.
- def to_unicode(s):
+ # Convert params to contain string values.
+ def to_string(s):
return force_text(s, strings_only=True, errors='replace')
if isinstance(params, (list, tuple)):
- u_params = tuple(to_unicode(val) for val in params)
+ u_params = tuple(to_string(val) for val in params)
elif params is None:
u_params = ()
else:
- u_params = {to_unicode(k): to_unicode(v) for k, v in params.items()}
+ u_params = {to_string(k): to_string(v) for k, v in params.items()}
- return six.text_type("QUERY = %r - PARAMS = %r") % (sql, u_params)
+ return "QUERY = %r - PARAMS = %r" % (sql, u_params)
def last_insert_id(self, cursor, table_name, pk_name):
"""
@@ -462,7 +462,7 @@ class BaseDatabaseOperations(object):
"""
if value is None:
return None
- return six.text_type(value)
+ return str(value)
def adapt_datetimefield_value(self, value):
"""
@@ -471,7 +471,7 @@ class BaseDatabaseOperations(object):
"""
if value is None:
return None
- return six.text_type(value)
+ return str(value)
def adapt_timefield_value(self, value):
"""
@@ -482,7 +482,7 @@ class BaseDatabaseOperations(object):
return None
if timezone.is_aware(value):
raise ValueError("Django does not support timezone-aware times.")
- return six.text_type(value)
+ return str(value)
def adapt_decimalfield_value(self, value, max_digits=None, decimal_places=None):
"""
diff --git a/django/db/backends/base/schema.py b/django/db/backends/base/schema.py
index b00853b74d..6cb6826a7f 100644
--- a/django/db/backends/base/schema.py
+++ b/django/db/backends/base/schema.py
@@ -4,7 +4,7 @@ from datetime import datetime
from django.db.backends.utils import strip_quotes
from django.db.transaction import TransactionManagementError, atomic
-from django.utils import six, timezone
+from django.utils import timezone
from django.utils.encoding import force_bytes
logger = logging.getLogger('django.db.backends.schema')
@@ -206,9 +206,9 @@ class BaseDatabaseSchemaEditor(object):
default = field.get_default()
elif not field.null and field.blank and field.empty_strings_allowed:
if field.get_internal_type() == "BinaryField":
- default = six.binary_type()
+ default = bytes()
else:
- default = six.text_type()
+ default = str()
elif getattr(field, 'auto_now', False) or getattr(field, 'auto_now_add', False):
default = datetime.now()
internal_type = field.get_internal_type()
diff --git a/django/db/backends/mysql/base.py b/django/db/backends/mysql/base.py
index 495ca33221..f674687ff1 100644
--- a/django/db/backends/mysql/base.py
+++ b/django/db/backends/mysql/base.py
@@ -256,7 +256,7 @@ class DatabaseWrapper(BaseDatabaseWrapper):
def get_new_connection(self, conn_params):
conn = Database.connect(**conn_params)
- conn.encoders[SafeText] = conn.encoders[six.text_type]
+ conn.encoders[SafeText] = conn.encoders[str]
conn.encoders[SafeBytes] = conn.encoders[bytes]
return conn
diff --git a/django/db/backends/mysql/operations.py b/django/db/backends/mysql/operations.py
index 4edc9272a9..acb86c62ac 100644
--- a/django/db/backends/mysql/operations.py
+++ b/django/db/backends/mysql/operations.py
@@ -2,7 +2,7 @@ import uuid
from django.conf import settings
from django.db.backends.base.operations import BaseDatabaseOperations
-from django.utils import six, timezone
+from django.utils import timezone
from django.utils.encoding import force_text
@@ -168,7 +168,7 @@ class DatabaseOperations(BaseDatabaseOperations):
if not self.connection.features.supports_microsecond_precision:
value = value.replace(microsecond=0)
- return six.text_type(value)
+ return str(value)
def adapt_timefield_value(self, value):
if value is None:
@@ -182,7 +182,7 @@ class DatabaseOperations(BaseDatabaseOperations):
if timezone.is_aware(value):
raise ValueError("MySQL backend does not support timezone-aware times.")
- return six.text_type(value)
+ return str(value)
def max_name_length(self):
return 64
diff --git a/django/db/backends/oracle/base.py b/django/db/backends/oracle/base.py
index 317599253d..c365c673c5 100644
--- a/django/db/backends/oracle/base.py
+++ b/django/db/backends/oracle/base.py
@@ -338,7 +338,7 @@ class OracleParam(object):
# To transmit to the database, we need Unicode if supported
# To get size right, we must consider bytes.
self.force_bytes = force_text(param, cursor.charset, strings_only)
- if isinstance(self.force_bytes, six.string_types):
+ if isinstance(self.force_bytes, str):
# We could optimize by only converting up to 4000 bytes here
string_size = len(force_bytes(param, cursor.charset, strings_only))
if hasattr(param, 'input_size'):
@@ -566,18 +566,5 @@ def _rowfactory(row, cursor):
value = decimal.Decimal(value)
else:
value = int(value)
- elif desc[1] in (Database.STRING, Database.FIXED_CHAR,
- Database.LONG_STRING):
- value = to_unicode(value)
casted.append(value)
return tuple(casted)
-
-
-def to_unicode(s):
- """
- Convert strings to Unicode objects (and return all other data types
- unchanged).
- """
- if isinstance(s, six.string_types):
- return force_text(s)
- return s
diff --git a/django/db/backends/oracle/operations.py b/django/db/backends/oracle/operations.py
index 9878fbd9bb..8d94319987 100644
--- a/django/db/backends/oracle/operations.py
+++ b/django/db/backends/oracle/operations.py
@@ -5,7 +5,7 @@ import uuid
from django.conf import settings
from django.db.backends.base.operations import BaseDatabaseOperations
from django.db.backends.utils import strip_quotes, truncate_name
-from django.utils import six, timezone
+from django.utils import timezone
from django.utils.encoding import force_bytes, force_text
from .base import Database
@@ -490,7 +490,7 @@ WHEN (new.%(col_name)s IS NULL)
if hasattr(value, 'resolve_expression'):
return value
- if isinstance(value, six.string_types):
+ if isinstance(value, str):
return datetime.datetime.strptime(value, '%H:%M:%S')
# Oracle doesn't support tz-aware times
diff --git a/django/db/backends/oracle/schema.py b/django/db/backends/oracle/schema.py
index 15d361bf7a..44a1f3cd8d 100644
--- a/django/db/backends/oracle/schema.py
+++ b/django/db/backends/oracle/schema.py
@@ -5,7 +5,6 @@ import re
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.utils import DatabaseError
-from django.utils import six
from django.utils.text import force_text
@@ -23,9 +22,9 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
def quote_value(self, value):
if isinstance(value, (datetime.date, datetime.time, datetime.datetime)):
return "'%s'" % value
- elif isinstance(value, six.string_types):
- return "'%s'" % six.text_type(value).replace("\'", "\'\'")
- elif isinstance(value, six.buffer_types):
+ elif isinstance(value, str):
+ return "'%s'" % value.replace("\'", "\'\'")
+ elif isinstance(value, (bytes, bytearray, memoryview)):
return "'%s'" % force_text(binascii.hexlify(value))
elif isinstance(value, bool):
return "1" if value else "0"
diff --git a/django/db/backends/sqlite3/base.py b/django/db/backends/sqlite3/base.py
index de3aa40000..44f81c8ba1 100644
--- a/django/db/backends/sqlite3/base.py
+++ b/django/db/backends/sqlite3/base.py
@@ -14,7 +14,7 @@ from django.core.exceptions import ImproperlyConfigured
from django.db import utils
from django.db.backends import utils as backend_utils
from django.db.backends.base.base import BaseDatabaseWrapper
-from django.utils import six, timezone
+from django.utils import timezone
from django.utils.dateparse import (
parse_date, parse_datetime, parse_duration, parse_time,
)
@@ -425,12 +425,12 @@ def _sqlite_format_dtdelta(conn, lhs, rhs):
- A string representing a datetime
"""
try:
- if isinstance(lhs, six.integer_types):
+ if isinstance(lhs, int):
lhs = str(decimal.Decimal(lhs) / decimal.Decimal(1000000))
real_lhs = parse_duration(lhs)
if real_lhs is None:
real_lhs = backend_utils.typecast_timestamp(lhs)
- if isinstance(rhs, six.integer_types):
+ if isinstance(rhs, int):
rhs = str(decimal.Decimal(rhs) / decimal.Decimal(1000000))
real_rhs = parse_duration(rhs)
if real_rhs is None:
diff --git a/django/db/backends/sqlite3/operations.py b/django/db/backends/sqlite3/operations.py
index 529db94451..64486be737 100644
--- a/django/db/backends/sqlite3/operations.py
+++ b/django/db/backends/sqlite3/operations.py
@@ -7,7 +7,7 @@ from django.db import utils
from django.db.backends import utils as backend_utils
from django.db.backends.base.operations import BaseDatabaseOperations
from django.db.models import aggregates, fields
-from django.utils import six, timezone
+from django.utils import timezone
from django.utils.dateparse import parse_date, parse_datetime, parse_time
from django.utils.duration import duration_string
@@ -178,7 +178,7 @@ class DatabaseOperations(BaseDatabaseOperations):
else:
raise ValueError("SQLite backend does not support timezone-aware datetimes when USE_TZ is False.")
- return six.text_type(value)
+ return str(value)
def adapt_timefield_value(self, value):
if value is None:
@@ -192,7 +192,7 @@ class DatabaseOperations(BaseDatabaseOperations):
if timezone.is_aware(value):
raise ValueError("SQLite backend does not support timezone-aware times.")
- return six.text_type(value)
+ return str(value)
def get_db_converters(self, expression):
converters = super(DatabaseOperations, self).get_db_converters(expression)
diff --git a/django/db/backends/sqlite3/schema.py b/django/db/backends/sqlite3/schema.py
index 36adb22584..d74f59d21c 100644
--- a/django/db/backends/sqlite3/schema.py
+++ b/django/db/backends/sqlite3/schema.py
@@ -5,7 +5,6 @@ from decimal import Decimal
from django.apps.registry import Apps
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
-from django.utils import six
class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
@@ -46,15 +45,13 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
# Manual emulation of SQLite parameter quoting
if isinstance(value, type(True)):
return str(int(value))
- elif isinstance(value, (Decimal, float)):
+ elif isinstance(value, (Decimal, float, int)):
return str(value)
- elif isinstance(value, six.integer_types):
- return str(value)
- elif isinstance(value, six.string_types):
- return "'%s'" % six.text_type(value).replace("\'", "\'\'")
+ elif isinstance(value, str):
+ return "'%s'" % value.replace("\'", "\'\'")
elif value is None:
return "NULL"
- elif isinstance(value, (bytes, bytearray, six.memoryview)):
+ elif isinstance(value, (bytes, bytearray, memoryview)):
# Bytes are only allowed for BLOB fields, encoded as string
# literals containing hexadecimal data and preceded by a single "X"
# character:
diff --git a/django/db/migrations/autodetector.py b/django/db/migrations/autodetector.py
index 84ecf90b9e..d2b6f6d497 100644
--- a/django/db/migrations/autodetector.py
+++ b/django/db/migrations/autodetector.py
@@ -12,7 +12,6 @@ from django.db.migrations.questioner import MigrationQuestioner
from django.db.migrations.utils import (
COMPILED_REGEX_TYPE, RegexObject, get_migration_name_timestamp,
)
-from django.utils import six
from .topological_sort import stable_topological_sort
@@ -538,7 +537,7 @@ class MigrationAutodetector(object):
]
# Depend on all bases
for base in model_state.bases:
- if isinstance(base, six.string_types) and "." in base:
+ if isinstance(base, str) and "." in base:
base_app_label, base_name = base.split(".", 1)
dependencies.append((base_app_label, base_name, None, True))
# Depend on the other end of the primary key if it's a relation
@@ -659,7 +658,7 @@ class MigrationAutodetector(object):
]
# Depend on all bases
for base in model_state.bases:
- if isinstance(base, six.string_types) and "." in base:
+ if isinstance(base, str) and "." in base:
base_app_label, base_name = base.split(".", 1)
dependencies.append((base_app_label, base_name, None, True))
# Generate creation operation
diff --git a/django/db/migrations/operations/models.py b/django/db/migrations/operations/models.py
index 783cfcc519..f376324580 100644
--- a/django/db/migrations/operations/models.py
+++ b/django/db/migrations/operations/models.py
@@ -3,7 +3,6 @@ from django.db.migrations.operations.base import Operation
from django.db.migrations.state import ModelState
from django.db.models.fields.related import RECURSIVE_RELATIONSHIP_CONSTANT
from django.db.models.options import normalize_together
-from django.utils import six
from django.utils.functional import cached_property
from .fields import (
@@ -57,7 +56,7 @@ class CreateModel(ModelOperation):
_check_for_duplicates('fields', (name for name, _ in self.fields))
_check_for_duplicates('bases', (
base._meta.label_lower if hasattr(base, '_meta') else
- base.lower() if isinstance(base, six.string_types) else base
+ base.lower() if isinstance(base, str) else base
for base in self.bases
))
_check_for_duplicates('managers', (name for name, _ in self.managers))
@@ -110,7 +109,7 @@ class CreateModel(ModelOperation):
# Check we didn't inherit from the model
models_to_check = [
base for base in self.bases
- if base is not models.Model and isinstance(base, (models.base.ModelBase, six.string_types))
+ if base is not models.Model and isinstance(base, (models.base.ModelBase, str))
]
# Check we have no FKs/M2Ms with it
for fname, field in self.fields:
@@ -129,7 +128,7 @@ class CreateModel(ModelOperation):
Take either a model class or an "app_label.ModelName" string
and return (app_label, object_name).
"""
- if isinstance(model, six.string_types):
+ if isinstance(model, str):
return model.split(".", 1)
else:
return model._meta.app_label, model._meta.object_name
diff --git a/django/db/migrations/serializer.py b/django/db/migrations/serializer.py
index 261fcabd73..bcd2268e2a 100644
--- a/django/db/migrations/serializer.py
+++ b/django/db/migrations/serializer.py
@@ -362,11 +362,11 @@ def serializer_factory(value):
return SettingsReferenceSerializer(value)
if isinstance(value, float):
return FloatSerializer(value)
- if isinstance(value, six.integer_types + (bool, type(None))):
+ if isinstance(value, (bool, int, type(None))):
return BaseSimpleSerializer(value)
- if isinstance(value, six.binary_type):
+ if isinstance(value, bytes):
return ByteTypeSerializer(value)
- if isinstance(value, six.text_type):
+ if isinstance(value, str):
return TextTypeSerializer(value)
if isinstance(value, decimal.Decimal):
return DecimalSerializer(value)
diff --git a/django/db/migrations/state.py b/django/db/migrations/state.py
index c88663ff3a..db42220918 100644
--- a/django/db/migrations/state.py
+++ b/django/db/migrations/state.py
@@ -10,7 +10,6 @@ from django.db.models.fields.proxy import OrderWrt
from django.db.models.fields.related import RECURSIVE_RELATIONSHIP_CONSTANT
from django.db.models.options import DEFAULT_NAMES, normalize_together
from django.db.models.utils import make_model_tuple
-from django.utils import six
from django.utils.encoding import force_text
from django.utils.functional import cached_property
from django.utils.module_loading import import_string
@@ -20,7 +19,7 @@ from .exceptions import InvalidBasesError
def _get_app_label_and_model_name(model, app_label=''):
- if isinstance(model, six.string_types):
+ if isinstance(model, str):
split = model.split('.', 1)
return (tuple(split) if len(split) == 2 else (app_label, split[0]))
else:
@@ -37,7 +36,7 @@ def _get_related_models(m):
]
related_fields_models = set()
for f in m._meta.get_fields(include_parents=True, include_hidden=True):
- if f.is_relation and f.related_model is not None and not isinstance(f.related_model, six.string_types):
+ if f.is_relation and f.related_model is not None and not isinstance(f.related_model, str):
related_fields_models.add(f.model)
related_models.append(f.related_model)
# Reverse accessors of foreign keys to proxy models are attached to their
@@ -458,7 +457,7 @@ class ModelState(object):
options[name] = set(normalize_together(it))
else:
options[name] = model._meta.original_attrs[name]
- # Force-convert all options to text_type (#23226)
+ # Force-convert all options to str (#23226)
options = cls.force_text_recursive(options)
# If we're ignoring relationships, remove all field-listing model
# options (that option basically just means "make a stub model")
@@ -496,7 +495,7 @@ class ModelState(object):
for base in flattened_bases
)
# Ensure at least one base inherits from models.Model
- if not any((isinstance(base, six.string_types) or issubclass(base, models.Model)) for base in bases):
+ if not any((isinstance(base, str) or issubclass(base, models.Model)) for base in bases):
bases = (models.Model,)
managers = []
@@ -539,9 +538,7 @@ class ModelState(object):
@classmethod
def force_text_recursive(cls, value):
- if isinstance(value, six.string_types):
- return force_text(value)
- elif isinstance(value, list):
+ if isinstance(value, list):
return [cls.force_text_recursive(x) for x in value]
elif isinstance(value, tuple):
return tuple(cls.force_text_recursive(x) for x in value)
@@ -588,7 +585,7 @@ class ModelState(object):
# Then, work out our bases
try:
bases = tuple(
- (apps.get_model(base) if isinstance(base, six.string_types) else base)
+ (apps.get_model(base) if isinstance(base, str) else base)
for base in self.bases
)
except LookupError:
diff --git a/django/db/models/base.py b/django/db/models/base.py
index 38d0b96217..95700edb13 100644
--- a/django/db/models/base.py
+++ b/django/db/models/base.py
@@ -504,7 +504,7 @@ class Model(six.with_metaclass(ModelBase)):
def __repr__(self):
try:
- u = six.text_type(self)
+ u = str(self)
except (UnicodeEncodeError, UnicodeDecodeError):
u = '[Bad Unicode data]'
return force_str('<%s: %s>' % (self.__class__.__name__, u))
@@ -1089,12 +1089,12 @@ class Model(six.with_metaclass(ModelBase)):
code='unique_for_date',
params={
'model': self,
- 'model_name': six.text_type(capfirst(opts.verbose_name)),
+ 'model_name': capfirst(opts.verbose_name),
'lookup_type': lookup_type,
'field': field_name,
- 'field_label': six.text_type(capfirst(field.verbose_name)),
+ 'field_label': capfirst(field.verbose_name),
'date_field': unique_for,
- 'date_field_label': six.text_type(capfirst(opts.get_field(unique_for).verbose_name)),
+ 'date_field_label': capfirst(opts.get_field(unique_for).verbose_name),
}
)
@@ -1104,14 +1104,14 @@ class Model(six.with_metaclass(ModelBase)):
params = {
'model': self,
'model_class': model_class,
- 'model_name': six.text_type(capfirst(opts.verbose_name)),
+ 'model_name': capfirst(opts.verbose_name),
'unique_check': unique_check,
}
# A unique field
if len(unique_check) == 1:
field = opts.get_field(unique_check[0])
- params['field_label'] = six.text_type(capfirst(field.verbose_name))
+ params['field_label'] = capfirst(field.verbose_name)
return ValidationError(
message=field.error_messages['unique'],
code='unique',
@@ -1121,7 +1121,7 @@ class Model(six.with_metaclass(ModelBase)):
# unique_together
else:
field_labels = [capfirst(opts.get_field(f).verbose_name) for f in unique_check]
- params['field_labels'] = six.text_type(get_text_list(field_labels, _('and')))
+ params['field_labels'] = get_text_list(field_labels, _('and'))
return ValidationError(
message=_("%(model_name)s with this %(field_labels)s already exists."),
code='unique_together',
@@ -1647,7 +1647,7 @@ class Model(six.with_metaclass(ModelBase)):
for f in cls._meta.local_many_to_many:
# Skip nonexistent models.
- if isinstance(f.remote_field.through, six.string_types):
+ if isinstance(f.remote_field.through, str):
continue
# Check if auto-generated name for the M2M field is too long
diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py
index 36c2b969db..960435f169 100644
--- a/django/db/models/expressions.py
+++ b/django/db/models/expressions.py
@@ -5,7 +5,6 @@ from django.core.exceptions import EmptyResultSet, FieldError
from django.db.backends import utils as backend_utils
from django.db.models import fields
from django.db.models.query_utils import Q
-from django.utils import six
from django.utils.functional import cached_property
@@ -149,7 +148,7 @@ class BaseExpression(object):
def _parse_expressions(self, *expressions):
return [
arg if hasattr(arg, 'resolve_expression') else (
- F(arg) if isinstance(arg, six.string_types) else Value(arg)
+ F(arg) if isinstance(arg, str) else Value(arg)
) for arg in expressions
]
diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py
index 2e21a42672..3ac04effc7 100644
--- a/django/db/models/fields/__init__.py
+++ b/django/db/models/fields/__init__.py
@@ -19,7 +19,7 @@ from django.core.exceptions import FieldDoesNotExist # NOQA
from django.db import connection, connections, router
from django.db.models.constants import LOOKUP_SEP
from django.db.models.query_utils import DeferredAttribute, RegisterLookupMixin
-from django.utils import six, timezone
+from django.utils import timezone
from django.utils.datastructures import DictWrapper
from django.utils.dateparse import (
parse_date, parse_datetime, parse_duration, parse_time,
@@ -244,8 +244,7 @@ class Field(RegisterLookupMixin):
def _check_choices(self):
if self.choices:
- if (isinstance(self.choices, six.string_types) or
- not is_iterable(self.choices)):
+ if isinstance(self.choices, str) or not is_iterable(self.choices):
return [
checks.Error(
"'choices' must be an iterable (e.g., a list or tuple).",
@@ -253,7 +252,7 @@ class Field(RegisterLookupMixin):
id='fields.E004',
)
]
- elif any(isinstance(choice, six.string_types) or
+ elif any(isinstance(choice, str) or
not is_iterable(choice) or len(choice) != 2
for choice in self.choices):
return [
@@ -763,7 +762,7 @@ class Field(RegisterLookupMixin):
if not self.empty_strings_allowed or self.null and not connection.features.interprets_empty_strings_as_nulls:
return return_None
- return six.text_type # returns empty string
+ return str # returns empty string
def get_choices(self, include_blank=True, blank_choice=BLANK_CHOICE_DASH, limit_choices_to=None):
"""Returns choices with a default blank choices included, for use
@@ -1038,7 +1037,7 @@ class CharField(Field):
id='fields.E120',
)
]
- elif not isinstance(self.max_length, six.integer_types) or self.max_length <= 0:
+ elif not isinstance(self.max_length, int) or self.max_length <= 0:
return [
checks.Error(
"'max_length' must be a positive integer.",
@@ -1053,7 +1052,7 @@ class CharField(Field):
return "CharField"
def to_python(self, value):
- if isinstance(value, six.string_types) or value is None:
+ if isinstance(value, str) or value is None:
return value
return force_text(value)
@@ -1535,7 +1534,7 @@ class DecimalField(Field):
)
def _format(self, value):
- if isinstance(value, six.string_types):
+ if isinstance(value, str):
return value
else:
return self.format_number(value)
@@ -1703,7 +1702,7 @@ class FilePathField(Field):
value = super(FilePathField, self).get_prep_value(value)
if value is None:
return None
- return six.text_type(value)
+ return str(value)
def formfield(self, **kwargs):
defaults = {
@@ -1867,7 +1866,7 @@ class IPAddressField(Field):
value = super(IPAddressField, self).get_prep_value(value)
if value is None:
return None
- return six.text_type(value)
+ return str(value)
def get_internal_type(self):
return "IPAddressField"
@@ -1922,7 +1921,7 @@ class GenericIPAddressField(Field):
def to_python(self, value):
if value is None:
return None
- if not isinstance(value, six.string_types):
+ if not isinstance(value, str):
value = force_text(value)
value = value.strip()
if ':' in value:
@@ -1943,7 +1942,7 @@ class GenericIPAddressField(Field):
return clean_ipv6_address(value, self.unpack_ipv4)
except exceptions.ValidationError:
pass
- return six.text_type(value)
+ return str(value)
def formfield(self, **kwargs):
defaults = {
@@ -2094,7 +2093,7 @@ class TextField(Field):
return "TextField"
def to_python(self, value):
- if isinstance(value, six.string_types) or value is None:
+ if isinstance(value, str) or value is None:
return value
return force_text(value)
@@ -2310,8 +2309,8 @@ class BinaryField(Field):
def to_python(self, value):
# If it's a string, it should be base64-encoded data
- if isinstance(value, six.text_type):
- return six.memoryview(b64decode(force_bytes(value)))
+ if isinstance(value, str):
+ return memoryview(b64decode(force_bytes(value)))
return value
diff --git a/django/db/models/fields/files.py b/django/db/models/fields/files.py
index e52cc1164d..90b6515409 100644
--- a/django/db/models/fields/files.py
+++ b/django/db/models/fields/files.py
@@ -9,7 +9,6 @@ from django.core.files.storage import default_storage
from django.core.validators import validate_image_file_extension
from django.db.models import signals
from django.db.models.fields import Field
-from django.utils import six
from django.utils.encoding import force_str, force_text
from django.utils.translation import ugettext_lazy as _
@@ -181,7 +180,7 @@ class FileDescriptor(object):
# subclasses might also want to subclass the attribute class]. This
# object understands how to convert a path to a file, and also how to
# handle None.
- if isinstance(file, six.string_types) or file is None:
+ if isinstance(file, str) or file is None:
attr = self.field.attr_class(instance, self.field, file)
instance.__dict__[self.field.name] = attr
@@ -253,7 +252,7 @@ class FileField(Field):
return []
def _check_upload_to(self):
- if isinstance(self.upload_to, six.string_types) and self.upload_to.startswith('/'):
+ if isinstance(self.upload_to, str) and self.upload_to.startswith('/'):
return [
checks.Error(
"%s's 'upload_to' argument must be a relative path, not an "
@@ -284,7 +283,7 @@ class FileField(Field):
# Need to convert File objects provided via a form to unicode for database insertion
if value is None:
return None
- return six.text_type(value)
+ return str(value)
def pre_save(self, model_instance, add):
"Returns field's value just before saving."
diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py
index 7f7a6d3ea8..65d0da41e1 100644
--- a/django/db/models/fields/related.py
+++ b/django/db/models/fields/related.py
@@ -11,7 +11,6 @@ from django.db.models.constants import LOOKUP_SEP
from django.db.models.deletion import CASCADE, SET_DEFAULT, SET_NULL
from django.db.models.query_utils import PathInfo
from django.db.models.utils import make_model_tuple
-from django.utils import six
from django.utils.encoding import force_text
from django.utils.functional import cached_property, curry
from django.utils.lru_cache import lru_cache
@@ -52,7 +51,7 @@ def resolve_relation(scope_model, relation):
relation = scope_model
# Look for an "app.Model" relation
- if isinstance(relation, six.string_types):
+ if isinstance(relation, str):
if "." not in relation:
relation = "%s.%s" % (scope_model._meta.app_label, relation)
@@ -160,7 +159,7 @@ class RelatedField(Field):
def _check_relation_model_exists(self):
rel_is_missing = self.remote_field.model not in self.opts.apps.get_models()
- rel_is_string = isinstance(self.remote_field.model, six.string_types)
+ rel_is_string = isinstance(self.remote_field.model, str)
model_name = self.remote_field.model if rel_is_string else self.remote_field.model._meta.object_name
if rel_is_missing and (rel_is_string or not self.remote_field.model._meta.swapped):
return [
@@ -175,7 +174,7 @@ class RelatedField(Field):
def _check_referencing_to_swapped_model(self):
if (self.remote_field.model not in self.opts.apps.get_models() and
- not isinstance(self.remote_field.model, six.string_types) and
+ not isinstance(self.remote_field.model, str) and
self.remote_field.model._meta.swapped):
model = "%s.%s" % (
self.remote_field.model._meta.app_label,
@@ -364,7 +363,7 @@ class RelatedField(Field):
"""
if self.swappable:
# Work out string form of "to"
- if isinstance(self.remote_field.model, six.string_types):
+ if isinstance(self.remote_field.model, str):
to_string = self.remote_field.model
else:
to_string = self.remote_field.model._meta.label
@@ -479,7 +478,7 @@ class ForeignObject(RelatedField):
def _check_to_fields_exist(self):
# Skip nonexistent models.
- if isinstance(self.remote_field.model, six.string_types):
+ if isinstance(self.remote_field.model, str):
return []
errors = []
@@ -500,7 +499,7 @@ class ForeignObject(RelatedField):
return errors
def _check_unique_target(self):
- rel_is_string = isinstance(self.remote_field.model, six.string_types)
+ rel_is_string = isinstance(self.remote_field.model, str)
if rel_is_string or not self.requires_unique_target:
return []
@@ -568,7 +567,7 @@ class ForeignObject(RelatedField):
if self.remote_field.parent_link:
kwargs['parent_link'] = self.remote_field.parent_link
# Work out string form of "to"
- if isinstance(self.remote_field.model, six.string_types):
+ if isinstance(self.remote_field.model, str):
kwargs['to'] = self.remote_field.model
else:
kwargs['to'] = "%s.%s" % (
@@ -598,7 +597,7 @@ class ForeignObject(RelatedField):
def resolve_related_fields(self):
if len(self.from_fields) < 1 or len(self.from_fields) != len(self.to_fields):
raise ValueError('Foreign Object from and to fields must be the same non-zero length')
- if isinstance(self.remote_field.model, six.string_types):
+ if isinstance(self.remote_field.model, str):
raise ValueError('Related model %r cannot be resolved' % self.remote_field.model)
related_fields = []
for index in range(len(self.from_fields)):
@@ -772,7 +771,7 @@ class ForeignKey(ForeignObject):
try:
to._meta.model_name
except AttributeError:
- assert isinstance(to, six.string_types), (
+ assert isinstance(to, str), (
"%s(%r) is invalid. First parameter to ForeignKey must be "
"either a model, a model name, or the string %r" % (
self.__class__.__name__, to,
@@ -926,7 +925,7 @@ class ForeignKey(ForeignObject):
def formfield(self, **kwargs):
db = kwargs.pop('using', None)
- if isinstance(self.remote_field.model, six.string_types):
+ if isinstance(self.remote_field.model, str):
raise ValueError("Cannot create form field for %r yet, because "
"its related model %r has not been loaded yet" %
(self.name, self.remote_field.model))
@@ -948,7 +947,7 @@ class ForeignKey(ForeignObject):
return {"type": self.db_type(connection), "check": self.db_check(connection)}
def convert_empty_strings(self, value, expression, connection, context):
- if (not value) and isinstance(value, six.string_types):
+ if (not value) and isinstance(value, str):
return None
return value
@@ -1082,14 +1081,11 @@ class ManyToManyField(RelatedField):
try:
to._meta
except AttributeError:
- assert isinstance(to, six.string_types), (
+ assert isinstance(to, str), (
"%s(%r) is invalid. First parameter to ManyToManyField must be "
"either a model, a model name, or the string %r" %
(self.__class__.__name__, to, RECURSIVE_RELATIONSHIP_CONSTANT)
)
- # Class names must be ASCII in Python 2.x, so we forcibly coerce it
- # here to break early if there's a problem.
- to = str(to)
if symmetrical is None:
symmetrical = (to == RECURSIVE_RELATIONSHIP_CONSTANT)
@@ -1197,7 +1193,7 @@ class ManyToManyField(RelatedField):
# Set some useful local variables
to_model = resolve_relation(from_model, self.remote_field.model)
from_model_name = from_model._meta.object_name
- if isinstance(to_model, six.string_types):
+ if isinstance(to_model, str):
to_model_name = to_model
else:
to_model_name = to_model._meta.object_name
@@ -1368,7 +1364,7 @@ class ManyToManyField(RelatedField):
return errors
def _check_table_uniqueness(self, **kwargs):
- if isinstance(self.remote_field.through, six.string_types) or not self.remote_field.through._meta.managed:
+ if isinstance(self.remote_field.through, str) or not self.remote_field.through._meta.managed:
return []
registered_tables = {
model._meta.db_table: model
@@ -1411,7 +1407,7 @@ class ManyToManyField(RelatedField):
if self.remote_field.related_query_name is not None:
kwargs['related_query_name'] = self.remote_field.related_query_name
# Rel needs more work.
- if isinstance(self.remote_field.model, six.string_types):
+ if isinstance(self.remote_field.model, str):
kwargs['to'] = self.remote_field.model
else:
kwargs['to'] = "%s.%s" % (
@@ -1419,7 +1415,7 @@ class ManyToManyField(RelatedField):
self.remote_field.model._meta.object_name,
)
if getattr(self.remote_field, 'through', None) is not None:
- if isinstance(self.remote_field.through, six.string_types):
+ if isinstance(self.remote_field.through, str):
kwargs['through'] = self.remote_field.through
elif not self.remote_field.through._meta.auto_created:
kwargs['through'] = "%s.%s" % (
diff --git a/django/db/models/options.py b/django/db/models/options.py
index a4593d125a..cf3e031104 100644
--- a/django/db/models/options.py
+++ b/django/db/models/options.py
@@ -310,7 +310,7 @@ class Options(object):
"""
if self.proxy or self.swapped or not self.managed:
return False
- if isinstance(connection, six.string_types):
+ if isinstance(connection, str):
connection = connections[connection]
if self.required_db_vendor:
return self.required_db_vendor == connection.vendor
@@ -689,7 +689,7 @@ class Options(object):
if f.is_relation and f.related_model is not None
)
for f in fields_with_relations:
- if not isinstance(f.remote_field.model, six.string_types):
+ if not isinstance(f.remote_field.model, str):
related_objects_graph[f.remote_field.model._meta.concrete_model._meta].append(f)
for model in all_models:
diff --git a/django/db/models/query.py b/django/db/models/query.py
index 2dbe3b7461..69f84d72a9 100644
--- a/django/db/models/query.py
+++ b/django/db/models/query.py
@@ -260,7 +260,7 @@ class QuerySet(object):
"""
Retrieves an item or slice from the set of results.
"""
- if not isinstance(k, (slice,) + six.integer_types):
+ if not isinstance(k, (int, slice)):
raise TypeError
assert ((not isinstance(k, slice) and (k >= 0)) or
(isinstance(k, slice) and (k.start is None or k.start >= 0) and
diff --git a/django/db/models/signals.py b/django/db/models/signals.py
index 9f9fbccde3..a511024342 100644
--- a/django/db/models/signals.py
+++ b/django/db/models/signals.py
@@ -2,7 +2,6 @@ from functools import partial
from django.db.models.utils import make_model_tuple
from django.dispatch import Signal
-from django.utils import six
class_prepared = Signal(providing_args=["class"])
@@ -18,7 +17,7 @@ class ModelSignal(Signal):
# This partial takes a single optional argument named "sender".
partial_method = partial(method, receiver, **kwargs)
- if isinstance(sender, six.string_types):
+ if isinstance(sender, str):
apps = apps or Options.default_apps
apps.lazy_model_operation(partial_method, make_model_tuple(sender))
else:
diff --git a/django/db/models/utils.py b/django/db/models/utils.py
index cda96277a6..7d563c4ae0 100644
--- a/django/db/models/utils.py
+++ b/django/db/models/utils.py
@@ -1,6 +1,3 @@
-from django.utils import six
-
-
def make_model_tuple(model):
"""
Takes a model or a string of the form "app_label.ModelName" and returns a
@@ -10,7 +7,7 @@ def make_model_tuple(model):
try:
if isinstance(model, tuple):
model_tuple = model
- elif isinstance(model, six.string_types):
+ elif isinstance(model, str):
app_label, model_name = model.split(".")
model_tuple = app_label, model_name.lower()
else:
diff --git a/django/db/utils.py b/django/db/utils.py
index 4451f5a60e..a65510ea80 100644
--- a/django/db/utils.py
+++ b/django/db/utils.py
@@ -247,7 +247,7 @@ class ConnectionRouter(object):
self._routers = settings.DATABASE_ROUTERS
routers = []
for r in self._routers:
- if isinstance(r, six.string_types):
+ if isinstance(r, str):
router = import_string(r)()
else:
router = r
diff --git a/django/forms/boundfield.py b/django/forms/boundfield.py
index 6faff6ffc9..dc40bca508 100644
--- a/django/forms/boundfield.py
+++ b/django/forms/boundfield.py
@@ -3,7 +3,6 @@ import warnings
from django.forms.utils import flatatt, pretty_name
from django.forms.widgets import Textarea, TextInput
-from django.utils import six
from django.utils.deprecation import RemovedInDjango21Warning
from django.utils.encoding import force_text
from django.utils.functional import cached_property
@@ -63,7 +62,7 @@ class BoundField(object):
def __getitem__(self, idx):
# Prevent unnecessary reevaluation when accessing BoundField's attrs
# from templates.
- if not isinstance(idx, six.integer_types + (slice,)):
+ if not isinstance(idx, (int, slice)):
raise TypeError
return self.subwidgets[idx]
diff --git a/django/forms/fields.py b/django/forms/fields.py
index 65824fbd97..5be10708c3 100644
--- a/django/forms/fields.py
+++ b/django/forms/fields.py
@@ -393,10 +393,10 @@ class BaseTemporalField(Field):
def to_python(self, value):
# Try to coerce the value to unicode.
unicode_value = force_text(value, strings_only=True)
- if isinstance(unicode_value, six.text_type):
+ if isinstance(unicode_value, str):
value = unicode_value.strip()
# If unicode, try to strptime against each input format.
- if isinstance(value, six.text_type):
+ if isinstance(value, str):
for format in self.input_formats:
try:
return self.strptime(value, format)
@@ -521,7 +521,7 @@ class RegexField(CharField):
return self._regex
def _set_regex(self, regex):
- if isinstance(regex, six.string_types):
+ if isinstance(regex, str):
regex = re.compile(regex, re.UNICODE)
self._regex = regex
if hasattr(self, '_regex_validator') and self._regex_validator in self.validators:
@@ -712,7 +712,7 @@ class BooleanField(Field):
# will submit for False. Also check for '0', since this is what
# RadioSelect will provide. Because bool("True") == bool('1') == True,
# we don't need to handle that explicitly.
- if isinstance(value, six.string_types) and value.lower() in ('false', '0'):
+ if isinstance(value, str) and value.lower() in ('false', '0'):
value = False
else:
value = bool(value)
diff --git a/django/forms/forms.py b/django/forms/forms.py
index 3971893aa2..c8086b1361 100644
--- a/django/forms/forms.py
+++ b/django/forms/forms.py
@@ -209,7 +209,7 @@ class BaseForm(object):
top_errors.extend(
[_('(Hidden field %(name)s) %(error)s') % {'name': name, 'error': force_text(e)}
for e in bf_errors])
- hidden_fields.append(six.text_type(bf))
+ hidden_fields.append(str(bf))
else:
# Create a 'class="..."' attribute if the row should have any
# CSS classes applied.
@@ -234,7 +234,7 @@ class BaseForm(object):
output.append(normal_row % {
'errors': force_text(bf_errors),
'label': force_text(label),
- 'field': six.text_type(bf),
+ 'field': str(bf),
'help_text': help_text,
'html_class_attr': html_class_attr,
'css_classes': css_classes,
diff --git a/django/forms/formsets.py b/django/forms/formsets.py
index 81788626e1..60638c475c 100644
--- a/django/forms/formsets.py
+++ b/django/forms/formsets.py
@@ -3,7 +3,6 @@ from django.forms import Form
from django.forms.fields import BooleanField, IntegerField
from django.forms.utils import ErrorList
from django.forms.widgets import HiddenInput
-from django.utils import six
from django.utils.functional import cached_property
from django.utils.html import html_safe
from django.utils.safestring import mark_safe
@@ -416,17 +415,17 @@ class BaseFormSet(object):
# probably should be. It might make sense to render each form as a
# table row with each field as a td.
forms = ' '.join(form.as_table() for form in self)
- return mark_safe('\n'.join([six.text_type(self.management_form), forms]))
+ return mark_safe('\n'.join([str(self.management_form), forms]))
def as_p(self):
"Returns this formset rendered as HTML
s."
forms = ' '.join(form.as_p() for form in self)
- return mark_safe('\n'.join([six.text_type(self.management_form), forms]))
+ return mark_safe('\n'.join([str(self.management_form), forms]))
def as_ul(self):
"Returns this formset rendered as HTML
s."
forms = ' '.join(form.as_ul() for form in self)
- return mark_safe('\n'.join([six.text_type(self.management_form), forms]))
+ return mark_safe('\n'.join([str(self.management_form), forms]))
def formset_factory(form, formset=BaseFormSet, extra=1, can_order=False,
diff --git a/django/forms/models.py b/django/forms/models.py
index 38f6812ba0..c3a1b81c8c 100644
--- a/django/forms/models.py
+++ b/django/forms/models.py
@@ -220,7 +220,7 @@ class ModelFormMetaclass(DeclarativeFieldsMetaclass):
# of ('foo',)
for opt in ['fields', 'exclude', 'localized_fields']:
value = getattr(opts, opt)
- if isinstance(value, six.string_types) and value != ALL_FIELDS:
+ if isinstance(value, str) and value != ALL_FIELDS:
msg = ("%(model)s.Meta.%(opt)s cannot be a string. "
"Did you mean to type: ('%(value)s',)?" % {
'model': new_class.__name__,
@@ -727,7 +727,7 @@ class BaseModelFormSet(BaseFormSet):
}
else:
return ugettext("Please correct the duplicate data for %(field)s, which must be unique.") % {
- "field": get_text_list(unique_check, six.text_type(_("and"))),
+ "field": get_text_list(unique_check, _("and")),
}
def get_date_error_message(self, date_check):
@@ -737,7 +737,7 @@ class BaseModelFormSet(BaseFormSet):
) % {
'field_name': date_check[2],
'date_field': date_check[3],
- 'lookup': six.text_type(date_check[1]),
+ 'lookup': str(date_check[1]),
}
def get_form_error(self):
@@ -1305,7 +1305,7 @@ class ModelMultipleChoiceField(ModelChoiceField):
def prepare_value(self, value):
if (hasattr(value, '__iter__') and
- not isinstance(value, six.text_type) and
+ not isinstance(value, str) and
not hasattr(value, '_meta')):
return [super(ModelMultipleChoiceField, self).prepare_value(v) for v in value]
return super(ModelMultipleChoiceField, self).prepare_value(value)
diff --git a/django/forms/widgets.py b/django/forms/widgets.py
index c4bbb7fe4f..e21dba0607 100644
--- a/django/forms/widgets.py
+++ b/django/forms/widgets.py
@@ -498,7 +498,7 @@ class CheckboxInput(Input):
value = data.get(name)
# Translate true and false strings to boolean values.
values = {'true': True, 'false': False}
- if isinstance(value, six.string_types):
+ if isinstance(value, str):
value = values.get(value.lower(), value)
return bool(value)
@@ -671,10 +671,7 @@ class Select(ChoiceWidget):
def _choice_has_empty_value(choice):
"""Return True if the choice's value is empty string or None."""
value, _ = choice
- return (
- (isinstance(value, six.string_types) and not bool(value)) or
- value is None
- )
+ return (isinstance(value, str) and not bool(value)) or value is None
def use_required_attribute(self, initial):
"""
@@ -986,7 +983,7 @@ class SelectDateWidget(Widget):
year, month, day = None, None, None
if isinstance(value, (datetime.date, datetime.datetime)):
year, month, day = value.year, value.month, value.day
- elif isinstance(value, six.string_types):
+ elif isinstance(value, str):
if settings.USE_L10N:
try:
input_format = get_format('DATE_INPUT_FORMATS')[0]
diff --git a/django/http/multipartparser.py b/django/http/multipartparser.py
index 812e83eff0..b1db1f81ca 100644
--- a/django/http/multipartparser.py
+++ b/django/http/multipartparser.py
@@ -84,7 +84,7 @@ class MultiPartParser(object):
# This means we shouldn't continue...raise an error.
raise MultiPartParserError("Invalid content length: %r" % content_length)
- if isinstance(boundary, six.text_type):
+ if isinstance(boundary, str):
boundary = boundary.encode('ascii')
self._boundary = boundary
self._input_data = input_data
diff --git a/django/http/request.py b/django/http/request.py
index b4053142ac..fe1684ee58 100644
--- a/django/http/request.py
+++ b/django/http/request.py
@@ -522,7 +522,7 @@ def bytes_to_text(s, encoding):
Returns any non-basestring objects without change.
"""
if isinstance(s, bytes):
- return six.text_type(s, encoding, 'replace')
+ return str(s, encoding, 'replace')
else:
return s
diff --git a/django/http/response.py b/django/http/response.py
index e4cce4fdbe..1c2677035d 100644
--- a/django/http/response.py
+++ b/django/http/response.py
@@ -113,10 +113,10 @@ class HttpResponseBase(six.Iterator):
`value` can't be represented in the given charset, MIME-encoding
is applied.
"""
- if not isinstance(value, (bytes, six.text_type)):
+ if not isinstance(value, (bytes, str)):
value = str(value)
if ((isinstance(value, bytes) and (b'\n' in value or b'\r' in value)) or
- isinstance(value, six.text_type) and ('\n' in value or '\r' in value)):
+ isinstance(value, str) and ('\n' in value or '\r' in value)):
raise BadHeaderError("Header values can't contain newlines (got %r)" % value)
try:
if isinstance(value, str):
@@ -226,11 +226,11 @@ class HttpResponseBase(six.Iterator):
# This doesn't make a copy when `value` already contains bytes.
# Handle string types -- we can't rely on force_bytes here because:
- # - under Python 3 it attempts str conversion first
+ # - Python attempts str conversion first
# - when self._charset != 'utf-8' it re-encodes the content
if isinstance(value, bytes):
return bytes(value)
- if isinstance(value, six.text_type):
+ if isinstance(value, str):
return bytes(value.encode(self.charset))
# Handle non-string types (#16494)
@@ -309,7 +309,7 @@ class HttpResponse(HttpResponseBase):
@content.setter
def content(self, value):
# Consume iterators upon assignment to allow repeated iteration.
- if hasattr(value, '__iter__') and not isinstance(value, (bytes, six.string_types)):
+ if hasattr(value, '__iter__') and not isinstance(value, (bytes, str)):
content = b''.join(self.make_bytes(chunk) for chunk in value)
if hasattr(value, 'close'):
try:
diff --git a/django/shortcuts.py b/django/shortcuts.py
index f4fa0600ac..b27a75206f 100644
--- a/django/shortcuts.py
+++ b/django/shortcuts.py
@@ -8,7 +8,6 @@ from django.http import (
)
from django.template import loader
from django.urls import NoReverseMatch, reverse
-from django.utils import six
from django.utils.encoding import force_text
from django.utils.functional import Promise
@@ -137,7 +136,7 @@ def resolve_url(to, *args, **kwargs):
# further to some Python functions like urlparse.
to = force_text(to)
- if isinstance(to, six.string_types):
+ if isinstance(to, str):
# Handle relative URLs
if to.startswith(('./', '../')):
return to
diff --git a/django/template/base.py b/django/template/base.py
index aa30d2e2b3..c7c2249aa0 100644
--- a/django/template/base.py
+++ b/django/template/base.py
@@ -56,7 +56,6 @@ import re
from django.template.context import ( # NOQA: imported for backwards compatibility
BaseContext, Context, ContextPopException, RequestContext,
)
-from django.utils import six
from django.utils.encoding import force_str, force_text
from django.utils.formats import localize
from django.utils.html import conditional_escape, escape
@@ -771,7 +770,7 @@ class Variable(object):
self.translate = False
self.message_context = None
- if not isinstance(var, six.string_types):
+ if not isinstance(var, str):
raise TypeError(
"Variable must be a string or number, got %s" % type(var))
try:
diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py
index fc249953ea..828255b73c 100644
--- a/django/template/defaultfilters.py
+++ b/django/template/defaultfilters.py
@@ -6,7 +6,7 @@ from functools import wraps
from operator import itemgetter
from pprint import pformat
-from django.utils import formats, six
+from django.utils import formats
from django.utils.dateformat import format, time_format
from django.utils.encoding import force_text, iri_to_uri
from django.utils.html import (
@@ -168,7 +168,7 @@ def floatformat(text, arg=-1):
# Avoid conversion to scientific notation by accessing `sign`, `digits`
# and `exponent` from `Decimal.as_tuple()` directly.
sign, digits, exponent = d.quantize(exp, ROUND_HALF_UP, Context(prec=prec)).as_tuple()
- digits = [six.text_type(digit) for digit in reversed(digits)]
+ digits = [str(digit) for digit in reversed(digits)]
while len(digits) <= abs(exponent):
digits.append('0')
digits.insert(-exponent, '.')
@@ -194,7 +194,7 @@ def linenumbers(value, autoescape=True):
lines = value.split('\n')
# Find the maximum width of the line count, for use with zero padding
# string format command
- width = six.text_type(len(six.text_type(len(lines))))
+ width = str(len(str(len(lines))))
if not autoescape or isinstance(value, SafeData):
for i, line in enumerate(lines):
lines[i] = ("%0" + width + "d. %s") % (i + 1, line)
@@ -246,7 +246,7 @@ def stringformat(value, arg):
for documentation of Python string formatting.
"""
try:
- return ("%" + six.text_type(arg)) % value
+ return ("%" + str(arg)) % value
except (ValueError, TypeError):
return ""
@@ -675,7 +675,7 @@ def unordered_list(value, autoescape=True):
except StopIteration:
yield item, None
break
- if not isinstance(next_item, six.string_types):
+ if not isinstance(next_item, str):
try:
iter(next_item)
except TypeError:
diff --git a/django/template/engine.py b/django/template/engine.py
index 154276a5b0..6d73569e02 100644
--- a/django/template/engine.py
+++ b/django/template/engine.py
@@ -1,5 +1,5 @@
from django.core.exceptions import ImproperlyConfigured
-from django.utils import lru_cache, six
+from django.utils import lru_cache
from django.utils.functional import cached_property
from django.utils.module_loading import import_string
@@ -120,7 +120,7 @@ class Engine(object):
else:
args = []
- if isinstance(loader, six.string_types):
+ if isinstance(loader, str):
loader_class = import_string(loader)
return loader_class(self, *args)
else:
diff --git a/django/template/library.py b/django/template/library.py
index 8a6c98ee09..b7e3cad532 100644
--- a/django/template/library.py
+++ b/django/template/library.py
@@ -1,7 +1,6 @@
import functools
from importlib import import_module
-from django.utils import six
from django.utils.html import conditional_escape
from django.utils.inspect import getargspec
from django.utils.itercompat import is_iterable
@@ -220,7 +219,7 @@ class InclusionNode(TagHelperNode):
t = self.filename
elif isinstance(getattr(self.filename, 'template', None), Template):
t = self.filename.template
- elif not isinstance(self.filename, six.string_types) and is_iterable(self.filename):
+ elif not isinstance(self.filename, str) and is_iterable(self.filename):
t = context.template.engine.select_template(self.filename)
else:
t = context.template.engine.get_template(self.filename)
diff --git a/django/template/loader.py b/django/template/loader.py
index 17b278812b..fe598bc816 100644
--- a/django/template/loader.py
+++ b/django/template/loader.py
@@ -1,5 +1,3 @@
-from django.utils import six
-
from . import engines
from .exceptions import TemplateDoesNotExist
@@ -29,7 +27,7 @@ def select_template(template_name_list, using=None):
Raises TemplateDoesNotExist if no such template exists.
"""
- if isinstance(template_name_list, six.string_types):
+ if isinstance(template_name_list, str):
raise TypeError(
'select_template() takes an iterable of template names but got a '
'string: %r. Use get_template() if you want to load a single '
diff --git a/django/template/response.py b/django/template/response.py
index 95cb335ab4..e5c1fbfa66 100644
--- a/django/template/response.py
+++ b/django/template/response.py
@@ -1,5 +1,4 @@
from django.http import HttpResponse
-from django.utils import six
from .loader import get_template, select_template
@@ -62,7 +61,7 @@ class SimpleTemplateResponse(HttpResponse):
"Accepts a template object, path-to-template or list of paths"
if isinstance(template, (list, tuple)):
return select_template(template, using=self.using)
- elif isinstance(template, six.string_types):
+ elif isinstance(template, str):
return get_template(template, using=self.using)
else:
return template
diff --git a/django/templatetags/i18n.py b/django/templatetags/i18n.py
index 4a32e628c2..407ce87609 100644
--- a/django/templatetags/i18n.py
+++ b/django/templatetags/i18n.py
@@ -74,7 +74,7 @@ class TranslateNode(Node):
self.asvar = asvar
self.message_context = message_context
self.filter_expression = filter_expression
- if isinstance(self.filter_expression.var, six.string_types):
+ if isinstance(self.filter_expression.var, str):
self.filter_expression.var = Variable("'%s'" %
self.filter_expression.var)
diff --git a/django/templatetags/tz.py b/django/templatetags/tz.py
index 4088ba7eb8..99d391e45d 100644
--- a/django/templatetags/tz.py
+++ b/django/templatetags/tz.py
@@ -3,7 +3,7 @@ from datetime import datetime, tzinfo
import pytz
from django.template import Library, Node, TemplateSyntaxError
-from django.utils import six, timezone
+from django.utils import timezone
register = Library()
@@ -59,7 +59,7 @@ def do_timezone(value, arg):
# Obtain a tzinfo instance
if isinstance(arg, tzinfo):
tz = arg
- elif isinstance(arg, six.string_types):
+ elif isinstance(arg, str):
try:
tz = pytz.timezone(arg)
except pytz.UnknownTimeZoneError:
diff --git a/django/test/client.py b/django/test/client.py
index 8134c17253..1c08ada1cf 100644
--- a/django/test/client.py
+++ b/django/test/client.py
@@ -197,7 +197,7 @@ def encode_multipart(boundary, data):
for (key, value) in data.items():
if is_file(value):
lines.extend(encode_file(boundary, key, value))
- elif not isinstance(value, six.string_types) and is_iterable(value):
+ elif not isinstance(value, str) and is_iterable(value):
for item in value:
if is_file(item):
lines.extend(encode_file(boundary, key, item))
@@ -229,7 +229,7 @@ def encode_file(boundary, key, file):
# file.name might not be a string. For example, it's an int for
# tempfile.TemporaryFile().
- file_has_string_name = hasattr(file, 'name') and isinstance(file.name, six.string_types)
+ file_has_string_name = hasattr(file, 'name') and isinstance(file.name, str)
filename = os.path.basename(file.name) if file_has_string_name else ''
if hasattr(file, 'content_type'):
diff --git a/django/test/html.py b/django/test/html.py
index fd78e6b713..d84b9770e1 100644
--- a/django/test/html.py
+++ b/django/test/html.py
@@ -4,8 +4,6 @@ Comparing two html documents.
import re
-from django.utils import six
-from django.utils.encoding import force_text
from django.utils.html_parser import HTMLParseError, HTMLParser
WHITESPACE = re.compile(r'\s+')
@@ -22,11 +20,10 @@ class Element(object):
self.children = []
def append(self, element):
- if isinstance(element, six.string_types):
- element = force_text(element)
+ if isinstance(element, str):
element = normalize_whitespace(element)
if self.children:
- if isinstance(self.children[-1], six.string_types):
+ if isinstance(self.children[-1], str):
self.children[-1] += element
self.children[-1] = normalize_whitespace(self.children[-1])
return
@@ -34,7 +31,7 @@ class Element(object):
# removing last children if it is only whitespace
# this can result in incorrect dom representations since
# whitespace between inline tags like is significant
- if isinstance(self.children[-1], six.string_types):
+ if isinstance(self.children[-1], str):
if self.children[-1].isspace():
self.children.pop()
if element:
@@ -43,7 +40,7 @@ class Element(object):
def finalize(self):
def rstrip_last_element(children):
if children:
- if isinstance(children[-1], six.string_types):
+ if isinstance(children[-1], str):
children[-1] = children[-1].rstrip()
if not children[-1]:
children.pop()
@@ -52,7 +49,7 @@ class Element(object):
rstrip_last_element(self.children)
for i, child in enumerate(self.children):
- if isinstance(child, six.string_types):
+ if isinstance(child, str):
self.children[i] = child.strip()
elif hasattr(child, 'finalize'):
child.finalize()
@@ -88,7 +85,7 @@ class Element(object):
return not self.__eq__(element)
def _count(self, element, count=True):
- if not isinstance(element, six.string_types):
+ if not isinstance(element, str):
if self == element:
return 1
if isinstance(element, RootElement):
@@ -98,8 +95,8 @@ class Element(object):
for child in self.children:
# child is text content and element is also text content, then
# make a simple "text" in "text"
- if isinstance(child, six.string_types):
- if isinstance(element, six.string_types):
+ if isinstance(child, str):
+ if isinstance(element, str):
if count:
i += child.count(element)
elif element in child:
@@ -128,14 +125,14 @@ class Element(object):
output += ' %s' % key
if self.children:
output += '>\n'
- output += ''.join(six.text_type(c) for c in self.children)
+ output += ''.join(str(c) for c in self.children)
output += '\n%s>' % self.name
else:
output += ' />'
return output
def __repr__(self):
- return six.text_type(self)
+ return str(self)
class RootElement(Element):
@@ -143,7 +140,7 @@ class RootElement(Element):
super(RootElement, self).__init__(None, ())
def __str__(self):
- return ''.join(six.text_type(c) for c in self.children)
+ return ''.join(str(c) for c in self.children)
class Parser(HTMLParser):
@@ -232,6 +229,6 @@ def parse_html(html):
document.finalize()
# Removing ROOT element if it's not necessary
if len(document.children) == 1:
- if not isinstance(document.children[0], six.string_types):
+ if not isinstance(document.children[0], str):
document = document.children[0]
return document
diff --git a/django/test/testcases.py b/django/test/testcases.py
index 7e8cee5c0d..9d08940f5a 100644
--- a/django/test/testcases.py
+++ b/django/test/testcases.py
@@ -674,8 +674,7 @@ class SimpleTestCase(unittest.TestCase):
standardMsg = '%s != %s' % (
safe_repr(dom1, True), safe_repr(dom2, True))
diff = ('\n' + '\n'.join(difflib.ndiff(
- six.text_type(dom1).splitlines(),
- six.text_type(dom2).splitlines(),
+ str(dom1).splitlines(), str(dom2).splitlines(),
)))
standardMsg = self._truncateMessage(standardMsg, diff)
self.fail(self._formatMessage(msg, standardMsg))
@@ -712,7 +711,7 @@ class SimpleTestCase(unittest.TestCase):
data = json.loads(raw)
except ValueError:
self.fail("First argument is not valid JSON: %r" % raw)
- if isinstance(expected_data, six.string_types):
+ if isinstance(expected_data, str):
try:
expected_data = json.loads(expected_data)
except ValueError:
@@ -729,7 +728,7 @@ class SimpleTestCase(unittest.TestCase):
data = json.loads(raw)
except ValueError:
self.fail("First argument is not valid JSON: %r" % raw)
- if isinstance(expected_data, six.string_types):
+ if isinstance(expected_data, str):
try:
expected_data = json.loads(expected_data)
except ValueError:
@@ -751,10 +750,7 @@ class SimpleTestCase(unittest.TestCase):
if not result:
standardMsg = '%s != %s' % (safe_repr(xml1, True), safe_repr(xml2, True))
diff = ('\n' + '\n'.join(
- difflib.ndiff(
- six.text_type(xml1).splitlines(),
- six.text_type(xml2).splitlines(),
- )
+ difflib.ndiff(xml1.splitlines(), xml2.splitlines())
))
standardMsg = self._truncateMessage(standardMsg, diff)
self.fail(self._formatMessage(msg, standardMsg))
diff --git a/django/test/utils.py b/django/test/utils.py
index 5ed32dbab5..7395396fbb 100644
--- a/django/test/utils.py
+++ b/django/test/utils.py
@@ -61,7 +61,7 @@ class ContextList(list):
in a list of context objects.
"""
def __getitem__(self, key):
- if isinstance(key, six.string_types):
+ if isinstance(key, str):
for subcontext in self:
if key in subcontext:
return subcontext[key]
@@ -478,7 +478,7 @@ class modify_settings(override_settings):
value = list(getattr(settings, name, []))
for action, items in operations.items():
# items my be a single value or an iterable.
- if isinstance(items, six.string_types):
+ if isinstance(items, str):
items = [items]
if action == 'append':
value = value + [item for item in items if item not in value]
diff --git a/django/urls/base.py b/django/urls/base.py
index 8e30acb860..c09eeed8f6 100644
--- a/django/urls/base.py
+++ b/django/urls/base.py
@@ -1,6 +1,5 @@
from threading import local
-from django.utils import six
from django.utils.encoding import force_text, iri_to_uri
from django.utils.functional import lazy
from django.utils.six.moves.urllib.parse import urlsplit, urlunsplit
@@ -34,7 +33,7 @@ def reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None):
prefix = get_script_prefix()
- if not isinstance(viewname, six.string_types):
+ if not isinstance(viewname, str):
view = viewname
else:
parts = viewname.split(':')
@@ -89,7 +88,7 @@ def reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None):
return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
-reverse_lazy = lazy(reverse, six.text_type)
+reverse_lazy = lazy(reverse, str)
def clear_url_caches():
diff --git a/django/urls/resolvers.py b/django/urls/resolvers.py
index 4e8bded3db..cf2fe0ecec 100644
--- a/django/urls/resolvers.py
+++ b/django/urls/resolvers.py
@@ -14,7 +14,7 @@ from django.conf import settings
from django.core.checks import Warning
from django.core.checks.urls import check_resolver
from django.core.exceptions import ImproperlyConfigured
-from django.utils import lru_cache, six
+from django.utils import lru_cache
from django.utils.datastructures import MultiValueDict
from django.utils.encoding import force_str, force_text
from django.utils.functional import cached_property
@@ -87,7 +87,7 @@ class LocaleRegexDescriptor(object):
# As a performance optimization, if the given regex string is a regular
# string (not a lazily-translated string proxy), compile it once and
# avoid per-language compilation.
- if isinstance(instance._regex, six.string_types):
+ if isinstance(instance._regex, str):
instance.__dict__['regex'] = self._compile(instance._regex)
return instance.__dict__['regex']
language_code = get_language()
@@ -103,8 +103,7 @@ class LocaleRegexDescriptor(object):
return re.compile(regex, re.UNICODE)
except re.error as e:
raise ImproperlyConfigured(
- '"%s" is not a valid regular expression: %s' %
- (regex, six.text_type(e))
+ '"%s" is not a valid regular expression: %s' % (regex, e)
)
@@ -388,7 +387,7 @@ class RegexURLResolver(LocaleRegexProvider):
@cached_property
def urlconf_module(self):
- if isinstance(self.urlconf_name, six.string_types):
+ if isinstance(self.urlconf_name, str):
return import_module(self.urlconf_name)
else:
return self.urlconf_name
diff --git a/django/urls/utils.py b/django/urls/utils.py
index 8558b82bba..3cf5439e77 100644
--- a/django/urls/utils.py
+++ b/django/urls/utils.py
@@ -1,7 +1,7 @@
from importlib import import_module
from django.core.exceptions import ViewDoesNotExist
-from django.utils import lru_cache, six
+from django.utils import lru_cache
from django.utils.module_loading import module_has_submodule
@@ -17,7 +17,7 @@ def get_callable(lookup_view):
if callable(lookup_view):
return lookup_view
- if not isinstance(lookup_view, six.string_types):
+ if not isinstance(lookup_view, str):
raise ViewDoesNotExist("'%s' is not a callable or a dot-notation path" % lookup_view)
mod_name, func_name = get_mod_func(lookup_view)
diff --git a/django/utils/archive.py b/django/utils/archive.py
index 57e87658a6..456145a520 100644
--- a/django/utils/archive.py
+++ b/django/utils/archive.py
@@ -27,8 +27,6 @@ import stat
import tarfile
import zipfile
-from django.utils import six
-
class ArchiveException(Exception):
"""
@@ -61,7 +59,7 @@ class Archive(object):
@staticmethod
def _archive_cls(file):
cls = None
- if isinstance(file, six.string_types):
+ if isinstance(file, str):
filename = file
else:
try:
diff --git a/django/utils/dateformat.py b/django/utils/dateformat.py
index 861bf8f923..ded952df99 100644
--- a/django/utils/dateformat.py
+++ b/django/utils/dateformat.py
@@ -15,7 +15,6 @@ import datetime
import re
import time
-from django.utils import six
from django.utils.dates import (
MONTHS, MONTHS_3, MONTHS_ALT, MONTHS_AP, WEEKDAYS, WEEKDAYS_ABBR,
)
@@ -182,7 +181,7 @@ class TimeFormat(Formatter):
pass
if name is None:
name = self.format('O')
- return six.text_type(name)
+ return str(name)
def u(self):
"Microseconds; i.e. '000000' to '999999'"
@@ -350,7 +349,7 @@ class DateFormat(TimeFormat):
def y(self):
"Year, 2 digits; e.g. '99'"
- return six.text_type(self.data.year)[2:]
+ return str(self.data.year)[2:]
def Y(self):
"Year, 4 digits; e.g. '1999'"
diff --git a/django/utils/encoding.py b/django/utils/encoding.py
index f0627f5d39..abd17526c6 100644
--- a/django/utils/encoding.py
+++ b/django/utils/encoding.py
@@ -36,8 +36,8 @@ def smart_text(s, encoding='utf-8', strings_only=False, errors='strict'):
return force_text(s, encoding, strings_only, errors)
-_PROTECTED_TYPES = six.integer_types + (
- type(None), float, Decimal, datetime.datetime, datetime.date, datetime.time
+_PROTECTED_TYPES = (
+ type(None), int, float, Decimal, datetime.datetime, datetime.date, datetime.time,
)
@@ -58,18 +58,18 @@ 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 for performance reasons.
- if issubclass(type(s), six.text_type):
+ if issubclass(type(s), str):
return s
if strings_only and is_protected_type(s):
return s
try:
- if not issubclass(type(s), six.string_types):
+ if not issubclass(type(s), str):
if isinstance(s, bytes):
- s = six.text_type(s, encoding, errors)
+ s = str(s, encoding, errors)
else:
- s = six.text_type(s)
+ s = str(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)
@@ -114,13 +114,13 @@ def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
return s.decode('utf-8', errors).encode(encoding, errors)
if strings_only and is_protected_type(s):
return s
- if isinstance(s, six.memoryview):
+ if isinstance(s, memoryview):
return bytes(s)
if isinstance(s, Promise):
- return six.text_type(s).encode(encoding, errors)
- if not isinstance(s, six.string_types):
+ return str(s).encode(encoding, errors)
+ if not isinstance(s, str):
try:
- return six.text_type(s).encode(encoding)
+ return str(s).encode(encoding)
except UnicodeEncodeError:
if isinstance(s, Exception):
# An Exception subclass containing non-ASCII data that doesn't
@@ -128,7 +128,7 @@ def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
# further exception.
return b' '.join(force_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)
diff --git a/django/utils/formats.py b/django/utils/formats.py
index e381c1fbca..894003b4fa 100644
--- a/django/utils/formats.py
+++ b/django/utils/formats.py
@@ -4,7 +4,7 @@ import unicodedata
from importlib import import_module
from django.conf import settings
-from django.utils import dateformat, datetime_safe, numberformat, six
+from django.utils import dateformat, datetime_safe, numberformat
from django.utils.encoding import force_str
from django.utils.functional import lazy
from django.utils.safestring import mark_safe
@@ -71,7 +71,7 @@ def iter_format_modules(lang, format_module_path=None):
format_locations = []
if format_module_path:
- if isinstance(format_module_path, six.string_types):
+ if isinstance(format_module_path, str):
format_module_path = [format_module_path]
for path in format_module_path:
format_locations.append(path + '.%s')
@@ -148,7 +148,7 @@ def get_format(format_type, lang=None, use_l10n=None):
return val
-get_format_lazy = lazy(get_format, six.text_type, list, tuple)
+get_format_lazy = lazy(get_format, str, list, tuple)
def date_format(value, format=None, use_l10n=None):
@@ -201,11 +201,11 @@ def localize(value, use_l10n=None):
If use_l10n is provided and is not None, that will force the value to
be localized (or not), overriding the value of settings.USE_L10N.
"""
- if isinstance(value, six.string_types): # Handle strings first for performance reasons.
+ if isinstance(value, str): # Handle strings first for performance reasons.
return value
elif isinstance(value, bool): # Make sure booleans don't get treated as numbers
- return mark_safe(six.text_type(value))
- elif isinstance(value, (decimal.Decimal, float) + six.integer_types):
+ return mark_safe(str(value))
+ elif isinstance(value, (decimal.Decimal, float, int)):
return number_format(value, use_l10n=use_l10n)
elif isinstance(value, datetime.datetime):
return date_format(value, 'DATETIME_FORMAT', use_l10n=use_l10n)
@@ -221,11 +221,11 @@ def localize_input(value, default=None):
Checks if an input value is a localizable type and returns it
formatted with the appropriate formatting string of the current locale.
"""
- if isinstance(value, six.string_types): # Handle strings first for performance reasons.
+ if isinstance(value, str): # Handle strings first for performance reasons.
return value
elif isinstance(value, bool): # Don't treat booleans as numbers.
- return six.text_type(value)
- elif isinstance(value, (decimal.Decimal, float) + six.integer_types):
+ return str(value)
+ elif isinstance(value, (decimal.Decimal, float, int)):
return number_format(value)
elif isinstance(value, datetime.datetime):
value = datetime_safe.new_datetime(value)
@@ -246,7 +246,7 @@ def sanitize_separators(value):
Sanitizes a value according to the current decimal and
thousand separator setting. Used with form field input.
"""
- if settings.USE_L10N and isinstance(value, six.string_types):
+ if settings.USE_L10N and isinstance(value, str):
parts = []
decimal_separator = get_format('DECIMAL_SEPARATOR')
if decimal_separator in value:
diff --git a/django/utils/functional.py b/django/utils/functional.py
index 933085391d..3e35582cbf 100644
--- a/django/utils/functional.py
+++ b/django/utils/functional.py
@@ -88,7 +88,7 @@ def lazy(func, *resultclasses):
meth = cls.__promise__(method_name)
setattr(cls, method_name, 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:
@@ -148,7 +148,7 @@ def lazy(func, *resultclasses):
def __mod__(self, rhs):
if self._delegate_text:
- return six.text_type(self) % rhs
+ return str(self) % rhs
return self.__cast() % rhs
def __deepcopy__(self, memo):
@@ -175,7 +175,7 @@ def lazystr(text):
Shortcut for the common case of a lazy callable that returns str.
"""
from django.utils.encoding import force_text # Avoid circular import
- return lazy(force_text, six.text_type)(text)
+ return lazy(force_text, str)(text)
def keep_lazy(*resultclasses):
@@ -207,7 +207,7 @@ def keep_lazy_text(func):
"""
A decorator for functions that accept lazy arguments and return text.
"""
- return keep_lazy(six.text_type)(func)
+ return keep_lazy(str)(func)
empty = object()
diff --git a/django/utils/html.py b/django/utils/html.py
index 36b5d53283..430350fed6 100644
--- a/django/utils/html.py
+++ b/django/utils/html.py
@@ -33,7 +33,7 @@ simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net
simple_email_re = re.compile(r'^\S+@\S+\.\S+$')
-@keep_lazy(six.text_type, SafeText)
+@keep_lazy(str, SafeText)
def escape(text):
"""
Returns the given text with ampersands, quotes and angle brackets encoded
@@ -67,7 +67,7 @@ _js_escapes = {
_js_escapes.update((ord('%c' % z), '\\u%04X' % z) for z in range(32))
-@keep_lazy(six.text_type, SafeText)
+@keep_lazy(str, SafeText)
def escapejs(value):
"""Hex encodes characters for use in JavaScript strings."""
return mark_safe(force_text(value).translate(_js_escapes))
diff --git a/django/utils/numberformat.py b/django/utils/numberformat.py
index d4c9ad74a5..1931015e7b 100644
--- a/django/utils/numberformat.py
+++ b/django/utils/numberformat.py
@@ -1,7 +1,6 @@
from decimal import Decimal
from django.conf import settings
-from django.utils import six
from django.utils.safestring import mark_safe
@@ -24,13 +23,13 @@ def format(number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep='',
use_grouping = use_grouping and grouping != 0
# Make the common case fast
if isinstance(number, int) and not use_grouping and not decimal_pos:
- return mark_safe(six.text_type(number))
+ return mark_safe(str(number))
# sign
sign = ''
if isinstance(number, Decimal):
str_number = '{:f}'.format(number)
else:
- str_number = six.text_type(number)
+ str_number = str(number)
if str_number[0] == '-':
sign = '-'
str_number = str_number[1:]
diff --git a/django/utils/regex_helper.py b/django/utils/regex_helper.py
index 41f2459491..bc4a09b359 100644
--- a/django/utils/regex_helper.py
+++ b/django/utils/regex_helper.py
@@ -7,7 +7,6 @@ should be good enough for a large class of URLS, however.
"""
import warnings
-from django.utils import six
from django.utils.deprecation import RemovedInDjango21Warning
from django.utils.six.moves import zip
@@ -318,7 +317,7 @@ def flatten_result(source):
result_args = [[]]
pos = last = 0
for pos, elt in enumerate(source):
- if isinstance(elt, six.string_types):
+ if isinstance(elt, str):
continue
piece = ''.join(source[last:pos])
if isinstance(elt, Group):
diff --git a/django/utils/safestring.py b/django/utils/safestring.py
index 3f4b3d48fd..609f8f45ac 100644
--- a/django/utils/safestring.py
+++ b/django/utils/safestring.py
@@ -5,7 +5,6 @@ that the producer of the string has already turned characters that should not
be interpreted by the HTML engine (e.g. '<') into the appropriate entities.
"""
-from django.utils import six
from django.utils.functional import Promise, curry, wraps
@@ -52,10 +51,10 @@ class SafeBytes(bytes, SafeData):
decode = curry(_proxy_method, method=bytes.decode)
-class SafeText(six.text_type, SafeData):
+class SafeText(str, SafeData):
"""
- A unicode (Python 2) / str (Python 3) subclass that has been specifically
- marked as "safe" for HTML output purposes.
+ A str subclass that has been specifically marked as "safe" for HTML output
+ purposes.
"""
def __add__(self, rhs):
"""
@@ -80,7 +79,7 @@ class SafeText(six.text_type, SafeData):
else:
return SafeText(data)
- encode = curry(_proxy_method, method=six.text_type.encode)
+ encode = curry(_proxy_method, method=str.encode)
SafeString = SafeText
@@ -106,7 +105,7 @@ def mark_safe(s):
return s
if isinstance(s, bytes) or (isinstance(s, Promise) and s._delegate_bytes):
return SafeBytes(s)
- if isinstance(s, (six.text_type, Promise)):
+ if isinstance(s, (str, Promise)):
return SafeText(s)
if callable(s):
return _safety_decorator(mark_safe, s)
diff --git a/django/utils/text.py b/django/utils/text.py
index fc8677cf4e..15a9b6160a 100644
--- a/django/utils/text.py
+++ b/django/utils/text.py
@@ -408,7 +408,7 @@ def unescape_string_literal(s):
return s[1:-1].replace(r'\%s' % quote, quote).replace(r'\\', '\\')
-@keep_lazy(six.text_type, SafeText)
+@keep_lazy(str, SafeText)
def slugify(value, allow_unicode=False):
"""
Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens.
@@ -441,4 +441,4 @@ def _format_lazy(format_string, *args, **kwargs):
return format_string.format(*args, **kwargs)
-format_lazy = lazy(_format_lazy, six.text_type)
+format_lazy = lazy(_format_lazy, str)
diff --git a/django/utils/timezone.py b/django/utils/timezone.py
index 090750793a..992e80086a 100644
--- a/django/utils/timezone.py
+++ b/django/utils/timezone.py
@@ -8,7 +8,7 @@ from threading import local
import pytz
from django.conf import settings
-from django.utils import lru_cache, six
+from django.utils import lru_cache
from django.utils.decorators import ContextDecorator
__all__ = [
@@ -130,7 +130,7 @@ def activate(timezone):
"""
if isinstance(timezone, tzinfo):
_active.value = timezone
- elif isinstance(timezone, six.string_types):
+ elif isinstance(timezone, str):
_active.value = pytz.timezone(timezone)
else:
raise ValueError("Invalid timezone: %r" % timezone)
diff --git a/django/utils/translation/__init__.py b/django/utils/translation/__init__.py
index fd02fa16a3..345015d994 100644
--- a/django/utils/translation/__init__.py
+++ b/django/utils/translation/__init__.py
@@ -4,7 +4,6 @@ Internationalization support.
import re
import warnings
-from django.utils import six
from django.utils.decorators import ContextDecorator
from django.utils.deprecation import RemovedInDjango21Warning
from django.utils.encoding import force_text
@@ -100,12 +99,12 @@ def npgettext(context, singular, plural, number):
gettext_lazy = lazy(gettext, str)
-ugettext_lazy = lazy(ugettext, six.text_type)
-pgettext_lazy = lazy(pgettext, six.text_type)
+ugettext_lazy = lazy(ugettext, str)
+pgettext_lazy = lazy(pgettext, str)
def lazy_number(func, resultclass, number=None, **kwargs):
- if isinstance(number, six.integer_types):
+ if isinstance(number, int):
kwargs['number'] = number
proxy = lazy(func, resultclass)(**kwargs)
else:
@@ -153,11 +152,11 @@ def ngettext_lazy(singular, plural, number=None):
def ungettext_lazy(singular, plural, number=None):
- return lazy_number(ungettext, six.text_type, singular=singular, plural=plural, number=number)
+ return lazy_number(ungettext, str, singular=singular, plural=plural, number=number)
def npgettext_lazy(context, singular, plural, number=None):
- return lazy_number(npgettext, six.text_type, context=context, singular=singular, plural=plural, number=number)
+ return lazy_number(npgettext, str, context=context, singular=singular, plural=plural, number=number)
def activate(language):
@@ -234,7 +233,7 @@ def _string_concat(*strings):
return ''.join(force_text(s) for s in strings)
-string_concat = lazy(_string_concat, six.text_type)
+string_concat = lazy(_string_concat, str)
def get_language_info(lang_code):
diff --git a/django/views/debug.py b/django/views/debug.py
index 2390995b56..de8c4319bf 100644
--- a/django/views/debug.py
+++ b/django/views/debug.py
@@ -7,7 +7,7 @@ from django.http import HttpResponse, HttpResponseNotFound
from django.template import Context, Engine, TemplateDoesNotExist
from django.template.defaultfilters import force_escape, pprint
from django.urls import Resolver404, resolve
-from django.utils import lru_cache, six, timezone
+from django.utils import lru_cache, timezone
from django.utils.datastructures import MultiValueDict
from django.utils.encoding import force_bytes, force_text
from django.utils.module_loading import import_string
@@ -246,7 +246,7 @@ class ExceptionReporter(object):
self.postmortem = None
# Handle deprecated string exceptions
- if isinstance(self.exc_type, six.string_types):
+ if isinstance(self.exc_type, str):
self.exc_value = Exception('Deprecated String Exception: %r' % self.exc_type)
self.exc_type = type(self.exc_value)
@@ -263,7 +263,7 @@ class ExceptionReporter(object):
for k, v in frame['vars']:
v = pprint(v)
# The force_escape filter assume unicode, make sure that works
- if isinstance(v, six.binary_type):
+ if isinstance(v, bytes):
v = v.decode('utf-8', 'replace') # don't choke on non-utf-8 input
# Trim large blobs of data
if len(v) > 4096:
@@ -361,7 +361,7 @@ class ExceptionReporter(object):
# If we just read the source from a file, or if the loader did not
# apply tokenize.detect_encoding to decode the source into a Unicode
# string, then we should do that ourselves.
- if isinstance(source[0], six.binary_type):
+ if isinstance(source[0], bytes):
encoding = 'ascii'
for line in source[:2]:
# File coding may be specified. Match pattern from PEP-263
@@ -370,7 +370,7 @@ class ExceptionReporter(object):
if match:
encoding = match.group(1).decode('ascii')
break
- source = [six.text_type(sline, encoding, 'replace') for sline in source]
+ source = [str(sline, encoding, 'replace') for sline in source]
lower_bound = max(0, lineno - context_lines)
upper_bound = lineno + context_lines
diff --git a/django/views/defaults.py b/django/views/defaults.py
index 348837ed99..12218e8048 100644
--- a/django/views/defaults.py
+++ b/django/views/defaults.py
@@ -1,6 +1,5 @@
from django import http
from django.template import Context, Engine, TemplateDoesNotExist, loader
-from django.utils import six
from django.utils.encoding import force_text
from django.views.decorators.csrf import requires_csrf_token
@@ -34,7 +33,7 @@ def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME):
except (AttributeError, IndexError):
pass
else:
- if isinstance(message, six.text_type):
+ if isinstance(message, str):
exception_repr = message
context = {
'request_path': request.path,
diff --git a/django/views/generic/list.py b/django/views/generic/list.py
index 951c11f5a5..e37f4f1ac0 100644
--- a/django/views/generic/list.py
+++ b/django/views/generic/list.py
@@ -2,7 +2,6 @@ from django.core.exceptions import ImproperlyConfigured
from django.core.paginator import InvalidPage, Paginator
from django.db.models.query import QuerySet
from django.http import Http404
-from django.utils import six
from django.utils.translation import ugettext as _
from django.views.generic.base import ContextMixin, TemplateResponseMixin, View
@@ -44,7 +43,7 @@ class MultipleObjectMixin(ContextMixin):
)
ordering = self.get_ordering()
if ordering:
- if isinstance(ordering, six.string_types):
+ if isinstance(ordering, str):
ordering = (ordering,)
queryset = queryset.order_by(*ordering)
diff --git a/django/views/i18n.py b/django/views/i18n.py
index ba8fce67e7..1fc5461b1c 100644
--- a/django/views/i18n.py
+++ b/django/views/i18n.py
@@ -75,7 +75,7 @@ def get_formats():
result[attr] = get_format(attr)
formats = {}
for k, v in result.items():
- if isinstance(v, (six.string_types, int)):
+ if isinstance(v, (int, str)):
formats[k] = force_text(v)
elif isinstance(v, (tuple, list)):
formats[k] = [force_text(value) for value in v]
@@ -268,7 +268,7 @@ class JavaScriptCatalog(View):
for key, value in itertools.chain(six.iteritems(trans_cat), six.iteritems(trans_fallback_cat)):
if key == '' or key in catalog:
continue
- if isinstance(key, six.string_types):
+ if isinstance(key, str):
catalog[key] = value
elif isinstance(key, tuple):
msgid = key[0]
diff --git a/tests/admin_changelist/tests.py b/tests/admin_changelist/tests.py
index 48e7460314..33bf85a9ff 100644
--- a/tests/admin_changelist/tests.py
+++ b/tests/admin_changelist/tests.py
@@ -12,7 +12,7 @@ from django.template import Context, Template
from django.test import TestCase, override_settings
from django.test.client import RequestFactory
from django.urls import reverse
-from django.utils import formats, six
+from django.utils import formats
from .admin import (
BandAdmin, ChildAdmin, ChordsBandAdmin, ConcertAdmin,
@@ -466,7 +466,7 @@ class ChangeListTests(TestCase):
event = Event.objects.create(date=datetime.date.today())
response = self.client.get(reverse('admin:admin_changelist_event_changelist'))
self.assertContains(response, formats.localize(event.date))
- self.assertNotContains(response, six.text_type(event.date))
+ self.assertNotContains(response, str(event.date))
def test_dynamic_list_display(self):
"""
@@ -581,9 +581,9 @@ class ChangeListTests(TestCase):
request = self._mocked_authenticated_request('/swallow/', superuser)
response = model_admin.changelist_view(request)
# just want to ensure it doesn't blow up during rendering
- self.assertContains(response, six.text_type(swallow.origin))
- self.assertContains(response, six.text_type(swallow.load))
- self.assertContains(response, six.text_type(swallow.speed))
+ self.assertContains(response, str(swallow.origin))
+ self.assertContains(response, str(swallow.load))
+ self.assertContains(response, str(swallow.speed))
# Reverse one-to-one relations should work.
self.assertContains(response, '
-
')
self.assertContains(response, '
%s
' % swallow_o2o)
diff --git a/tests/admin_utils/models.py b/tests/admin_utils/models.py
index 1af2f09411..cf90421e9a 100644
--- a/tests/admin_utils/models.py
+++ b/tests/admin_utils/models.py
@@ -1,5 +1,4 @@
from django.db import models
-from django.utils import six
from django.utils.translation import ugettext_lazy as _
@@ -37,7 +36,7 @@ class Count(models.Model):
parent = models.ForeignKey('self', models.CASCADE, null=True)
def __str__(self):
- return six.text_type(self.num)
+ return str(self.num)
class Event(models.Model):
diff --git a/tests/admin_utils/test_logentry.py b/tests/admin_utils/test_logentry.py
index 89b25f462b..c2eee96f48 100644
--- a/tests/admin_utils/test_logentry.py
+++ b/tests/admin_utils/test_logentry.py
@@ -7,7 +7,7 @@ from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.test import TestCase, override_settings
from django.urls import reverse
-from django.utils import six, translation
+from django.utils import translation
from django.utils.encoding import force_bytes
from django.utils.html import escape
@@ -164,17 +164,17 @@ class LogEntryTests(TestCase):
log_entry = LogEntry()
log_entry.action_flag = ADDITION
- self.assertTrue(six.text_type(log_entry).startswith('Added '))
+ self.assertTrue(str(log_entry).startswith('Added '))
log_entry.action_flag = CHANGE
- self.assertTrue(six.text_type(log_entry).startswith('Changed '))
+ self.assertTrue(str(log_entry).startswith('Changed '))
log_entry.action_flag = DELETION
- self.assertTrue(six.text_type(log_entry).startswith('Deleted '))
+ self.assertTrue(str(log_entry).startswith('Deleted '))
# Make sure custom action_flags works
log_entry.action_flag = 4
- self.assertEqual(six.text_type(log_entry), 'LogEntry Object')
+ self.assertEqual(str(log_entry), 'LogEntry Object')
def test_log_action(self):
content_type_pk = ContentType.objects.get_for_model(Article).pk
diff --git a/tests/admin_views/tests.py b/tests/admin_views/tests.py
index 2353a9ee7a..fb404e5fd2 100644
--- a/tests/admin_views/tests.py
+++ b/tests/admin_views/tests.py
@@ -29,7 +29,7 @@ from django.test import (
)
from django.test.utils import override_script_prefix, patch_logger
from django.urls import NoReverseMatch, resolve, reverse
-from django.utils import formats, six, translation
+from django.utils import formats, translation
from django.utils._os import upath
from django.utils.cache import get_max_age
from django.utils.deprecation import RemovedInDjango21Warning
@@ -3759,7 +3759,7 @@ class AdminCustomQuerysetTest(TestCase):
self.assertEqual(response.status_code, 200)
self.assertEqual(ShortMessage.objects.count(), 1)
# Message should contain non-ugly model verbose name. The ugly(!)
- # instance representation is set by six.text_type()
+ # instance representation is set by __str__().
self.assertContains(
response,
'