summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorClaude Paroz <claude@2xlibre.net>2016-12-29 16:27:49 +0100
committerClaude Paroz <claude@2xlibre.net>2017-01-18 20:18:46 +0100
commit7b2f2e74adb36a4334e83130f6abc2f79d395235 (patch)
tree313387ba6a6f1311b43cf5fb4f2576d2d6c4f805
parentf6acd1d271122d66de8061e75ae26137ddf02658 (diff)
Refs #23919 -- Removed six.<various>_types usage
Thanks Tim Graham and Simon Charette for the reviews.
-rw-r--r--django/conf/urls/__init__.py3
-rw-r--r--django/contrib/admin/helpers.py5
-rw-r--r--django/contrib/admin/options.py10
-rw-r--r--django/contrib/admin/utils.py8
-rw-r--r--django/contrib/admin/widgets.py3
-rw-r--r--django/contrib/auth/decorators.py3
-rw-r--r--django/contrib/auth/mixins.py3
-rw-r--r--django/contrib/auth/models.py9
-rw-r--r--django/contrib/auth/password_validation.py5
-rw-r--r--django/contrib/auth/tokens.py6
-rw-r--r--django/contrib/gis/admin/widgets.py4
-rw-r--r--django/contrib/gis/db/backends/base/models.py3
-rw-r--r--django/contrib/gis/db/backends/oracle/operations.py3
-rw-r--r--django/contrib/gis/db/backends/postgis/operations.py5
-rw-r--r--django/contrib/gis/db/backends/spatialite/introspection.py5
-rw-r--r--django/contrib/gis/db/models/fields.py3
-rw-r--r--django/contrib/gis/db/models/functions.py13
-rw-r--r--django/contrib/gis/db/models/lookups.py3
-rw-r--r--django/contrib/gis/db/models/proxy.py5
-rw-r--r--django/contrib/gis/forms/widgets.py4
-rw-r--r--django/contrib/gis/gdal/datasource.py5
-rw-r--r--django/contrib/gis/gdal/driver.py3
-rw-r--r--django/contrib/gis/gdal/feature.py3
-rw-r--r--django/contrib/gis/gdal/geometries.py10
-rw-r--r--django/contrib/gis/gdal/geomtype.py5
-rw-r--r--django/contrib/gis/gdal/layer.py3
-rw-r--r--django/contrib/gis/gdal/prototypes/errcheck.py7
-rw-r--r--django/contrib/gis/gdal/raster/source.py7
-rw-r--r--django/contrib/gis/gdal/srs.py7
-rw-r--r--django/contrib/gis/geoip2/base.py5
-rw-r--r--django/contrib/gis/geos/factory.py2
-rw-r--r--django/contrib/gis/geos/geometry.py8
-rw-r--r--django/contrib/gis/geos/mutable_list.py7
-rw-r--r--django/contrib/gis/geos/point.py5
-rw-r--r--django/contrib/gis/geos/polygon.py3
-rw-r--r--django/contrib/gis/geos/prototypes/io.py4
-rw-r--r--django/contrib/gis/measure.py4
-rw-r--r--django/contrib/gis/utils/layermapping.py8
-rw-r--r--django/contrib/gis/utils/ogrinspect.py5
-rw-r--r--django/contrib/messages/storage/session.py3
-rw-r--r--django/contrib/postgres/fields/array.py3
-rw-r--r--django/contrib/postgres/fields/hstore.py5
-rw-r--r--django/contrib/postgres/fields/ranges.py3
-rw-r--r--django/contrib/postgres/forms/array.py3
-rw-r--r--django/contrib/postgres/forms/hstore.py3
-rw-r--r--django/contrib/postgres/forms/jsonb.py7
-rw-r--r--django/core/cache/backends/memcached.py3
-rw-r--r--django/core/checks/templates.py3
-rw-r--r--django/core/checks/urls.py3
-rw-r--r--django/core/files/base.py9
-rw-r--r--django/core/handlers/base.py3
-rw-r--r--django/core/mail/backends/filebased.py3
-rw-r--r--django/core/mail/message.py10
-rw-r--r--django/core/management/utils.py2
-rw-r--r--django/core/paginator.py2
-rw-r--r--django/core/serializers/base.py2
-rw-r--r--django/core/serializers/json.py8
-rw-r--r--django/core/serializers/python.py4
-rw-r--r--django/core/serializers/pyyaml.py2
-rw-r--r--django/core/validators.py5
-rw-r--r--django/db/backends/base/operations.py18
-rw-r--r--django/db/backends/base/schema.py6
-rw-r--r--django/db/backends/mysql/base.py2
-rw-r--r--django/db/backends/mysql/operations.py6
-rw-r--r--django/db/backends/oracle/base.py15
-rw-r--r--django/db/backends/oracle/operations.py4
-rw-r--r--django/db/backends/oracle/schema.py7
-rw-r--r--django/db/backends/sqlite3/base.py6
-rw-r--r--django/db/backends/sqlite3/operations.py6
-rw-r--r--django/db/backends/sqlite3/schema.py11
-rw-r--r--django/db/migrations/autodetector.py5
-rw-r--r--django/db/migrations/operations/models.py7
-rw-r--r--django/db/migrations/serializer.py6
-rw-r--r--django/db/migrations/state.py15
-rw-r--r--django/db/models/base.py16
-rw-r--r--django/db/models/expressions.py3
-rw-r--r--django/db/models/fields/__init__.py29
-rw-r--r--django/db/models/fields/files.py7
-rw-r--r--django/db/models/fields/related.py36
-rw-r--r--django/db/models/options.py4
-rw-r--r--django/db/models/query.py2
-rw-r--r--django/db/models/signals.py3
-rw-r--r--django/db/models/utils.py5
-rw-r--r--django/db/utils.py2
-rw-r--r--django/forms/boundfield.py3
-rw-r--r--django/forms/fields.py8
-rw-r--r--django/forms/forms.py4
-rw-r--r--django/forms/formsets.py7
-rw-r--r--django/forms/models.py8
-rw-r--r--django/forms/widgets.py9
-rw-r--r--django/http/multipartparser.py2
-rw-r--r--django/http/request.py2
-rw-r--r--django/http/response.py10
-rw-r--r--django/shortcuts.py3
-rw-r--r--django/template/base.py3
-rw-r--r--django/template/defaultfilters.py10
-rw-r--r--django/template/engine.py4
-rw-r--r--django/template/library.py3
-rw-r--r--django/template/loader.py4
-rw-r--r--django/template/response.py3
-rw-r--r--django/templatetags/i18n.py2
-rw-r--r--django/templatetags/tz.py4
-rw-r--r--django/test/client.py4
-rw-r--r--django/test/html.py27
-rw-r--r--django/test/testcases.py12
-rw-r--r--django/test/utils.py4
-rw-r--r--django/urls/base.py5
-rw-r--r--django/urls/resolvers.py9
-rw-r--r--django/urls/utils.py4
-rw-r--r--django/utils/archive.py4
-rw-r--r--django/utils/dateformat.py5
-rw-r--r--django/utils/encoding.py24
-rw-r--r--django/utils/formats.py20
-rw-r--r--django/utils/functional.py8
-rw-r--r--django/utils/html.py4
-rw-r--r--django/utils/numberformat.py5
-rw-r--r--django/utils/regex_helper.py3
-rw-r--r--django/utils/safestring.py11
-rw-r--r--django/utils/text.py4
-rw-r--r--django/utils/timezone.py4
-rw-r--r--django/utils/translation/__init__.py13
-rw-r--r--django/views/debug.py10
-rw-r--r--django/views/defaults.py3
-rw-r--r--django/views/generic/list.py3
-rw-r--r--django/views/i18n.py4
-rw-r--r--tests/admin_changelist/tests.py10
-rw-r--r--tests/admin_utils/models.py3
-rw-r--r--tests/admin_utils/test_logentry.py10
-rw-r--r--tests/admin_views/tests.py10
-rw-r--r--tests/admin_widgets/tests.py4
-rw-r--r--tests/auth_tests/test_management.py2
-rw-r--r--tests/backends/tests.py5
-rw-r--r--tests/contenttypes_tests/test_models.py3
-rw-r--r--tests/csrf_tests/tests.py3
-rw-r--r--tests/custom_columns/tests.py9
-rw-r--r--tests/custom_managers/tests.py9
-rw-r--r--tests/custom_pk/fields.py5
-rw-r--r--tests/custom_pk/tests.py17
-rw-r--r--tests/datatypes/tests.py3
-rw-r--r--tests/expressions/tests.py3
-rw-r--r--tests/expressions_case/tests.py7
-rw-r--r--tests/field_deconstruction/tests.py2
-rw-r--r--tests/field_defaults/tests.py3
-rw-r--r--tests/file_uploads/views.py3
-rw-r--r--tests/files/tests.py7
-rw-r--r--tests/fixtures_regress/models.py3
-rw-r--r--tests/forms_tests/field_tests/test_filepathfield.py3
-rw-r--r--tests/forms_tests/field_tests/test_typedchoicefield.py3
-rw-r--r--tests/forms_tests/tests/test_utils.py3
-rw-r--r--tests/forms_tests/tests/tests.py3
-rw-r--r--tests/gis_tests/geoadmin/tests.py2
-rw-r--r--tests/gis_tests/geoapp/test_functions.py3
-rw-r--r--tests/gis_tests/geos_tests/test_geos.py13
-rw-r--r--tests/gis_tests/geos_tests/test_io.py3
-rw-r--r--tests/gis_tests/geos_tests/test_mutable_list.py3
-rw-r--r--tests/gis_tests/test_geoforms.py2
-rw-r--r--tests/gis_tests/test_geoip2.py3
-rw-r--r--tests/handlers/tests.py3
-rw-r--r--tests/httpwrappers/tests.py7
-rw-r--r--tests/i18n/contenttypes/tests.py6
-rw-r--r--tests/i18n/test_extraction.py3
-rw-r--r--tests/i18n/tests.py6
-rw-r--r--tests/inline_formsets/tests.py5
-rw-r--r--tests/lookup/models.py3
-rw-r--r--tests/m2m_and_m2o/models.py3
-rw-r--r--tests/m2m_intermediary/tests.py5
-rw-r--r--tests/mail/tests.py4
-rw-r--r--tests/migrations/test_state.py9
-rw-r--r--tests/migrations/test_writer.py2
-rw-r--r--tests/model_fields/test_foreignkey.py3
-rw-r--r--tests/model_fields/test_integerfield.py7
-rw-r--r--tests/model_fields/test_promises.py55
-rw-r--r--tests/model_forms/models.py3
-rw-r--r--tests/model_forms/tests.py34
-rw-r--r--tests/model_formsets/models.py3
-rw-r--r--tests/model_formsets/tests.py25
-rw-r--r--tests/model_formsets_regress/tests.py15
-rw-r--r--tests/model_inheritance/tests.py5
-rw-r--r--tests/model_regress/tests.py6
-rw-r--r--tests/order_with_respect_to/models.py3
-rw-r--r--tests/pagination/tests.py4
-rw-r--r--tests/prefetch_related/tests.py39
-rw-r--r--tests/queries/models.py3
-rw-r--r--tests/redirects_tests/tests.py3
-rw-r--r--tests/resolve_url/tests.py3
-rwxr-xr-xtests/runtests.py7
-rw-r--r--tests/save_delete_hooks/tests.py3
-rw-r--r--tests/select_related_regress/tests.py5
-rw-r--r--tests/serializers/models/base.py3
-rw-r--r--tests/serializers/test_xml.py3
-rw-r--r--tests/serializers/test_yaml.py3
-rw-r--r--tests/servers/tests.py3
-rw-r--r--tests/signals/tests.py3
-rw-r--r--tests/staticfiles_tests/cases.py5
-rw-r--r--tests/staticfiles_tests/test_management.py6
-rw-r--r--tests/staticfiles_tests/test_storage.py2
-rw-r--r--tests/template_tests/filter_tests/test_escape.py3
-rw-r--r--tests/template_tests/filter_tests/test_escapejs.py3
-rw-r--r--tests/template_tests/filter_tests/test_floatformat.py7
-rw-r--r--tests/template_tests/filter_tests/test_linebreaks.py3
-rw-r--r--tests/template_tests/filter_tests/test_slugify.py3
-rw-r--r--tests/template_tests/filter_tests/test_urlize.py3
-rw-r--r--tests/template_tests/templatetags/custom.py6
-rw-r--r--tests/template_tests/templatetags/inclusion.py10
-rw-r--r--tests/template_tests/test_unicode.py3
-rw-r--r--tests/test_utils/tests.py2
-rw-r--r--tests/update/models.py5
-rw-r--r--tests/urlpatterns_reverse/tests.py8
-rw-r--r--tests/utils_tests/test_encoding.py3
-rw-r--r--tests/utils_tests/test_functional.py7
-rw-r--r--tests/utils_tests/test_lazyobject.py2
-rw-r--r--tests/utils_tests/test_safestring.py4
-rw-r--r--tests/utils_tests/test_text.py3
213 files changed, 574 insertions, 763 deletions
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 '<ul>%s</ul>' % ''.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 <p>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 <li>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 <span> 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, '<td class="field-swallowonetoone">-</td>')
self.assertContains(response, '<td class="field-swallowonetoone">%s</td>' % 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,
'<li class="success">The short message "<a href="%s">'
@@ -3806,7 +3806,7 @@ class AdminCustomQuerysetTest(TestCase):
self.assertEqual(response.status_code, 200)
self.assertEqual(Paper.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,
'<li class="success">The paper "<a href="%s">'
@@ -3863,8 +3863,8 @@ class AdminInlineFileUploadTest(TestCase):
"pictures-TOTAL_FORMS": "2",
"pictures-INITIAL_FORMS": "1",
"pictures-MAX_NUM_FORMS": "0",
- "pictures-0-id": six.text_type(self.picture.id),
- "pictures-0-gallery": six.text_type(self.gallery.id),
+ "pictures-0-id": str(self.picture.id),
+ "pictures-0-gallery": str(self.gallery.id),
"pictures-0-name": "Test Picture",
"pictures-0-image": "",
"pictures-1-id": "",
diff --git a/tests/admin_widgets/tests.py b/tests/admin_widgets/tests.py
index 8eadab07d5..ae8443565d 100644
--- a/tests/admin_widgets/tests.py
+++ b/tests/admin_widgets/tests.py
@@ -17,7 +17,7 @@ from django.core.files.uploadedfile import SimpleUploadedFile
from django.db.models import CharField, DateField, DateTimeField
from django.test import SimpleTestCase, TestCase, override_settings
from django.urls import reverse
-from django.utils import six, translation
+from django.utils import translation
from .models import (
Advisor, Album, Band, Bee, Car, Company, Event, Honeycomb, Individual,
@@ -180,7 +180,7 @@ class AdminFormfieldForDBFieldTests(SimpleTestCase):
ma = AdvisorAdmin(Advisor, admin.site)
f = ma.formfield_for_dbfield(Advisor._meta.get_field('companies'), request=None)
self.assertEqual(
- six.text_type(f.help_text),
+ f.help_text,
'Hold down "Control", or "Command" on a Mac, to select more than one.'
)
diff --git a/tests/auth_tests/test_management.py b/tests/auth_tests/test_management.py
index ac57bbd511..9335b75dba 100644
--- a/tests/auth_tests/test_management.py
+++ b/tests/auth_tests/test_management.py
@@ -79,7 +79,7 @@ class GetDefaultUsernameTestCase(TestCase):
management.get_system_username = self.old_get_system_username
def test_actual_implementation(self):
- self.assertIsInstance(management.get_system_username(), six.text_type)
+ self.assertIsInstance(management.get_system_username(), str)
def test_simple(self):
management.get_system_username = lambda: 'joe'
diff --git a/tests/backends/tests.py b/tests/backends/tests.py
index 7a102b040a..a7939ed8be 100644
--- a/tests/backends/tests.py
+++ b/tests/backends/tests.py
@@ -23,7 +23,6 @@ from django.test import (
SimpleTestCase, TestCase, TransactionTestCase, mock, override_settings,
skipIfDBFeature, skipUnlessDBFeature,
)
-from django.utils import six
from django.utils.six.moves import range
from .models import (
@@ -101,7 +100,7 @@ class OracleTests(unittest.TestCase):
# than 4000 chars and read it properly
with connection.cursor() as cursor:
cursor.execute('CREATE TABLE ltext ("TEXT" NCLOB)')
- long_str = ''.join(six.text_type(x) for x in range(4000))
+ long_str = ''.join(str(x) for x in range(4000))
cursor.execute('INSERT INTO ltext VALUES (%s)', [long_str])
cursor.execute('SELECT text FROM ltext')
row = cursor.fetchone()
@@ -419,7 +418,7 @@ class LastExecutedQueryTest(TestCase):
sql, params = data.query.sql_with_params()
cursor = data.query.get_compiler('default').execute_sql(CURSOR)
last_sql = cursor.db.ops.last_executed_query(cursor, sql, params)
- self.assertIsInstance(last_sql, six.text_type)
+ self.assertIsInstance(last_sql, str)
@unittest.skipUnless(connection.vendor == 'sqlite',
"This test is specific to SQLite.")
diff --git a/tests/contenttypes_tests/test_models.py b/tests/contenttypes_tests/test_models.py
index bb0f8c890f..4c16e0b4aa 100644
--- a/tests/contenttypes_tests/test_models.py
+++ b/tests/contenttypes_tests/test_models.py
@@ -3,7 +3,6 @@ from django.contrib.contenttypes.views import shortcut
from django.contrib.sites.shortcuts import get_current_site
from django.http import Http404, HttpRequest
from django.test import TestCase, override_settings
-from django.utils import six
from .models import (
ConcreteModel, FooWithBrokenAbsoluteUrl, FooWithoutUrl, FooWithUrl,
@@ -242,7 +241,7 @@ class ContentTypesTests(TestCase):
app_label='contenttypes',
model='OldModel',
)
- self.assertEqual(six.text_type(ct), 'OldModel')
+ self.assertEqual(str(ct), 'OldModel')
self.assertIsNone(ct.model_class())
# Make sure stale ContentTypes can be fetched like any other object.
diff --git a/tests/csrf_tests/tests.py b/tests/csrf_tests/tests.py
index 33f30a8353..49247b7af8 100644
--- a/tests/csrf_tests/tests.py
+++ b/tests/csrf_tests/tests.py
@@ -13,7 +13,6 @@ from django.middleware.csrf import (
from django.test import SimpleTestCase, override_settings
from django.test.utils import patch_logger
from django.utils.encoding import force_bytes
-from django.utils.six import text_type
from django.views.decorators.csrf import csrf_exempt, requires_csrf_token
from .views import (
@@ -65,7 +64,7 @@ class CsrfViewMiddlewareTestMixin(object):
return req
def _check_token_present(self, response, csrf_id=None):
- text = text_type(response.content, response.charset)
+ text = str(response.content, response.charset)
match = re.search("name='csrfmiddlewaretoken' value='(.*?)'", text)
csrf_token = csrf_id or self._csrf_id
self.assertTrue(
diff --git a/tests/custom_columns/tests.py b/tests/custom_columns/tests.py
index 04aca12914..2d7044b8de 100644
--- a/tests/custom_columns/tests.py
+++ b/tests/custom_columns/tests.py
@@ -1,6 +1,5 @@
from django.core.exceptions import FieldError
from django.test import TestCase
-from django.utils import six
from .models import Article, Author
@@ -20,7 +19,7 @@ class CustomColumnsTests(TestCase):
Author.objects.all(), [
"Peter Jones", "John Smith",
],
- six.text_type
+ str
)
def test_get_first_name(self):
@@ -34,7 +33,7 @@ class CustomColumnsTests(TestCase):
Author.objects.filter(first_name__exact="John"), [
"John Smith",
],
- six.text_type
+ str
)
def test_field_error(self):
@@ -54,7 +53,7 @@ class CustomColumnsTests(TestCase):
"Peter Jones",
"John Smith",
],
- six.text_type
+ str
)
def test_get_all_articles_for_an_author(self):
@@ -70,7 +69,7 @@ class CustomColumnsTests(TestCase):
self.article.authors.filter(last_name='Jones'), [
"Peter Jones"
],
- six.text_type
+ str
)
def test_author_querying(self):
diff --git a/tests/custom_managers/tests.py b/tests/custom_managers/tests.py
index 1bfaf52766..54f3b58a79 100644
--- a/tests/custom_managers/tests.py
+++ b/tests/custom_managers/tests.py
@@ -1,6 +1,5 @@
from django.db import models
from django.test import TestCase
-from django.utils import six
from .models import (
Book, Car, CustomManager, CustomQuerySet, DeconstructibleCustomManager,
@@ -34,7 +33,7 @@ class CustomManagerTests(TestCase):
Person.objects.get_fun_people(), [
"Bugs Bunny"
],
- six.text_type
+ str
)
def test_queryset_copied_to_default(self):
@@ -67,12 +66,12 @@ class CustomManagerTests(TestCase):
for manager_name in self.custom_manager_names:
manager = getattr(Person, manager_name)
queryset = manager.filter()
- self.assertQuerysetEqual(queryset, ["Bugs Bunny"], six.text_type)
+ self.assertQuerysetEqual(queryset, ["Bugs Bunny"], str)
self.assertIs(queryset._filter_CustomQuerySet, True)
# Specialized querysets inherit from our custom queryset.
queryset = manager.values_list('first_name', flat=True).filter()
- self.assertEqual(list(queryset), [six.text_type("Bugs")])
+ self.assertEqual(list(queryset), ["Bugs"])
self.assertIs(queryset._filter_CustomQuerySet, True)
self.assertIsInstance(queryset.values(), CustomQuerySet)
@@ -99,7 +98,7 @@ class CustomManagerTests(TestCase):
Queryset method doesn't override the custom manager method.
"""
queryset = Person.custom_queryset_custom_manager.filter()
- self.assertQuerysetEqual(queryset, ["Bugs Bunny"], six.text_type)
+ self.assertQuerysetEqual(queryset, ["Bugs Bunny"], str)
self.assertIs(queryset._filter_CustomManager, True)
def test_related_manager(self):
diff --git a/tests/custom_pk/fields.py b/tests/custom_pk/fields.py
index eb63f66679..fa61a72a0d 100644
--- a/tests/custom_pk/fields.py
+++ b/tests/custom_pk/fields.py
@@ -2,7 +2,6 @@ import random
import string
from django.db import models
-from django.utils import six
class MyWrapper(object):
@@ -50,12 +49,12 @@ class MyAutoField(models.CharField):
if not value:
return
if isinstance(value, MyWrapper):
- return six.text_type(value)
+ return str(value)
return value
def get_db_prep_value(self, value, connection, prepared=False):
if not value:
return
if isinstance(value, MyWrapper):
- return six.text_type(value)
+ return str(value)
return value
diff --git a/tests/custom_pk/tests.py b/tests/custom_pk/tests.py
index 01150a46d2..7c89b6d120 100644
--- a/tests/custom_pk/tests.py
+++ b/tests/custom_pk/tests.py
@@ -1,6 +1,5 @@
from django.db import IntegrityError, transaction
from django.test import TestCase, skipIfDBFeature
-from django.utils import six
from .models import Bar, Business, Employee, Foo
@@ -25,14 +24,14 @@ class BasicCustomPKTests(TestCase):
Employee.objects.filter(pk=123), [
"Dan Jones",
],
- six.text_type
+ str
)
self.assertQuerysetEqual(
Employee.objects.filter(employee_code=123), [
"Dan Jones",
],
- six.text_type
+ str
)
self.assertQuerysetEqual(
@@ -40,7 +39,7 @@ class BasicCustomPKTests(TestCase):
"Fran Bones",
"Dan Jones",
],
- six.text_type
+ str
)
self.assertQuerysetEqual(
@@ -48,7 +47,7 @@ class BasicCustomPKTests(TestCase):
"Fran Bones",
"Dan Jones",
],
- six.text_type
+ str
)
self.assertQuerysetEqual(
@@ -73,7 +72,7 @@ class BasicCustomPKTests(TestCase):
"Fran Bones",
"Dan Jones",
],
- six.text_type
+ str
)
self.assertQuerysetEqual(
self.fran.business_set.all(), [
@@ -91,14 +90,14 @@ class BasicCustomPKTests(TestCase):
"Fran Bones",
"Dan Jones",
],
- six.text_type,
+ str,
)
self.assertQuerysetEqual(
Employee.objects.filter(business__pk="Sears"), [
"Fran Bones",
"Dan Jones",
],
- six.text_type,
+ str,
)
self.assertQuerysetEqual(
@@ -173,7 +172,7 @@ class BasicCustomPKTests(TestCase):
"Dan Jones",
"Fran Jones",
],
- six.text_type
+ str
)
diff --git a/tests/datatypes/tests.py b/tests/datatypes/tests.py
index b6899c7609..5c3dffa457 100644
--- a/tests/datatypes/tests.py
+++ b/tests/datatypes/tests.py
@@ -1,7 +1,6 @@
import datetime
from django.test import TestCase, skipIfDBFeature
-from django.utils import six
from django.utils.timezone import utc
from .models import Donut, RumBaba
@@ -75,7 +74,7 @@ class DataTypesTestCase(TestCase):
database should be unicode."""
d = Donut.objects.create(name='Jelly Donut', review='Outstanding')
newd = Donut.objects.get(id=d.id)
- self.assertIsInstance(newd.review, six.text_type)
+ self.assertIsInstance(newd.review, str)
@skipIfDBFeature('supports_timezones')
def test_error_on_timezone(self):
diff --git a/tests/expressions/tests.py b/tests/expressions/tests.py
index d3eabb6dbb..0a41494217 100644
--- a/tests/expressions/tests.py
+++ b/tests/expressions/tests.py
@@ -20,7 +20,6 @@ from django.db.models.sql import constants
from django.db.models.sql.datastructures import Join
from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature
from django.test.utils import Approximate
-from django.utils import six
from .models import (
UUID, Company, Employee, Experiment, Number, Result, SimulationRun, Time,
@@ -202,7 +201,7 @@ class BasicExpressionsTests(TestCase):
"Frank Meyer",
"Max Mustermann",
],
- lambda c: six.text_type(c.point_of_contact),
+ lambda c: str(c.point_of_contact),
ordered=False
)
diff --git a/tests/expressions_case/tests.py b/tests/expressions_case/tests.py
index 414c4353a5..a662ffbc3b 100644
--- a/tests/expressions_case/tests.py
+++ b/tests/expressions_case/tests.py
@@ -9,7 +9,6 @@ from django.db import connection, models
from django.db.models import F, Max, Min, Q, Sum, Value
from django.db.models.expressions import Case, When
from django.test import TestCase
-from django.utils import six
from .models import CaseTestModel, Client, FKCaseTestModel, O2OCaseTestModel
@@ -648,7 +647,7 @@ class CaseExpressionTests(TestCase):
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by('pk'),
[(1, b'one'), (2, b'two'), (3, b''), (2, b'two'), (3, b''), (3, b''), (4, b'')],
- transform=lambda o: (o.integer, six.binary_type(o.binary))
+ transform=lambda o: (o.integer, bytes(o.binary))
)
def test_update_boolean(self):
@@ -757,7 +756,7 @@ class CaseExpressionTests(TestCase):
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by('pk'),
[(1, '~/1'), (2, '~/2'), (3, ''), (2, '~/2'), (3, ''), (3, ''), (4, '')],
- transform=lambda o: (o.integer, six.text_type(o.file))
+ transform=lambda o: (o.integer, str(o.file))
)
def test_update_file_path(self):
@@ -798,7 +797,7 @@ class CaseExpressionTests(TestCase):
self.assertQuerysetEqual(
CaseTestModel.objects.all().order_by('pk'),
[(1, '~/1'), (2, '~/2'), (3, ''), (2, '~/2'), (3, ''), (3, ''), (4, '')],
- transform=lambda o: (o.integer, six.text_type(o.image))
+ transform=lambda o: (o.integer, str(o.image))
)
def test_update_generic_ip_address(self):
diff --git a/tests/field_deconstruction/tests.py b/tests/field_deconstruction/tests.py
index bb16f4d76e..7b816b8bf0 100644
--- a/tests/field_deconstruction/tests.py
+++ b/tests/field_deconstruction/tests.py
@@ -2,7 +2,6 @@ from django.apps import apps
from django.db import models
from django.test import SimpleTestCase, override_settings
from django.test.utils import isolate_lru_cache
-from django.utils import six
class FieldDeconstructionTests(SimpleTestCase):
@@ -21,7 +20,6 @@ class FieldDeconstructionTests(SimpleTestCase):
field.set_attributes_from_name("is_awesome_test")
name, path, args, kwargs = field.deconstruct()
self.assertEqual(name, "is_awesome_test")
- self.assertIsInstance(name, six.text_type)
# Now try with a ForeignKey
field = models.ForeignKey("some_fake.ModelName", models.CASCADE)
name, path, args, kwargs = field.deconstruct()
diff --git a/tests/field_defaults/tests.py b/tests/field_defaults/tests.py
index 031fd75fe3..19b05aa537 100644
--- a/tests/field_defaults/tests.py
+++ b/tests/field_defaults/tests.py
@@ -1,7 +1,6 @@
from datetime import datetime
from django.test import TestCase
-from django.utils import six
from .models import Article
@@ -12,6 +11,6 @@ class DefaultTests(TestCase):
now = datetime.now()
a.save()
- self.assertIsInstance(a.id, six.integer_types)
+ self.assertIsInstance(a.id, int)
self.assertEqual(a.headline, "Default headline")
self.assertLess((now - a.pub_date).seconds, 5)
diff --git a/tests/file_uploads/views.py b/tests/file_uploads/views.py
index bba71b87c2..c4166087ac 100644
--- a/tests/file_uploads/views.py
+++ b/tests/file_uploads/views.py
@@ -5,7 +5,6 @@ import os
from django.core.files.uploadedfile import UploadedFile
from django.http import HttpResponse, HttpResponseServerError
-from django.utils import six
from django.utils.encoding import force_bytes, force_str
from .models import FileModel
@@ -19,7 +18,7 @@ def file_upload_view(request):
"""
form_data = request.POST.copy()
form_data.update(request.FILES)
- if isinstance(form_data.get('file_field'), UploadedFile) and isinstance(form_data['name'], six.text_type):
+ if isinstance(form_data.get('file_field'), UploadedFile) and isinstance(form_data['name'], str):
# If a file is posted, the dummy client should only post the file name,
# not the full path.
if os.path.dirname(form_data['file_field'].name) != '':
diff --git a/tests/files/tests.py b/tests/files/tests.py
index a0ff3d4782..50db4b7436 100644
--- a/tests/files/tests.py
+++ b/tests/files/tests.py
@@ -11,7 +11,6 @@ from django.core.files.move import file_move_safe
from django.core.files.temp import NamedTemporaryFile
from django.core.files.uploadedfile import SimpleUploadedFile, UploadedFile
from django.test import mock
-from django.utils import six
from django.utils._os import upath
try:
@@ -177,11 +176,11 @@ class ContentFileTestCase(unittest.TestCase):
def test_content_file_input_type(self):
"""
- ContentFile can accept both bytes and unicode and that the
- retrieved content is of the same type.
+ ContentFile can accept both bytes and strings and the retrieved content
+ is of the same type.
"""
self.assertIsInstance(ContentFile(b"content").read(), bytes)
- self.assertIsInstance(ContentFile("español").read(), six.text_type)
+ self.assertIsInstance(ContentFile("español").read(), str)
class DimensionClosingBug(unittest.TestCase):
diff --git a/tests/fixtures_regress/models.py b/tests/fixtures_regress/models.py
index a631fa44d1..d76642ac97 100644
--- a/tests/fixtures_regress/models.py
+++ b/tests/fixtures_regress/models.py
@@ -1,6 +1,5 @@
from django.contrib.auth.models import User
from django.db import models
-from django.utils import six
class Animal(models.Model):
@@ -29,7 +28,7 @@ class Stuff(models.Model):
owner = models.ForeignKey(User, models.SET_NULL, null=True)
def __str__(self):
- return six.text_type(self.name) + ' is owned by ' + six.text_type(self.owner)
+ return self.name + ' is owned by ' + str(self.owner)
class Absolute(models.Model):
diff --git a/tests/forms_tests/field_tests/test_filepathfield.py b/tests/forms_tests/field_tests/test_filepathfield.py
index 07ebe67f06..71164b5b7a 100644
--- a/tests/forms_tests/field_tests/test_filepathfield.py
+++ b/tests/forms_tests/field_tests/test_filepathfield.py
@@ -2,12 +2,11 @@ import os.path
from django.forms import FilePathField, ValidationError, forms
from django.test import SimpleTestCase
-from django.utils import six
from django.utils._os import upath
def fix_os_paths(x):
- if isinstance(x, six.string_types):
+ if isinstance(x, str):
return x.replace('\\', '/')
elif isinstance(x, tuple):
return tuple(fix_os_paths(list(x)))
diff --git a/tests/forms_tests/field_tests/test_typedchoicefield.py b/tests/forms_tests/field_tests/test_typedchoicefield.py
index c08a8bb611..bf0fdb4d47 100644
--- a/tests/forms_tests/field_tests/test_typedchoicefield.py
+++ b/tests/forms_tests/field_tests/test_typedchoicefield.py
@@ -2,7 +2,6 @@ import decimal
from django.forms import TypedChoiceField, ValidationError
from django.test import SimpleTestCase
-from django.utils import six
class TypedChoiceFieldTest(SimpleTestCase):
@@ -53,7 +52,7 @@ class TypedChoiceFieldTest(SimpleTestCase):
self.assertFalse(f.has_changed('1', '1'))
f = TypedChoiceField(
- choices=[('', '---------'), ('a', "a"), ('b', "b")], coerce=six.text_type,
+ choices=[('', '---------'), ('a', "a"), ('b', "b")], coerce=str,
required=False, initial=None, empty_value=None,
)
self.assertFalse(f.has_changed(None, ''))
diff --git a/tests/forms_tests/tests/test_utils.py b/tests/forms_tests/tests/test_utils.py
index f06b60a620..f52c195637 100644
--- a/tests/forms_tests/tests/test_utils.py
+++ b/tests/forms_tests/tests/test_utils.py
@@ -3,7 +3,6 @@ import copy
from django.core.exceptions import ValidationError
from django.forms.utils import ErrorDict, ErrorList, flatatt
from django.test import SimpleTestCase
-from django.utils import six
from django.utils.encoding import force_text
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy
@@ -63,7 +62,7 @@ class FormsUtilsTestCase(SimpleTestCase):
)
# Can take a unicode string.
self.assertHTMLEqual(
- six.text_type(ErrorList(ValidationError("Not \u03C0.").messages)),
+ str(ErrorList(ValidationError("Not \u03C0.").messages)),
'<ul class="errorlist"><li>Not π.</li></ul>'
)
# Can take a lazy string.
diff --git a/tests/forms_tests/tests/tests.py b/tests/forms_tests/tests/tests.py
index 025b749762..0119410fc8 100644
--- a/tests/forms_tests/tests/tests.py
+++ b/tests/forms_tests/tests/tests.py
@@ -7,7 +7,6 @@ from django.forms import (
)
from django.forms.models import ModelFormMetaclass
from django.test import SimpleTestCase, TestCase
-from django.utils import six
from ..models import (
BoundaryModel, ChoiceFieldModel, ChoiceModel, ChoiceOptionModel, Defaults,
@@ -97,7 +96,7 @@ class ModelFormCallableModelDefault(TestCase):
choices = list(ChoiceFieldForm().fields['choice'].choices)
self.assertEqual(len(choices), 1)
- self.assertEqual(choices[0], (option.pk, six.text_type(option)))
+ self.assertEqual(choices[0], (option.pk, str(option)))
def test_callable_initial_value(self):
"The initial value for a callable default returning a queryset is the pk (refs #13769)"
diff --git a/tests/gis_tests/geoadmin/tests.py b/tests/gis_tests/geoadmin/tests.py
index 23fa8071b3..96877c26e3 100644
--- a/tests/gis_tests/geoadmin/tests.py
+++ b/tests/gis_tests/geoadmin/tests.py
@@ -96,6 +96,6 @@ class GeoAdminTest(TestCase):
self.assertEqual(len(logger_calls), 1)
self.assertEqual(
logger_calls[0],
- "Error creating geometry from value 'INVALID()' (String or unicode input "
+ "Error creating geometry from value 'INVALID()' (String input "
"unrecognized as WKT EWKT, and HEXEWKB.)"
)
diff --git a/tests/gis_tests/geoapp/test_functions.py b/tests/gis_tests/geoapp/test_functions.py
index 2767b7974b..4d3913a7a3 100644
--- a/tests/gis_tests/geoapp/test_functions.py
+++ b/tests/gis_tests/geoapp/test_functions.py
@@ -7,7 +7,6 @@ from django.contrib.gis.measure import Area
from django.db import connection
from django.db.models import Sum
from django.test import TestCase, skipUnlessDBFeature
-from django.utils import six
from ..utils import mysql, oracle, postgis, spatialite
from .models import City, Country, CountryWebMercator, State, Track
@@ -361,7 +360,7 @@ class GISFunctionsTests(TestCase):
for bad_args in ((), range(3), range(5)):
with self.assertRaises(ValueError):
Country.objects.annotate(snap=functions.SnapToGrid('mpoly', *bad_args))
- for bad_args in (('1.0',), (1.0, None), tuple(map(six.text_type, range(4)))):
+ for bad_args in (('1.0',), (1.0, None), tuple(map(str, range(4)))):
with self.assertRaises(TypeError):
Country.objects.annotate(snap=functions.SnapToGrid('mpoly', *bad_args))
diff --git a/tests/gis_tests/geos_tests/test_geos.py b/tests/gis_tests/geos_tests/test_geos.py
index ff28eebf0f..7877e1f2d6 100644
--- a/tests/gis_tests/geos_tests/test_geos.py
+++ b/tests/gis_tests/geos_tests/test_geos.py
@@ -17,7 +17,6 @@ from django.contrib.gis.shortcuts import numpy
from django.template import Context
from django.template.engine import Engine
from django.test import SimpleTestCase, mock
-from django.utils import six
from django.utils.encoding import force_bytes
from django.utils.six.moves import range
@@ -65,8 +64,8 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
self.assertIs(GEOSGeometry(hexewkb_3d).hasz, True)
# Same for EWKB.
- self.assertEqual(six.memoryview(a2b_hex(hexewkb_2d)), pnt_2d.ewkb)
- self.assertEqual(six.memoryview(a2b_hex(hexewkb_3d)), pnt_3d.ewkb)
+ self.assertEqual(memoryview(a2b_hex(hexewkb_2d)), pnt_2d.ewkb)
+ self.assertEqual(memoryview(a2b_hex(hexewkb_3d)), pnt_3d.ewkb)
# Redundant sanity check.
self.assertEqual(4326, GEOSGeometry(hexewkb_2d).srid)
@@ -88,7 +87,7 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
# Bad WKB
with self.assertRaises(GEOSException):
- GEOSGeometry(six.memoryview(b'0'))
+ GEOSGeometry(memoryview(b'0'))
class NotAGeometry(object):
pass
@@ -118,7 +117,7 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
def test_create_wkb(self):
"Testing creation from WKB."
for g in self.geometries.hex_wkt:
- wkb = six.memoryview(a2b_hex(g.hex.encode()))
+ wkb = memoryview(a2b_hex(g.hex.encode()))
geom_h = GEOSGeometry(wkb)
# we need to do this so decimal places get normalized
geom_t = fromstr(g.wkt)
@@ -1164,13 +1163,13 @@ class GEOSTest(SimpleTestCase, TestDataMixin):
g = GEOSGeometry("POINT(0 0)")
self.assertTrue(g.valid)
- self.assertIsInstance(g.valid_reason, six.string_types)
+ self.assertIsInstance(g.valid_reason, str)
self.assertEqual(g.valid_reason, "Valid Geometry")
g = GEOSGeometry("LINESTRING(0 0, 0 0)")
self.assertFalse(g.valid)
- self.assertIsInstance(g.valid_reason, six.string_types)
+ self.assertIsInstance(g.valid_reason, str)
self.assertTrue(g.valid_reason.startswith("Too few points in geometry component"))
def test_linearref(self):
diff --git a/tests/gis_tests/geos_tests/test_io.py b/tests/gis_tests/geos_tests/test_io.py
index 81e0ff357f..98b2aba3b4 100644
--- a/tests/gis_tests/geos_tests/test_io.py
+++ b/tests/gis_tests/geos_tests/test_io.py
@@ -6,7 +6,6 @@ from django.contrib.gis.geos import (
WKTWriter,
)
from django.test import SimpleTestCase
-from django.utils.six import memoryview
@skipUnless(HAS_GEOS, "Geos is required.")
@@ -25,7 +24,7 @@ class GEOSIOTest(SimpleTestCase):
for geom in (g1, g2):
self.assertEqual(ref, geom)
- # Should only accept six.string_types objects.
+ # Should only accept string objects.
with self.assertRaises(TypeError):
wkt_r.read(1)
with self.assertRaises(TypeError):
diff --git a/tests/gis_tests/geos_tests/test_mutable_list.py b/tests/gis_tests/geos_tests/test_mutable_list.py
index 3f7d8c30a1..26bdeb8045 100644
--- a/tests/gis_tests/geos_tests/test_mutable_list.py
+++ b/tests/gis_tests/geos_tests/test_mutable_list.py
@@ -7,7 +7,6 @@
import unittest
from django.contrib.gis.geos.mutable_list import ListMixin
-from django.utils import six
class UserListA(ListMixin):
@@ -298,7 +297,7 @@ class ListMixinTest(unittest.TestCase):
def test07_allowed_types(self):
'Type-restricted list'
pl, ul = self.lists_of_len()
- ul._allowed = six.integer_types
+ ul._allowed = int
ul[1] = 50
ul[:2] = [60, 70, 80]
diff --git a/tests/gis_tests/test_geoforms.py b/tests/gis_tests/test_geoforms.py
index 27b80ce9b2..6fe0996721 100644
--- a/tests/gis_tests/test_geoforms.py
+++ b/tests/gis_tests/test_geoforms.py
@@ -132,7 +132,7 @@ class GeometryFieldTest(SimpleTestCase):
self.assertEqual(len(logger_calls), 1)
self.assertEqual(
logger_calls[0],
- "Error creating geometry from value 'PNT(0)' (String or unicode input "
+ "Error creating geometry from value 'PNT(0)' (String input "
"unrecognized as WKT EWKT, and HEXEWKB.)"
)
diff --git a/tests/gis_tests/test_geoip2.py b/tests/gis_tests/test_geoip2.py
index 54f20412a4..d35dcc336e 100644
--- a/tests/gis_tests/test_geoip2.py
+++ b/tests/gis_tests/test_geoip2.py
@@ -6,7 +6,6 @@ from django.conf import settings
from django.contrib.gis.geoip2 import HAS_GEOIP2
from django.contrib.gis.geos import HAS_GEOS, GEOSGeometry
from django.test import mock
-from django.utils import six
if HAS_GEOIP2:
from django.contrib.gis.geoip2 import GeoIP2, GeoIP2Exception
@@ -48,7 +47,7 @@ class GeoIPTest(unittest.TestCase):
for bad in bad_params:
with self.assertRaises(GeoIP2Exception):
GeoIP2(cache=bad)
- if isinstance(bad, six.string_types):
+ if isinstance(bad, str):
e = GeoIP2Exception
else:
e = TypeError
diff --git a/tests/handlers/tests.py b/tests/handlers/tests.py
index 72ba98b1d3..d7cfaadf62 100644
--- a/tests/handlers/tests.py
+++ b/tests/handlers/tests.py
@@ -7,7 +7,6 @@ from django.db import close_old_connections, connection
from django.test import (
RequestFactory, SimpleTestCase, TransactionTestCase, override_settings,
)
-from django.utils import six
from django.utils.encoding import force_str
try:
@@ -185,7 +184,7 @@ class HandlerRequestTests(SimpleTestCase):
def test_environ_path_info_type(self):
environ = RequestFactory().get('/%E2%A8%87%87%A5%E2%A8%A0').environ
- self.assertIsInstance(environ['PATH_INFO'], six.text_type)
+ self.assertIsInstance(environ['PATH_INFO'], str)
@unittest.skipIf(HTTPStatus is None, 'HTTPStatus only exists on Python 3.5+')
def test_handle_accepts_httpstatus_enum_value(self):
diff --git a/tests/httpwrappers/tests.py b/tests/httpwrappers/tests.py
index 9042f8ed6e..b8d359de41 100644
--- a/tests/httpwrappers/tests.py
+++ b/tests/httpwrappers/tests.py
@@ -578,7 +578,7 @@ class StreamingHttpResponseTests(SimpleTestCase):
chunks = list(r)
self.assertEqual(chunks, [b'hello', b'world'])
for chunk in chunks:
- self.assertIsInstance(chunk, six.binary_type)
+ self.assertIsInstance(chunk, bytes)
# and the response can only be iterated once.
self.assertEqual(list(r), [])
@@ -595,7 +595,7 @@ class StreamingHttpResponseTests(SimpleTestCase):
# '\xc3\xa9' == unichr(233).encode('utf-8')
self.assertEqual(chunks, [b'hello', b'caf\xc3\xa9'])
for chunk in chunks:
- self.assertIsInstance(chunk, six.binary_type)
+ self.assertIsInstance(chunk, bytes)
# streaming responses don't have a `content` attribute.
self.assertFalse(hasattr(r, 'content'))
@@ -616,8 +616,7 @@ class StreamingHttpResponseTests(SimpleTestCase):
# coercing a streaming response to bytes doesn't return a complete HTTP
# message like a regular response does. it only gives us the headers.
r = StreamingHttpResponse(iter(['hello', 'world']))
- self.assertEqual(
- six.binary_type(r), b'Content-Type: text/html; charset=utf-8')
+ self.assertEqual(bytes(r), b'Content-Type: text/html; charset=utf-8')
# and this won't consume its content.
self.assertEqual(list(r), [b'hello', b'world'])
diff --git a/tests/i18n/contenttypes/tests.py b/tests/i18n/contenttypes/tests.py
index 2a14e25972..94f355aba7 100644
--- a/tests/i18n/contenttypes/tests.py
+++ b/tests/i18n/contenttypes/tests.py
@@ -2,7 +2,7 @@ import os
from django.contrib.contenttypes.models import ContentType
from django.test import TestCase, override_settings
-from django.utils import six, translation
+from django.utils import translation
from django.utils._os import upath
@@ -21,6 +21,6 @@ class ContentTypeTests(TestCase):
def test_verbose_name(self):
company_type = ContentType.objects.get(app_label='i18n', model='company')
with translation.override('en'):
- self.assertEqual(six.text_type(company_type), 'Company')
+ self.assertEqual(str(company_type), 'Company')
with translation.override('fr'):
- self.assertEqual(six.text_type(company_type), 'Société')
+ self.assertEqual(str(company_type), 'Société')
diff --git a/tests/i18n/test_extraction.py b/tests/i18n/test_extraction.py
index 33e136e1dd..b8342865a9 100644
--- a/tests/i18n/test_extraction.py
+++ b/tests/i18n/test_extraction.py
@@ -16,7 +16,6 @@ from django.core.management.commands.makemessages import \
from django.core.management.utils import find_command
from django.test import SimpleTestCase, mock, override_settings
from django.test.utils import captured_stderr, captured_stdout
-from django.utils import six
from django.utils.encoding import force_text
from django.utils.six import StringIO
from django.utils.translation import TranslatorCommentWarning
@@ -69,7 +68,7 @@ class ExtractorTests(POFileAssertionMixin, RunInTmpDirMixin, SimpleTestCase):
path = os.path.join(cwd_prefix, *comment_parts)
parts = [path]
- if isinstance(line_number, six.string_types):
+ if isinstance(line_number, str):
line_number = self._get_token_line_number(path, line_number)
if line_number is not None:
parts.append(':%d' % line_number)
diff --git a/tests/i18n/tests.py b/tests/i18n/tests.py
index d039d016ce..c3acdfe2fc 100644
--- a/tests/i18n/tests.py
+++ b/tests/i18n/tests.py
@@ -14,7 +14,7 @@ from django.template import Context, Template
from django.test import (
RequestFactory, SimpleTestCase, TestCase, override_settings,
)
-from django.utils import six, translation
+from django.utils import translation
from django.utils._os import upath
from django.utils.formats import (
date_format, get_format, get_format_modules, iter_format_modules, localize,
@@ -140,9 +140,9 @@ class TranslationTests(SimpleTestCase):
def test_lazy_pickle(self):
s1 = ugettext_lazy("test")
- self.assertEqual(six.text_type(s1), "test")
+ self.assertEqual(str(s1), "test")
s2 = pickle.loads(pickle.dumps(s1))
- self.assertEqual(six.text_type(s2), "test")
+ self.assertEqual(str(s2), "test")
@override_settings(LOCALE_PATHS=extended_locale_paths)
def test_ungettext_lazy(self):
diff --git a/tests/inline_formsets/tests.py b/tests/inline_formsets/tests.py
index 0fb2fd2f02..fd51714cda 100644
--- a/tests/inline_formsets/tests.py
+++ b/tests/inline_formsets/tests.py
@@ -1,6 +1,5 @@
from django.forms.models import ModelForm, inlineformset_factory
from django.test import TestCase, skipUnlessDBFeature
-from django.utils import six
from .models import Child, Parent, Poem, Poet, School
@@ -65,8 +64,8 @@ class DeletionTests(TestCase):
'poem_set-TOTAL_FORMS': '1',
'poem_set-INITIAL_FORMS': '1',
'poem_set-MAX_NUM_FORMS': '0',
- 'poem_set-0-id': six.text_type(poem.id),
- 'poem_set-0-poem': six.text_type(poem.id),
+ 'poem_set-0-id': str(poem.id),
+ 'poem_set-0-poem': str(poem.id),
'poem_set-0-name': 'x' * 1000,
}
formset = PoemFormSet(data, instance=poet)
diff --git a/tests/lookup/models.py b/tests/lookup/models.py
index 9cf053d873..14742e8a8c 100644
--- a/tests/lookup/models.py
+++ b/tests/lookup/models.py
@@ -5,7 +5,6 @@ This demonstrates features of the database API.
"""
from django.db import models
-from django.utils import six
class Alarm(models.Model):
@@ -48,7 +47,7 @@ class Season(models.Model):
gt = models.IntegerField(null=True, blank=True)
def __str__(self):
- return six.text_type(self.year)
+ return str(self.year)
class Game(models.Model):
diff --git a/tests/m2m_and_m2o/models.py b/tests/m2m_and_m2o/models.py
index 7174e6369a..d9da2bf534 100644
--- a/tests/m2m_and_m2o/models.py
+++ b/tests/m2m_and_m2o/models.py
@@ -4,7 +4,6 @@ Many-to-many and many-to-one relationships to the same table
Make sure to set ``related_name`` if you use relationships to the same table.
"""
from django.db import models
-from django.utils import six
class User(models.Model):
@@ -17,7 +16,7 @@ class Issue(models.Model):
client = models.ForeignKey(User, models.CASCADE, related_name='test_issue_client')
def __str__(self):
- return six.text_type(self.num)
+ return str(self.num)
class Meta:
ordering = ('num',)
diff --git a/tests/m2m_intermediary/tests.py b/tests/m2m_intermediary/tests.py
index d429bf6516..215f6f86c6 100644
--- a/tests/m2m_intermediary/tests.py
+++ b/tests/m2m_intermediary/tests.py
@@ -1,7 +1,6 @@
from datetime import datetime
from django.test import TestCase
-from django.utils import six
from .models import Article, Reporter, Writer
@@ -23,7 +22,7 @@ class M2MIntermediaryTests(TestCase):
("John Smith", "Main writer"),
("Jane Doe", "Contributor"),
],
- lambda w: (six.text_type(w.reporter), w.position)
+ lambda w: (str(w.reporter), w.position)
)
self.assertEqual(w1.reporter, r1)
self.assertEqual(w2.reporter, r2)
@@ -35,5 +34,5 @@ class M2MIntermediaryTests(TestCase):
r1.writer_set.all(), [
("John Smith", "Main writer")
],
- lambda w: (six.text_type(w.reporter), w.position)
+ lambda w: (str(w.reporter), w.position)
)
diff --git a/tests/mail/tests.py b/tests/mail/tests.py
index cfe2889aa6..7c2cd8342a 100644
--- a/tests/mail/tests.py
+++ b/tests/mail/tests.py
@@ -26,7 +26,7 @@ from django.test import SimpleTestCase, override_settings
from django.test.utils import requires_tz_support
from django.utils._os import upath
from django.utils.encoding import force_bytes, force_text
-from django.utils.six import StringIO, binary_type
+from django.utils.six import StringIO
from django.utils.translation import ugettext_lazy
@@ -40,7 +40,7 @@ class HeadersCheckMixin(object):
with the contents of an email message.
headers: should be a set of (header-name, header-value) tuples.
"""
- if isinstance(message, binary_type):
+ if isinstance(message, bytes):
message = message_from_bytes(message)
msg_headers = set(message.items())
self.assertTrue(headers.issubset(msg_headers), msg='Message is missing '
diff --git a/tests/migrations/test_state.py b/tests/migrations/test_state.py
index c8eb1726ba..a6b027e079 100644
--- a/tests/migrations/test_state.py
+++ b/tests/migrations/test_state.py
@@ -10,7 +10,6 @@ from django.db.migrations.state import (
)
from django.test import SimpleTestCase, override_settings
from django.test.utils import isolate_apps
-from django.utils import six
from .models import (
FoodManager, FoodQuerySet, ModelWithCustomBase, NoMigrationFoodManager,
@@ -157,7 +156,7 @@ class StateTests(SimpleTestCase):
# The default manager is used in migrations
self.assertEqual([name for name, mgr in food_state.managers], ['food_mgr'])
- self.assertTrue(all(isinstance(name, six.text_type) for name, mgr in food_state.managers))
+ self.assertTrue(all(isinstance(name, str) for name, mgr in food_state.managers))
self.assertEqual(food_state.managers[0][1].args, ('a', 'b', 1, 2))
# No explicit managers defined. Migrations will fall back to the default
@@ -167,13 +166,13 @@ class StateTests(SimpleTestCase):
# default
self.assertEqual([name for name, mgr in food_no_default_manager_state.managers],
['food_no_mgr', 'food_mgr'])
- self.assertTrue(all(isinstance(name, six.text_type) for name, mgr in food_no_default_manager_state.managers))
+ self.assertTrue(all(isinstance(name, str) for name, mgr in food_no_default_manager_state.managers))
self.assertEqual(food_no_default_manager_state.managers[0][1].__class__, models.Manager)
self.assertIsInstance(food_no_default_manager_state.managers[1][1], FoodManager)
self.assertEqual([name for name, mgr in food_order_manager_state.managers],
['food_mgr1', 'food_mgr2'])
- self.assertTrue(all(isinstance(name, six.text_type) for name, mgr in food_order_manager_state.managers))
+ self.assertTrue(all(isinstance(name, str) for name, mgr in food_order_manager_state.managers))
self.assertEqual([mgr.args for name, mgr in food_order_manager_state.managers],
[('a', 'b', 1, 2), ('x', 'y', 3, 4)])
@@ -373,7 +372,7 @@ class StateTests(SimpleTestCase):
Food = new_apps.get_model("migrations", "Food")
self.assertEqual([mgr.name for mgr in Food._meta.managers],
['default', 'food_mgr1', 'food_mgr2'])
- self.assertTrue(all(isinstance(mgr.name, six.text_type) for mgr in Food._meta.managers))
+ self.assertTrue(all(isinstance(mgr.name, str) for mgr in Food._meta.managers))
self.assertEqual([mgr.__class__ for mgr in Food._meta.managers],
[models.Manager, FoodManager, FoodManager])
diff --git a/tests/migrations/test_writer.py b/tests/migrations/test_writer.py
index b926757920..59fd8eece5 100644
--- a/tests/migrations/test_writer.py
+++ b/tests/migrations/test_writer.py
@@ -42,7 +42,7 @@ class Money(decimal.Decimal):
def deconstruct(self):
return (
'%s.%s' % (self.__class__.__module__, self.__class__.__name__),
- [six.text_type(self)],
+ [str(self)],
{}
)
diff --git a/tests/model_fields/test_foreignkey.py b/tests/model_fields/test_foreignkey.py
index a521d1aa23..2580e3b650 100644
--- a/tests/model_fields/test_foreignkey.py
+++ b/tests/model_fields/test_foreignkey.py
@@ -5,7 +5,6 @@ from django.core import checks
from django.db import models
from django.test import TestCase, skipIfDBFeature
from django.test.utils import isolate_apps
-from django.utils import six
from .models import Bar, FkToChar, Foo, PrimaryKeyCharModel
@@ -50,7 +49,7 @@ class ForeignKeyTests(TestCase):
def test_related_name_converted_to_text(self):
rel_name = Bar._meta.get_field('a').remote_field.related_name
- self.assertIsInstance(rel_name, six.text_type)
+ self.assertIsInstance(rel_name, str)
def test_abstract_model_pending_operations(self):
"""
diff --git a/tests/model_fields/test_integerfield.py b/tests/model_fields/test_integerfield.py
index a474e6e602..99d7b1797c 100644
--- a/tests/model_fields/test_integerfield.py
+++ b/tests/model_fields/test_integerfield.py
@@ -2,7 +2,6 @@ from django.core import validators
from django.core.exceptions import ValidationError
from django.db import connection, models
from django.test import SimpleTestCase, TestCase
-from django.utils import six
from .models import (
BigIntegerModel, IntegerModel, PositiveIntegerModel,
@@ -121,11 +120,11 @@ class IntegerFieldTests(TestCase):
def test_types(self):
instance = self.model(value=0)
- self.assertIsInstance(instance.value, six.integer_types)
+ self.assertIsInstance(instance.value, int)
instance.save()
- self.assertIsInstance(instance.value, six.integer_types)
+ self.assertIsInstance(instance.value, int)
instance = self.model.objects.get()
- self.assertIsInstance(instance.value, six.integer_types)
+ self.assertIsInstance(instance.value, int)
def test_coercing(self):
self.model.objects.create(value='10')
diff --git a/tests/model_fields/test_promises.py b/tests/model_fields/test_promises.py
index 0dcb1abf3b..afbf36651a 100644
--- a/tests/model_fields/test_promises.py
+++ b/tests/model_fields/test_promises.py
@@ -10,7 +10,6 @@ from django.db.models.fields import (
)
from django.db.models.fields.files import FileField, ImageField
from django.test import SimpleTestCase
-from django.utils import six
from django.utils.functional import lazy
@@ -29,10 +28,10 @@ class PromiseTest(SimpleTestCase):
self.assertIsInstance(BooleanField().get_prep_value(lazy_func()), bool)
def test_CharField(self):
- lazy_func = lazy(lambda: '', six.text_type)
- self.assertIsInstance(CharField().get_prep_value(lazy_func()), six.text_type)
+ lazy_func = lazy(lambda: '', str)
+ self.assertIsInstance(CharField().get_prep_value(lazy_func()), str)
lazy_func = lazy(lambda: 0, int)
- self.assertIsInstance(CharField().get_prep_value(lazy_func()), six.text_type)
+ self.assertIsInstance(CharField().get_prep_value(lazy_func()), str)
def test_DateField(self):
lazy_func = lazy(lambda: datetime.date.today(), datetime.date)
@@ -47,44 +46,44 @@ class PromiseTest(SimpleTestCase):
self.assertIsInstance(DecimalField().get_prep_value(lazy_func()), Decimal)
def test_EmailField(self):
- lazy_func = lazy(lambda: 'mailbox@domain.com', six.text_type)
- self.assertIsInstance(EmailField().get_prep_value(lazy_func()), six.text_type)
+ lazy_func = lazy(lambda: 'mailbox@domain.com', str)
+ self.assertIsInstance(EmailField().get_prep_value(lazy_func()), str)
def test_FileField(self):
- lazy_func = lazy(lambda: 'filename.ext', six.text_type)
- self.assertIsInstance(FileField().get_prep_value(lazy_func()), six.text_type)
+ lazy_func = lazy(lambda: 'filename.ext', str)
+ self.assertIsInstance(FileField().get_prep_value(lazy_func()), str)
lazy_func = lazy(lambda: 0, int)
- self.assertIsInstance(FileField().get_prep_value(lazy_func()), six.text_type)
+ self.assertIsInstance(FileField().get_prep_value(lazy_func()), str)
def test_FilePathField(self):
- lazy_func = lazy(lambda: 'tests.py', six.text_type)
- self.assertIsInstance(FilePathField().get_prep_value(lazy_func()), six.text_type)
+ lazy_func = lazy(lambda: 'tests.py', str)
+ self.assertIsInstance(FilePathField().get_prep_value(lazy_func()), str)
lazy_func = lazy(lambda: 0, int)
- self.assertIsInstance(FilePathField().get_prep_value(lazy_func()), six.text_type)
+ self.assertIsInstance(FilePathField().get_prep_value(lazy_func()), str)
def test_FloatField(self):
lazy_func = lazy(lambda: 1.2, float)
self.assertIsInstance(FloatField().get_prep_value(lazy_func()), float)
def test_ImageField(self):
- lazy_func = lazy(lambda: 'filename.ext', six.text_type)
- self.assertIsInstance(ImageField().get_prep_value(lazy_func()), six.text_type)
+ lazy_func = lazy(lambda: 'filename.ext', str)
+ self.assertIsInstance(ImageField().get_prep_value(lazy_func()), str)
def test_IntegerField(self):
lazy_func = lazy(lambda: 1, int)
self.assertIsInstance(IntegerField().get_prep_value(lazy_func()), int)
def test_IPAddressField(self):
- lazy_func = lazy(lambda: '127.0.0.1', six.text_type)
- self.assertIsInstance(IPAddressField().get_prep_value(lazy_func()), six.text_type)
+ lazy_func = lazy(lambda: '127.0.0.1', str)
+ self.assertIsInstance(IPAddressField().get_prep_value(lazy_func()), str)
lazy_func = lazy(lambda: 0, int)
- self.assertIsInstance(IPAddressField().get_prep_value(lazy_func()), six.text_type)
+ self.assertIsInstance(IPAddressField().get_prep_value(lazy_func()), str)
def test_GenericIPAddressField(self):
- lazy_func = lazy(lambda: '127.0.0.1', six.text_type)
- self.assertIsInstance(GenericIPAddressField().get_prep_value(lazy_func()), six.text_type)
+ lazy_func = lazy(lambda: '127.0.0.1', str)
+ self.assertIsInstance(GenericIPAddressField().get_prep_value(lazy_func()), str)
lazy_func = lazy(lambda: 0, int)
- self.assertIsInstance(GenericIPAddressField().get_prep_value(lazy_func()), six.text_type)
+ self.assertIsInstance(GenericIPAddressField().get_prep_value(lazy_func()), str)
def test_NullBooleanField(self):
lazy_func = lazy(lambda: True, bool)
@@ -99,25 +98,25 @@ class PromiseTest(SimpleTestCase):
self.assertIsInstance(PositiveSmallIntegerField().get_prep_value(lazy_func()), int)
def test_SlugField(self):
- lazy_func = lazy(lambda: 'slug', six.text_type)
- self.assertIsInstance(SlugField().get_prep_value(lazy_func()), six.text_type)
+ lazy_func = lazy(lambda: 'slug', str)
+ self.assertIsInstance(SlugField().get_prep_value(lazy_func()), str)
lazy_func = lazy(lambda: 0, int)
- self.assertIsInstance(SlugField().get_prep_value(lazy_func()), six.text_type)
+ self.assertIsInstance(SlugField().get_prep_value(lazy_func()), str)
def test_SmallIntegerField(self):
lazy_func = lazy(lambda: 1, int)
self.assertIsInstance(SmallIntegerField().get_prep_value(lazy_func()), int)
def test_TextField(self):
- lazy_func = lazy(lambda: 'Abc', six.text_type)
- self.assertIsInstance(TextField().get_prep_value(lazy_func()), six.text_type)
+ lazy_func = lazy(lambda: 'Abc', str)
+ self.assertIsInstance(TextField().get_prep_value(lazy_func()), str)
lazy_func = lazy(lambda: 0, int)
- self.assertIsInstance(TextField().get_prep_value(lazy_func()), six.text_type)
+ self.assertIsInstance(TextField().get_prep_value(lazy_func()), str)
def test_TimeField(self):
lazy_func = lazy(lambda: datetime.datetime.now().time(), datetime.time)
self.assertIsInstance(TimeField().get_prep_value(lazy_func()), datetime.time)
def test_URLField(self):
- lazy_func = lazy(lambda: 'http://domain.com', six.text_type)
- self.assertIsInstance(URLField().get_prep_value(lazy_func()), six.text_type)
+ lazy_func = lazy(lambda: 'http://domain.com', str)
+ self.assertIsInstance(URLField().get_prep_value(lazy_func()), str)
diff --git a/tests/model_forms/models.py b/tests/model_forms/models.py
index 333a6050ab..0914fc2587 100644
--- a/tests/model_forms/models.py
+++ b/tests/model_forms/models.py
@@ -15,7 +15,6 @@ from django.core import validators
from django.core.exceptions import ValidationError
from django.core.files.storage import FileSystemStorage
from django.db import models
-from django.utils import six
from django.utils._os import upath
from django.utils.six.moves import range
@@ -319,7 +318,7 @@ class BigInt(models.Model):
biggie = models.BigIntegerField()
def __str__(self):
- return six.text_type(self.biggie)
+ return str(self.biggie)
class MarkupField(models.CharField):
diff --git a/tests/model_forms/tests.py b/tests/model_forms/tests.py
index 0fc516b55c..27143e97f4 100644
--- a/tests/model_forms/tests.py
+++ b/tests/model_forms/tests.py
@@ -1162,7 +1162,7 @@ class ModelFormBasicTests(TestCase):
# inserted as 'initial' data in each Field.
f = RoykoForm(auto_id=False, instance=self.w_royko)
self.assertHTMLEqual(
- six.text_type(f),
+ str(f),
'''<tr><th>Name:</th><td><input type="text" name="name" value="Mike Royko" maxlength="50" required /><br />
<span class="helptext">Use both first and last names.</span></td></tr>'''
)
@@ -1204,7 +1204,7 @@ class ModelFormBasicTests(TestCase):
'headline': 'Test headline',
'slug': 'test-headline',
'pub_date': '1984-02-06',
- 'writer': six.text_type(self.w_royko.pk),
+ 'writer': str(self.w_royko.pk),
'article': 'Hello.'
}, instance=art)
self.assertEqual(f.errors, {})
@@ -1294,7 +1294,7 @@ class ModelFormBasicTests(TestCase):
# fields with the 'choices' attribute are represented by a ChoiceField.
f = ArticleForm(auto_id=False)
self.assertHTMLEqual(
- six.text_type(f),
+ str(f),
'''<tr><th>Headline:</th><td><input type="text" name="headline" maxlength="50" required /></td></tr>
<tr><th>Slug:</th><td><input type="text" name="slug" maxlength="50" required /></td></tr>
<tr><th>Pub date:</th><td><input type="text" name="pub_date" required /></td></tr>
@@ -1360,7 +1360,7 @@ class ModelFormBasicTests(TestCase):
f = PartialArticleForm(auto_id=False)
self.assertHTMLEqual(
- six.text_type(f),
+ str(f),
'''<tr><th>Headline:</th><td><input type="text" name="headline" maxlength="50" required /></td></tr>
<tr><th>Pub date:</th><td><input type="text" name="pub_date" required /></td></tr>''')
@@ -1398,9 +1398,9 @@ class ModelFormBasicTests(TestCase):
'headline': 'New headline',
'slug': 'new-headline',
'pub_date': '1988-01-04',
- 'writer': six.text_type(self.w_royko.pk),
+ 'writer': str(self.w_royko.pk),
'article': 'Hello.',
- 'categories': [six.text_type(self.c1.id), six.text_type(self.c2.id)]
+ 'categories': [str(self.c1.id), str(self.c2.id)]
}
# Create a new article, with categories, via the form.
f = ArticleForm(form_data)
@@ -1427,7 +1427,7 @@ class ModelFormBasicTests(TestCase):
# Create a new article, with categories, via the form, but use commit=False.
# The m2m data won't be saved until save_m2m() is invoked on the form.
- form_data['categories'] = [six.text_type(self.c1.id), six.text_type(self.c2.id)]
+ form_data['categories'] = [str(self.c1.id), str(self.c2.id)]
f = ArticleForm(form_data)
new_art = f.save(commit=False)
@@ -1979,12 +1979,12 @@ class ModelOneToOneFieldTests(TestCase):
)
data = {
- 'writer': six.text_type(self.w_woodward.pk),
+ 'writer': str(self.w_woodward.pk),
'age': '65',
}
form = WriterProfileForm(data)
instance = form.save()
- self.assertEqual(six.text_type(instance), 'Bob Woodward is 65')
+ self.assertEqual(str(instance), 'Bob Woodward is 65')
form = WriterProfileForm(instance=instance)
self.assertHTMLEqual(
@@ -2062,14 +2062,14 @@ class FileAndImageFieldTests(TestCase):
fields = '__all__'
form = DocumentForm()
- self.assertIn('name="myfile"', six.text_type(form))
- self.assertNotIn('myfile-clear', six.text_type(form))
+ self.assertIn('name="myfile"', str(form))
+ self.assertNotIn('myfile-clear', str(form))
form = DocumentForm(files={'myfile': SimpleUploadedFile('something.txt', b'content')})
self.assertTrue(form.is_valid())
doc = form.save(commit=False)
self.assertEqual(doc.myfile.name, 'something.txt')
form = DocumentForm(instance=doc)
- self.assertIn('myfile-clear', six.text_type(form))
+ self.assertIn('myfile-clear', str(form))
form = DocumentForm(instance=doc, data={'myfile-clear': 'true'})
doc = form.save(commit=False)
self.assertFalse(doc.myfile)
@@ -2094,7 +2094,7 @@ class FileAndImageFieldTests(TestCase):
self.assertTrue(not form.is_valid())
self.assertEqual(form.errors['myfile'],
['Please either submit a file or check the clear checkbox, not both.'])
- rendered = six.text_type(form)
+ rendered = str(form)
self.assertIn('something.txt', rendered)
self.assertIn('myfile-clear', rendered)
@@ -2469,7 +2469,7 @@ class OtherModelFormTests(TestCase):
# the ModelForm.
f = ModelFormWithMedia()
self.assertHTMLEqual(
- six.text_type(f.media),
+ str(f.media),
'''<link href="/some/form/css" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/some/form/javascript"></script>'''
)
@@ -2520,7 +2520,7 @@ class OtherModelFormTests(TestCase):
(22, 'Pear')))
form = InventoryForm(instance=core)
- self.assertHTMLEqual(six.text_type(form['parent']), '''<select name="parent" id="id_parent">
+ self.assertHTMLEqual(str(form['parent']), '''<select name="parent" id="id_parent">
<option value="">---------</option>
<option value="86" selected>Apple</option>
<option value="87">Core</option>
@@ -2543,7 +2543,7 @@ class OtherModelFormTests(TestCase):
['description', 'url'])
self.assertHTMLEqual(
- six.text_type(CategoryForm()),
+ str(CategoryForm()),
'''<tr><th><label for="id_description">Description:</label></th>
<td><input type="text" name="description" id="id_description" required /></td></tr>
<tr><th><label for="id_url">The URL:</label></th>
@@ -2564,7 +2564,7 @@ class OtherModelFormTests(TestCase):
self.assertEqual(list(CustomFieldForExclusionForm.base_fields),
['name'])
self.assertHTMLEqual(
- six.text_type(CustomFieldForExclusionForm()),
+ str(CustomFieldForExclusionForm()),
'''<tr><th><label for="id_name">Name:</label></th>
<td><input id="id_name" type="text" name="name" maxlength="10" required /></td></tr>'''
)
diff --git a/tests/model_formsets/models.py b/tests/model_formsets/models.py
index b7b1f1edb9..744a7f6019 100644
--- a/tests/model_formsets/models.py
+++ b/tests/model_formsets/models.py
@@ -2,7 +2,6 @@ import datetime
import uuid
from django.db import models
-from django.utils import six
class Author(models.Model):
@@ -172,7 +171,7 @@ class Revision(models.Model):
unique_together = (("repository", "revision"),)
def __str__(self):
- return "%s (%s)" % (self.revision, six.text_type(self.repository))
+ return "%s (%s)" % (self.revision, str(self.repository))
# models for testing callable defaults (see bug #7975). If you define a model
diff --git a/tests/model_formsets/tests.py b/tests/model_formsets/tests.py
index b928944097..832dbe63ee 100644
--- a/tests/model_formsets/tests.py
+++ b/tests/model_formsets/tests.py
@@ -11,7 +11,6 @@ from django.forms.models import (
modelformset_factory,
)
from django.test import TestCase, skipUnlessDBFeature
-from django.utils import six
from .models import (
AlternateBook, Author, AuthorMeeting, BetterAuthor, Book, BookWithCustomPK,
@@ -54,11 +53,11 @@ class DeletionTests(TestCase):
'form-TOTAL_FORMS': '3',
'form-INITIAL_FORMS': '1',
'form-MAX_NUM_FORMS': '0',
- 'form-0-id': six.text_type(poet.id),
+ 'form-0-id': str(poet.id),
'form-0-name': 'test',
'form-1-id': '',
'form-1-name': 'x' * 1000, # Too long
- 'form-2-id': six.text_type(poet.id), # Violate unique constraint
+ 'form-2-id': str(poet.id), # Violate unique constraint
'form-2-name': 'test2',
}
formset = PoetFormSet(data, queryset=Poet.objects.all())
@@ -87,7 +86,7 @@ class DeletionTests(TestCase):
'form-TOTAL_FORMS': '1',
'form-INITIAL_FORMS': '1',
'form-MAX_NUM_FORMS': '0',
- 'form-0-id': six.text_type(poet.id),
+ 'form-0-id': str(poet.id),
'form-0-name': 'x' * 1000,
}
formset = PoetFormSet(data, queryset=Poet.objects.all())
@@ -1109,7 +1108,7 @@ class ModelFormsetTest(TestCase):
'owner_set-TOTAL_FORMS': '3',
'owner_set-INITIAL_FORMS': '1',
'owner_set-MAX_NUM_FORMS': '',
- 'owner_set-0-auto_id': six.text_type(owner1.auto_id),
+ 'owner_set-0-auto_id': str(owner1.auto_id),
'owner_set-0-name': 'Joe Perry',
'owner_set-1-auto_id': '',
'owner_set-1-name': 'Jack Berry',
@@ -1184,7 +1183,7 @@ class ModelFormsetTest(TestCase):
'ownerprofile-TOTAL_FORMS': '1',
'ownerprofile-INITIAL_FORMS': '1',
'ownerprofile-MAX_NUM_FORMS': '1',
- 'ownerprofile-0-owner': six.text_type(owner1.auto_id),
+ 'ownerprofile-0-owner': str(owner1.auto_id),
'ownerprofile-0-age': '55',
}
formset = FormSet(data, instance=owner1)
@@ -1383,8 +1382,8 @@ class ModelFormsetTest(TestCase):
'membership_set-TOTAL_FORMS': '1',
'membership_set-INITIAL_FORMS': '0',
'membership_set-MAX_NUM_FORMS': '',
- 'membership_set-0-date_joined': six.text_type(now.strftime('%Y-%m-%d %H:%M:%S')),
- 'initial-membership_set-0-date_joined': six.text_type(now.strftime('%Y-%m-%d %H:%M:%S')),
+ 'membership_set-0-date_joined': now.strftime('%Y-%m-%d %H:%M:%S'),
+ 'initial-membership_set-0-date_joined': now.strftime('%Y-%m-%d %H:%M:%S'),
'membership_set-0-karma': '',
}
formset = FormSet(data, instance=person)
@@ -1397,8 +1396,8 @@ class ModelFormsetTest(TestCase):
'membership_set-TOTAL_FORMS': '1',
'membership_set-INITIAL_FORMS': '0',
'membership_set-MAX_NUM_FORMS': '',
- 'membership_set-0-date_joined': six.text_type(one_day_later.strftime('%Y-%m-%d %H:%M:%S')),
- 'initial-membership_set-0-date_joined': six.text_type(now.strftime('%Y-%m-%d %H:%M:%S')),
+ 'membership_set-0-date_joined': one_day_later.strftime('%Y-%m-%d %H:%M:%S'),
+ 'initial-membership_set-0-date_joined': now.strftime('%Y-%m-%d %H:%M:%S'),
'membership_set-0-karma': '',
}
formset = FormSet(filled_data, instance=person)
@@ -1429,9 +1428,9 @@ class ModelFormsetTest(TestCase):
'membership_set-TOTAL_FORMS': '1',
'membership_set-INITIAL_FORMS': '0',
'membership_set-MAX_NUM_FORMS': '',
- 'membership_set-0-date_joined_0': six.text_type(now.strftime('%Y-%m-%d')),
- 'membership_set-0-date_joined_1': six.text_type(now.strftime('%H:%M:%S')),
- 'initial-membership_set-0-date_joined': six.text_type(now.strftime('%Y-%m-%d %H:%M:%S')),
+ 'membership_set-0-date_joined_0': now.strftime('%Y-%m-%d'),
+ 'membership_set-0-date_joined_1': now.strftime('%H:%M:%S'),
+ 'initial-membership_set-0-date_joined': now.strftime('%Y-%m-%d %H:%M:%S'),
'membership_set-0-karma': '',
}
formset = FormSet(data, instance=person)
diff --git a/tests/model_formsets_regress/tests.py b/tests/model_formsets_regress/tests.py
index a9b50b3699..5bad8a741a 100644
--- a/tests/model_formsets_regress/tests.py
+++ b/tests/model_formsets_regress/tests.py
@@ -6,7 +6,6 @@ from django.forms.models import (
)
from django.forms.utils import ErrorDict, ErrorList
from django.test import TestCase
-from django.utils import six
from .models import (
Host, Manager, Network, ProfileNetwork, Restaurant, User, UserProfile,
@@ -56,7 +55,7 @@ class InlineFormsetTests(TestCase):
'usersite_set-TOTAL_FORMS': '1',
'usersite_set-INITIAL_FORMS': '1',
'usersite_set-MAX_NUM_FORMS': '0',
- 'usersite_set-0-id': six.text_type(usersite[0]['id']),
+ 'usersite_set-0-id': str(usersite[0]['id']),
'usersite_set-0-data': '11',
'usersite_set-0-user': 'apollo13'
}
@@ -74,7 +73,7 @@ class InlineFormsetTests(TestCase):
'usersite_set-TOTAL_FORMS': '2',
'usersite_set-INITIAL_FORMS': '1',
'usersite_set-MAX_NUM_FORMS': '0',
- 'usersite_set-0-id': six.text_type(usersite[0]['id']),
+ 'usersite_set-0-id': str(usersite[0]['id']),
'usersite_set-0-data': '11',
'usersite_set-0-user': 'apollo13',
'usersite_set-1-data': '42',
@@ -129,7 +128,7 @@ class InlineFormsetTests(TestCase):
'manager_set-TOTAL_FORMS': '1',
'manager_set-INITIAL_FORMS': '1',
'manager_set-MAX_NUM_FORMS': '0',
- 'manager_set-0-id': six.text_type(manager[0]['id']),
+ 'manager_set-0-id': str(manager[0]['id']),
'manager_set-0-name': 'Terry Gilliam'
}
form_set = FormSet(data, instance=restaurant)
@@ -145,7 +144,7 @@ class InlineFormsetTests(TestCase):
'manager_set-TOTAL_FORMS': '2',
'manager_set-INITIAL_FORMS': '1',
'manager_set-MAX_NUM_FORMS': '0',
- 'manager_set-0-id': six.text_type(manager[0]['id']),
+ 'manager_set-0-id': str(manager[0]['id']),
'manager_set-0-name': 'Terry Gilliam',
'manager_set-1-name': 'John Cleese'
}
@@ -226,7 +225,7 @@ class InlineFormsetTests(TestCase):
'host_set-TOTAL_FORMS': '2',
'host_set-INITIAL_FORMS': '1',
'host_set-MAX_NUM_FORMS': '0',
- 'host_set-0-id': six.text_type(host1.id),
+ 'host_set-0-id': str(host1.id),
'host_set-0-hostname': 'tranquility.hub.dal.net',
'host_set-1-hostname': 'matrix.de.eu.dal.net'
}
@@ -505,7 +504,7 @@ class RedeleteTests(TestCase):
'usersite_set-TOTAL_FORMS': '1',
'usersite_set-INITIAL_FORMS': '1',
'usersite_set-MAX_NUM_FORMS': '1',
- 'usersite_set-0-id': six.text_type(us.pk),
+ 'usersite_set-0-id': str(us.pk),
'usersite_set-0-data': '7',
'usersite_set-0-user': 'foo',
'usersite_set-0-DELETE': '1'
@@ -531,7 +530,7 @@ class RedeleteTests(TestCase):
'usersite_set-TOTAL_FORMS': '1',
'usersite_set-INITIAL_FORMS': '1',
'usersite_set-MAX_NUM_FORMS': '1',
- 'usersite_set-0-id': six.text_type(us.pk),
+ 'usersite_set-0-id': str(us.pk),
'usersite_set-0-data': '7',
'usersite_set-0-user': 'foo',
'usersite_set-0-DELETE': '1'
diff --git a/tests/model_inheritance/tests.py b/tests/model_inheritance/tests.py
index 8bb74d7ccb..feff4a1407 100644
--- a/tests/model_inheritance/tests.py
+++ b/tests/model_inheritance/tests.py
@@ -4,7 +4,6 @@ from django.core.exceptions import FieldError, ValidationError
from django.db import connection, models
from django.test import SimpleTestCase, TestCase
from django.test.utils import CaptureQueriesContext, isolate_apps
-from django.utils import six
from .models import (
Base, Chef, CommonInfo, GrandChild, GrandParent, ItalianRestaurant,
@@ -25,8 +24,8 @@ class ModelInheritanceTests(TestCase):
s = Student.objects.create(name="Pebbles", age=5, school_class="1B")
- self.assertEqual(six.text_type(w1), "Worker Fred")
- self.assertEqual(six.text_type(s), "Student Pebbles")
+ self.assertEqual(str(w1), "Worker Fred")
+ self.assertEqual(str(s), "Student Pebbles")
# The children inherit the Meta class of their parents (if they don't
# specify their own).
diff --git a/tests/model_regress/tests.py b/tests/model_regress/tests.py
index 808729979f..e9374d9d93 100644
--- a/tests/model_regress/tests.py
+++ b/tests/model_regress/tests.py
@@ -5,7 +5,6 @@ from django.core.exceptions import ValidationError
from django.db import router
from django.db.models.sql import InsertQuery
from django.test import TestCase, skipUnlessDBFeature
-from django.utils import six
from django.utils.timezone import get_fixed_timezone
from .models import (
@@ -53,10 +52,9 @@ class ModelTests(TestCase):
# An empty choice field should return None for the display name.
self.assertIs(a.get_status_display(), None)
- # Empty strings should be returned as Unicode
+ # Empty strings should be returned as string
a = Article.objects.get(pk=a.pk)
self.assertEqual(a.misc_data, '')
- self.assertIs(type(a.misc_data), six.text_type)
def test_long_textfield(self):
# TextFields can hold more than 4000 characters (this was broken in
@@ -186,7 +184,7 @@ class ModelTests(TestCase):
# Check Department and Worker (non-default PK type)
d = Department.objects.create(id=10, name="IT")
w = Worker.objects.create(department=d, name="Full-time")
- self.assertEqual(six.text_type(w), "Full-time")
+ self.assertEqual(str(w), "Full-time")
def test_broken_unicode(self):
# Models with broken unicode methods should still have a printable repr
diff --git a/tests/order_with_respect_to/models.py b/tests/order_with_respect_to/models.py
index 8f50b42252..7f6cd8f8fd 100644
--- a/tests/order_with_respect_to/models.py
+++ b/tests/order_with_respect_to/models.py
@@ -3,7 +3,6 @@ Tests for the order_with_respect_to Meta attribute.
"""
from django.db import models
-from django.utils import six
class Question(models.Model):
@@ -18,7 +17,7 @@ class Answer(models.Model):
order_with_respect_to = 'question'
def __str__(self):
- return six.text_type(self.text)
+ return self.text
class Post(models.Model):
diff --git a/tests/pagination/tests.py b/tests/pagination/tests.py
index fe967631ab..cc3a0efbc2 100644
--- a/tests/pagination/tests.py
+++ b/tests/pagination/tests.py
@@ -256,7 +256,7 @@ class ModelPaginationTests(TestCase):
def test_first_page(self):
paginator = Paginator(Article.objects.order_by('id'), 5)
p = paginator.page(1)
- self.assertEqual("<Page 1 of 2>", six.text_type(p))
+ self.assertEqual("<Page 1 of 2>", str(p))
self.assertQuerysetEqual(p.object_list, [
"<Article: Article 1>",
"<Article: Article 2>",
@@ -276,7 +276,7 @@ class ModelPaginationTests(TestCase):
def test_last_page(self):
paginator = Paginator(Article.objects.order_by('id'), 5)
p = paginator.page(2)
- self.assertEqual("<Page 2 of 2>", six.text_type(p))
+ self.assertEqual("<Page 2 of 2>", str(p))
self.assertQuerysetEqual(p.object_list, [
"<Article: Article 6>",
"<Article: Article 7>",
diff --git a/tests/prefetch_related/tests.py b/tests/prefetch_related/tests.py
index 126a8bc035..33456069aa 100644
--- a/tests/prefetch_related/tests.py
+++ b/tests/prefetch_related/tests.py
@@ -5,7 +5,6 @@ from django.db.models import Prefetch, QuerySet
from django.db.models.query import get_prefetcher
from django.test import TestCase, override_settings
from django.test.utils import CaptureQueriesContext
-from django.utils import six
from django.utils.encoding import force_text
from .models import (
@@ -130,7 +129,7 @@ class PrefetchRelatedTests(TestCase):
"""A m2m can be followed through another m2m."""
with self.assertNumQueries(3):
qs = Author.objects.prefetch_related('books__read_by')
- lists = [[[six.text_type(r) for r in b.read_by.all()]
+ lists = [[[str(r) for r in b.read_by.all()]
for b in a.books.all()]
for a in qs]
self.assertEqual(lists, [
@@ -143,7 +142,7 @@ class PrefetchRelatedTests(TestCase):
def test_overriding_prefetch(self):
with self.assertNumQueries(3):
qs = Author.objects.prefetch_related('books', 'books__read_by')
- lists = [[[six.text_type(r) for r in b.read_by.all()]
+ lists = [[[str(r) for r in b.read_by.all()]
for b in a.books.all()]
for a in qs]
self.assertEqual(lists, [
@@ -154,7 +153,7 @@ class PrefetchRelatedTests(TestCase):
])
with self.assertNumQueries(3):
qs = Author.objects.prefetch_related('books__read_by', 'books')
- lists = [[[six.text_type(r) for r in b.read_by.all()]
+ lists = [[[str(r) for r in b.read_by.all()]
for b in a.books.all()]
for a in qs]
self.assertEqual(lists, [
@@ -171,7 +170,7 @@ class PrefetchRelatedTests(TestCase):
# Need a double
with self.assertNumQueries(3):
author = Author.objects.prefetch_related('books__read_by').get(name="Charlotte")
- lists = [[six.text_type(r) for r in b.read_by.all()] for b in author.books.all()]
+ lists = [[str(r) for r in b.read_by.all()] for b in author.books.all()]
self.assertEqual(lists, [["Amy"], ["Belinda"]]) # Poems, Jane Eyre
def test_foreign_key_then_m2m(self):
@@ -181,7 +180,7 @@ class PrefetchRelatedTests(TestCase):
"""
with self.assertNumQueries(2):
qs = Author.objects.select_related('first_book').prefetch_related('first_book__read_by')
- lists = [[six.text_type(r) for r in a.first_book.read_by.all()]
+ lists = [[str(r) for r in a.first_book.read_by.all()]
for a in qs]
self.assertEqual(lists, [["Amy"], ["Amy"], ["Amy"], ["Amy", "Belinda"]])
@@ -758,7 +757,7 @@ class DefaultManagerTests(TestCase):
# qualifications, since this will do one query per teacher.
qs = Department.objects.prefetch_related('teachers')
depts = "".join("%s department: %s\n" %
- (dept.name, ", ".join(six.text_type(t) for t in dept.teachers.all()))
+ (dept.name, ", ".join(str(t) for t in dept.teachers.all()))
for dept in qs)
self.assertEqual(depts,
@@ -895,8 +894,8 @@ class MultiTableInheritanceTest(TestCase):
def test_foreignkey(self):
with self.assertNumQueries(2):
qs = AuthorWithAge.objects.prefetch_related('addresses')
- addresses = [[six.text_type(address) for address in obj.addresses.all()] for obj in qs]
- self.assertEqual(addresses, [[six.text_type(self.author_address)], [], []])
+ addresses = [[str(address) for address in obj.addresses.all()] for obj in qs]
+ self.assertEqual(addresses, [[str(self.author_address)], [], []])
def test_foreignkey_to_inherited(self):
with self.assertNumQueries(2):
@@ -907,16 +906,16 @@ class MultiTableInheritanceTest(TestCase):
def test_m2m_to_inheriting_model(self):
qs = AuthorWithAge.objects.prefetch_related('books_with_year')
with self.assertNumQueries(2):
- lst = [[six.text_type(book) for book in author.books_with_year.all()] for author in qs]
+ lst = [[str(book) for book in author.books_with_year.all()] for author in qs]
qs = AuthorWithAge.objects.all()
- lst2 = [[six.text_type(book) for book in author.books_with_year.all()] for author in qs]
+ lst2 = [[str(book) for book in author.books_with_year.all()] for author in qs]
self.assertEqual(lst, lst2)
qs = BookWithYear.objects.prefetch_related('aged_authors')
with self.assertNumQueries(2):
- lst = [[six.text_type(author) for author in book.aged_authors.all()] for book in qs]
+ lst = [[str(author) for author in book.aged_authors.all()] for book in qs]
qs = BookWithYear.objects.all()
- lst2 = [[six.text_type(author) for author in book.aged_authors.all()] for book in qs]
+ lst2 = [[str(author) for author in book.aged_authors.all()] for book in qs]
self.assertEqual(lst, lst2)
def test_parent_link_prefetch(self):
@@ -953,23 +952,23 @@ class ForeignKeyToFieldTest(TestCase):
def test_foreignkey(self):
with self.assertNumQueries(2):
qs = Author.objects.prefetch_related('addresses')
- addresses = [[six.text_type(address) for address in obj.addresses.all()]
+ addresses = [[str(address) for address in obj.addresses.all()]
for obj in qs]
- self.assertEqual(addresses, [[six.text_type(self.author_address)], [], []])
+ self.assertEqual(addresses, [[str(self.author_address)], [], []])
def test_m2m(self):
with self.assertNumQueries(3):
qs = Author.objects.all().prefetch_related('favorite_authors', 'favors_me')
favorites = [(
- [six.text_type(i_like) for i_like in author.favorite_authors.all()],
- [six.text_type(likes_me) for likes_me in author.favors_me.all()]
+ [str(i_like) for i_like in author.favorite_authors.all()],
+ [str(likes_me) for likes_me in author.favors_me.all()]
) for author in qs]
self.assertEqual(
favorites,
[
- ([six.text_type(self.author2)], [six.text_type(self.author3)]),
- ([six.text_type(self.author3)], [six.text_type(self.author1)]),
- ([six.text_type(self.author1)], [six.text_type(self.author2)])
+ ([str(self.author2)], [str(self.author3)]),
+ ([str(self.author3)], [str(self.author1)]),
+ ([str(self.author1)], [str(self.author2)])
]
)
diff --git a/tests/queries/models.py b/tests/queries/models.py
index 4d5ed14ff0..8c20e76dee 100644
--- a/tests/queries/models.py
+++ b/tests/queries/models.py
@@ -4,7 +4,6 @@ Various complex queries that have been problematic in the past.
import threading
from django.db import models
-from django.utils import six
class DumbCategory(models.Model):
@@ -142,7 +141,7 @@ class Number(models.Model):
num = models.IntegerField()
def __str__(self):
- return six.text_type(self.num)
+ return str(self.num)
# Symmetrical m2m field with a normal field using the reverse accessor name
# ("valid").
diff --git a/tests/redirects_tests/tests.py b/tests/redirects_tests/tests.py
index 29c88bd1df..558bbaaf7e 100644
--- a/tests/redirects_tests/tests.py
+++ b/tests/redirects_tests/tests.py
@@ -5,7 +5,6 @@ from django.contrib.redirects.models import Redirect
from django.contrib.sites.models import Site
from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase, modify_settings, override_settings
-from django.utils import six
@modify_settings(MIDDLEWARE={'append': 'django.contrib.redirects.middleware.RedirectFallbackMiddleware'})
@@ -17,7 +16,7 @@ class RedirectTests(TestCase):
def test_model(self):
r1 = Redirect.objects.create(site=self.site, old_path='/initial', new_path='/new_target')
- self.assertEqual(six.text_type(r1), "/initial ---> /new_target")
+ self.assertEqual(str(r1), "/initial ---> /new_target")
def test_redirect(self):
Redirect.objects.create(site=self.site, old_path='/initial', new_path='/new_target')
diff --git a/tests/resolve_url/tests.py b/tests/resolve_url/tests.py
index 73556a93be..5a90282afa 100644
--- a/tests/resolve_url/tests.py
+++ b/tests/resolve_url/tests.py
@@ -1,7 +1,6 @@
from django.shortcuts import resolve_url
from django.test import SimpleTestCase, override_settings
from django.urls import NoReverseMatch, reverse_lazy
-from django.utils import six
from .models import UnimportantThing
from .urls import some_view
@@ -57,7 +56,7 @@ class ResolveUrlTests(SimpleTestCase):
string.
"""
resolved_url = resolve_url(reverse_lazy('some-view'))
- self.assertIsInstance(resolved_url, six.text_type)
+ self.assertIsInstance(resolved_url, str)
self.assertEqual('/some-url/', resolved_url)
def test_valid_view_name(self):
diff --git a/tests/runtests.py b/tests/runtests.py
index 82cd8207ba..6e86bf7a93 100755
--- a/tests/runtests.py
+++ b/tests/runtests.py
@@ -17,7 +17,6 @@ from django.test import TestCase, TransactionTestCase
from django.test.runner import default_test_processes
from django.test.selenium import SeleniumTestCaseBase
from django.test.utils import get_runner
-from django.utils import six
from django.utils._os import upath
from django.utils.deprecation import (
RemovedInDjango21Warning, RemovedInDjango30Warning,
@@ -42,10 +41,8 @@ TMPDIR = tempfile.mkdtemp(prefix='django_')
# so that children processes inherit it.
tempfile.tempdir = os.environ['TMPDIR'] = TMPDIR
-# Removing the temporary TMPDIR. Ensure we pass in unicode so that it will
-# successfully remove temp trees containing non-ASCII filenames on Windows.
-# (We're assuming the temp dir name itself only contains ASCII characters.)
-atexit.register(shutil.rmtree, six.text_type(TMPDIR))
+# Removing the temporary TMPDIR.
+atexit.register(shutil.rmtree, TMPDIR)
SUBDIRS_TO_SKIP = [
diff --git a/tests/save_delete_hooks/tests.py b/tests/save_delete_hooks/tests.py
index e0cb2f51ab..874cb7eb72 100644
--- a/tests/save_delete_hooks/tests.py
+++ b/tests/save_delete_hooks/tests.py
@@ -1,5 +1,4 @@
from django.test import TestCase
-from django.utils import six
from .models import Person
@@ -18,7 +17,7 @@ class SaveDeleteHookTests(TestCase):
Person.objects.all(), [
"John Smith",
],
- six.text_type
+ str
)
p.delete()
diff --git a/tests/select_related_regress/tests.py b/tests/select_related_regress/tests.py
index bb5f7774a3..753114a6d2 100644
--- a/tests/select_related_regress/tests.py
+++ b/tests/select_related_regress/tests.py
@@ -1,5 +1,4 @@
from django.test import TestCase
-from django.utils import six
from .models import (
A, B, Building, C, Chick, Child, Class, Client, ClientStatus, Connection,
@@ -35,7 +34,7 @@ class SelectRelatedRegressTests(TestCase):
connections = Connection.objects.filter(start__device__building=b, end__device__building=b).order_by('id')
self.assertEqual(
- [(c.id, six.text_type(c.start), six.text_type(c.end)) for c in connections],
+ [(c.id, str(c.start), str(c.end)) for c in connections],
[(c1.id, 'router/4', 'switch/7'), (c2.id, 'switch/7', 'server/1')]
)
@@ -46,7 +45,7 @@ class SelectRelatedRegressTests(TestCase):
.order_by('id')
)
self.assertEqual(
- [(c.id, six.text_type(c.start), six.text_type(c.end)) for c in connections],
+ [(c.id, str(c.start), str(c.end)) for c in connections],
[(c1.id, 'router/4', 'switch/7'), (c2.id, 'switch/7', 'server/1')]
)
diff --git a/tests/serializers/models/base.py b/tests/serializers/models/base.py
index aa55b87c61..9421578478 100644
--- a/tests/serializers/models/base.py
+++ b/tests/serializers/models/base.py
@@ -7,7 +7,6 @@ Serialization
from decimal import Decimal
from django.db import models
-from django.utils import six
class CategoryMetaDataManager(models.Manager):
@@ -118,7 +117,7 @@ class TeamField(models.CharField):
super(TeamField, self).__init__(max_length=100)
def get_db_prep_save(self, value, connection):
- return six.text_type(value.title)
+ return str(value.title)
def to_python(self, value):
if isinstance(value, Team):
diff --git a/tests/serializers/test_xml.py b/tests/serializers/test_xml.py
index 71b38d48fa..ea9677d87f 100644
--- a/tests/serializers/test_xml.py
+++ b/tests/serializers/test_xml.py
@@ -3,7 +3,6 @@ from xml.dom import minidom
from django.core import serializers
from django.core.serializers.xml_serializer import DTDForbidden
from django.test import TestCase, TransactionTestCase
-from django.utils import six
from .tests import SerializersTestBase, SerializersTransactionTestBase
@@ -34,7 +33,7 @@ class XmlSerializerTestCase(SerializersTestBase, TestCase):
def _comparison_value(value):
# The XML serializer handles everything as strings, so comparisons
# need to be performed on the stringified value
- return six.text_type(value)
+ return str(value)
@staticmethod
def _validate_output(serial_str):
diff --git a/tests/serializers/test_yaml.py b/tests/serializers/test_yaml.py
index 038227efea..f3988d7ff1 100644
--- a/tests/serializers/test_yaml.py
+++ b/tests/serializers/test_yaml.py
@@ -4,7 +4,6 @@ import unittest
from django.core import management, serializers
from django.core.serializers.base import DeserializationError
from django.test import SimpleTestCase, TestCase, TransactionTestCase
-from django.utils import six
from django.utils.six import StringIO
from .models import Author
@@ -147,7 +146,7 @@ class YamlSerializerTestCase(SerializersTestBase, TestCase):
# yaml.safe_load will return non-string objects for some
# of the fields we are interested in, this ensures that
# everything comes back as a string
- if isinstance(field_value, six.string_types):
+ if isinstance(field_value, str):
ret_list.append(field_value)
else:
ret_list.append(str(field_value))
diff --git a/tests/servers/tests.py b/tests/servers/tests.py
index ff1d4aff8c..ee0d8629cf 100644
--- a/tests/servers/tests.py
+++ b/tests/servers/tests.py
@@ -9,7 +9,6 @@ import socket
from django.test import LiveServerTestCase, override_settings
from django.utils._os import upath
from django.utils.http import urlencode
-from django.utils.six import text_type
from django.utils.six.moves.urllib.error import HTTPError
from django.utils.six.moves.urllib.request import urlopen
@@ -48,7 +47,7 @@ class LiveServerAddress(LiveServerBase):
cls.live_server_url_test = [cls.live_server_url]
def test_live_server_url_is_class_property(self):
- self.assertIsInstance(self.live_server_url_test[0], text_type)
+ self.assertIsInstance(self.live_server_url_test[0], str)
self.assertEqual(self.live_server_url_test[0], self.live_server_url)
diff --git a/tests/signals/tests.py b/tests/signals/tests.py
index 9cb470b8cf..88572ad44f 100644
--- a/tests/signals/tests.py
+++ b/tests/signals/tests.py
@@ -4,7 +4,6 @@ from django.db.models import signals
from django.dispatch import receiver
from django.test import TestCase, mock
from django.test.utils import isolate_apps
-from django.utils import six
from .models import Author, Book, Car, Person
@@ -160,7 +159,7 @@ class SignalTests(BaseSignalTest):
Person.objects.all(), [
"James Jones",
],
- six.text_type
+ str
)
finally:
signals.pre_delete.disconnect(pre_delete_handler)
diff --git a/tests/staticfiles_tests/cases.py b/tests/staticfiles_tests/cases.py
index f278e6a974..069402c6f6 100644
--- a/tests/staticfiles_tests/cases.py
+++ b/tests/staticfiles_tests/cases.py
@@ -7,7 +7,6 @@ from django.conf import settings
from django.core.management import call_command
from django.template import Context, Template
from django.test import SimpleTestCase, override_settings
-from django.utils import six
from django.utils.encoding import force_text
from .settings import TEST_SETTINGS
@@ -30,7 +29,7 @@ class BaseStaticFilesMixin(object):
self._get_file(filepath)
def render_template(self, template, **kwargs):
- if isinstance(template, six.string_types):
+ if isinstance(template, str):
template = Template(template)
return template.render(Context(**kwargs)).strip()
@@ -72,7 +71,7 @@ class CollectionTestCase(BaseStaticFilesMixin, SimpleTestCase):
self.patched_settings.enable()
self.run_collectstatic()
# Same comment as in runtests.teardown.
- self.addCleanup(shutil.rmtree, six.text_type(temp_dir))
+ self.addCleanup(shutil.rmtree, temp_dir)
def tearDown(self):
self.patched_settings.disable()
diff --git a/tests/staticfiles_tests/test_management.py b/tests/staticfiles_tests/test_management.py
index e8c00eb3f5..7d17f2abe1 100644
--- a/tests/staticfiles_tests/test_management.py
+++ b/tests/staticfiles_tests/test_management.py
@@ -166,7 +166,7 @@ class TestCollectionClear(CollectionTestCase):
self.assertFileNotFound('cleared.txt')
def test_dir_not_exists(self, **kwargs):
- shutil.rmtree(six.text_type(settings.STATIC_ROOT))
+ shutil.rmtree(settings.STATIC_ROOT)
super(TestCollectionClear, self).run_collectstatic(clear=True)
@override_settings(STATICFILES_STORAGE='staticfiles_tests.storage.PathNotImplementedStorage')
@@ -210,7 +210,7 @@ class TestInteractiveMessages(CollectionTestCase):
def test_no_warning_when_staticdir_does_not_exist(self):
stdout = six.StringIO()
- shutil.rmtree(six.text_type(settings.STATIC_ROOT))
+ shutil.rmtree(settings.STATIC_ROOT)
call_command('collectstatic', interactive=True, stdout=stdout)
output = force_text(stdout.getvalue())
self.assertNotIn(self.overwrite_warning_msg, output)
@@ -222,7 +222,7 @@ class TestInteractiveMessages(CollectionTestCase):
static_dir = tempfile.mkdtemp(prefix='collectstatic_empty_staticdir_test')
with override_settings(STATIC_ROOT=static_dir):
call_command('collectstatic', interactive=True, stdout=stdout)
- shutil.rmtree(six.text_type(static_dir))
+ shutil.rmtree(static_dir)
output = force_text(stdout.getvalue())
self.assertNotIn(self.overwrite_warning_msg, output)
self.assertNotIn(self.delete_warning_msg, output)
diff --git a/tests/staticfiles_tests/test_storage.py b/tests/staticfiles_tests/test_storage.py
index d1b7a49626..6333be7549 100644
--- a/tests/staticfiles_tests/test_storage.py
+++ b/tests/staticfiles_tests/test_storage.py
@@ -350,7 +350,7 @@ class TestCollectionManifestStorage(TestHashedFiles, CollectionTestCase):
self.patched_settings = self.settings(
STATICFILES_DIRS=settings.STATICFILES_DIRS + [temp_dir])
self.patched_settings.enable()
- self.addCleanup(shutil.rmtree, six.text_type(temp_dir))
+ self.addCleanup(shutil.rmtree, temp_dir)
self._manifest_strict = storage.staticfiles_storage.manifest_strict
def tearDown(self):
diff --git a/tests/template_tests/filter_tests/test_escape.py b/tests/template_tests/filter_tests/test_escape.py
index 6f28b972a2..22d5ca7d55 100644
--- a/tests/template_tests/filter_tests/test_escape.py
+++ b/tests/template_tests/filter_tests/test_escape.py
@@ -1,6 +1,5 @@
from django.template.defaultfilters import escape
from django.test import SimpleTestCase
-from django.utils import six
from django.utils.functional import Promise, lazy
from django.utils.safestring import mark_safe
@@ -34,7 +33,7 @@ class EscapeTests(SimpleTestCase):
self.assertEqual(output, "x&amp;y")
def test_escape_lazy_string(self):
- add_html = lazy(lambda string: string + 'special characters > here', six.text_type)
+ add_html = lazy(lambda string: string + 'special characters > here', str)
escaped = escape(add_html('<some html & '))
self.assertIsInstance(escaped, Promise)
self.assertEqual(escaped, '&lt;some html &amp; special characters &gt; here')
diff --git a/tests/template_tests/filter_tests/test_escapejs.py b/tests/template_tests/filter_tests/test_escapejs.py
index 3b038726b2..9aa98819e1 100644
--- a/tests/template_tests/filter_tests/test_escapejs.py
+++ b/tests/template_tests/filter_tests/test_escapejs.py
@@ -1,6 +1,5 @@
from django.template.defaultfilters import escapejs_filter
from django.test import SimpleTestCase
-from django.utils import six
from django.utils.functional import lazy
from ..utils import setup
@@ -53,7 +52,7 @@ class FunctionTests(SimpleTestCase):
)
def test_lazy_string(self):
- append_script = lazy(lambda string: r'<script>this</script>' + string, six.text_type)
+ append_script = lazy(lambda string: r'<script>this</script>' + string, str)
self.assertEqual(
escapejs_filter(append_script('whitespace: \r\n\t\v\f\b')),
'\\u003Cscript\\u003Ethis\\u003C/script\\u003E'
diff --git a/tests/template_tests/filter_tests/test_floatformat.py b/tests/template_tests/filter_tests/test_floatformat.py
index d4a4526d1d..8474238f21 100644
--- a/tests/template_tests/filter_tests/test_floatformat.py
+++ b/tests/template_tests/filter_tests/test_floatformat.py
@@ -2,7 +2,6 @@ from decimal import Decimal, localcontext
from django.template.defaultfilters import floatformat
from django.test import SimpleTestCase
-from django.utils import six
from django.utils.safestring import mark_safe
from ..utils import setup
@@ -64,13 +63,13 @@ class FunctionTests(SimpleTestCase):
def test_infinity(self):
pos_inf = float(1e30000)
- self.assertEqual(floatformat(pos_inf), six.text_type(pos_inf))
+ self.assertEqual(floatformat(pos_inf), str(pos_inf))
neg_inf = float(-1e30000)
- self.assertEqual(floatformat(neg_inf), six.text_type(neg_inf))
+ self.assertEqual(floatformat(neg_inf), str(neg_inf))
nan = pos_inf / pos_inf
- self.assertEqual(floatformat(nan), six.text_type(nan))
+ self.assertEqual(floatformat(nan), str(nan))
def test_float_dunder_method(self):
class FloatWrapper(object):
diff --git a/tests/template_tests/filter_tests/test_linebreaks.py b/tests/template_tests/filter_tests/test_linebreaks.py
index 50a66f3c47..0f3cd7a117 100644
--- a/tests/template_tests/filter_tests/test_linebreaks.py
+++ b/tests/template_tests/filter_tests/test_linebreaks.py
@@ -1,6 +1,5 @@
from django.template.defaultfilters import linebreaks_filter
from django.test import SimpleTestCase
-from django.utils import six
from django.utils.functional import lazy
from django.utils.safestring import mark_safe
@@ -54,7 +53,7 @@ class FunctionTests(SimpleTestCase):
)
def test_lazy_string_input(self):
- add_header = lazy(lambda string: 'Header\n\n' + string, six.text_type)
+ add_header = lazy(lambda string: 'Header\n\n' + string, str)
self.assertEqual(
linebreaks_filter(add_header('line 1\r\nline2')),
'<p>Header</p>\n\n<p>line 1<br />line2</p>'
diff --git a/tests/template_tests/filter_tests/test_slugify.py b/tests/template_tests/filter_tests/test_slugify.py
index ec9f2bb736..cb23e9b320 100644
--- a/tests/template_tests/filter_tests/test_slugify.py
+++ b/tests/template_tests/filter_tests/test_slugify.py
@@ -1,6 +1,5 @@
from django.template.defaultfilters import slugify
from django.test import SimpleTestCase
-from django.utils import six
from django.utils.encoding import force_text
from django.utils.functional import lazy
from django.utils.safestring import mark_safe
@@ -43,7 +42,7 @@ class FunctionTests(SimpleTestCase):
self.assertEqual(slugify(123), '123')
def test_slugify_lazy_string(self):
- lazy_str = lazy(lambda string: force_text(string), six.text_type)
+ lazy_str = lazy(lambda string: force_text(string), str)
self.assertEqual(
slugify(lazy_str(' Jack & Jill like numbers 1,2,3 and 4 and silly characters ?%.$!/')),
'jack-jill-like-numbers-123-and-4-and-silly-characters',
diff --git a/tests/template_tests/filter_tests/test_urlize.py b/tests/template_tests/filter_tests/test_urlize.py
index 3096213a22..2bf94126d4 100644
--- a/tests/template_tests/filter_tests/test_urlize.py
+++ b/tests/template_tests/filter_tests/test_urlize.py
@@ -1,6 +1,5 @@
from django.template.defaultfilters import urlize
from django.test import SimpleTestCase
-from django.utils import six
from django.utils.functional import lazy
from django.utils.safestring import mark_safe
@@ -367,7 +366,7 @@ class FunctionTests(SimpleTestCase):
)
def test_lazystring(self):
- prepend_www = lazy(lambda url: 'www.' + url, six.text_type)
+ prepend_www = lazy(lambda url: 'www.' + url, str)
self.assertEqual(
urlize(prepend_www('google.com')),
'<a href="http://www.google.com" rel="nofollow">www.google.com</a>',
diff --git a/tests/template_tests/templatetags/custom.py b/tests/template_tests/templatetags/custom.py
index 3c3e4ce8ed..363e7094ce 100644
--- a/tests/template_tests/templatetags/custom.py
+++ b/tests/template_tests/templatetags/custom.py
@@ -94,7 +94,7 @@ simple_one_default.anything = "Expected simple_one_default __dict__"
def simple_unlimited_args(one, two='hi', *args):
"""Expected simple_unlimited_args __doc__"""
return "simple_unlimited_args - Expected result: %s" % (
- ', '.join(six.text_type(arg) for arg in [one, two] + list(args))
+ ', '.join(str(arg) for arg in [one, two] + list(args))
)
@@ -104,7 +104,7 @@ simple_unlimited_args.anything = "Expected simple_unlimited_args __dict__"
@register.simple_tag
def simple_only_unlimited_args(*args):
"""Expected simple_only_unlimited_args __doc__"""
- return "simple_only_unlimited_args - Expected result: %s" % ', '.join(six.text_type(arg) for arg in args)
+ return "simple_only_unlimited_args - Expected result: %s" % ', '.join(str(arg) for arg in args)
simple_only_unlimited_args.anything = "Expected simple_only_unlimited_args __dict__"
@@ -116,7 +116,7 @@ def simple_unlimited_args_kwargs(one, two='hi', *args, **kwargs):
# Sort the dictionary by key to guarantee the order for testing.
sorted_kwarg = sorted(six.iteritems(kwargs), key=operator.itemgetter(0))
return "simple_unlimited_args_kwargs - Expected result: %s / %s" % (
- ', '.join(six.text_type(arg) for arg in [one, two] + list(args)),
+ ', '.join(str(arg) for arg in [one, two] + list(args)),
', '.join('%s=%s' % (k, v) for (k, v) in sorted_kwarg)
)
diff --git a/tests/template_tests/templatetags/inclusion.py b/tests/template_tests/templatetags/inclusion.py
index dbdfa45c95..745dd7ffae 100644
--- a/tests/template_tests/templatetags/inclusion.py
+++ b/tests/template_tests/templatetags/inclusion.py
@@ -152,7 +152,7 @@ def inclusion_unlimited_args(one, two='hi', *args):
return {
"result": (
"inclusion_unlimited_args - Expected result: %s" % (
- ', '.join(six.text_type(arg) for arg in [one, two] + list(args))
+ ', '.join(str(arg) for arg in [one, two] + list(args))
)
)
}
@@ -167,7 +167,7 @@ def inclusion_unlimited_args_from_template(one, two='hi', *args):
return {
"result": (
"inclusion_unlimited_args_from_template - Expected result: %s" % (
- ', '.join(six.text_type(arg) for arg in [one, two] + list(args))
+ ', '.join(str(arg) for arg in [one, two] + list(args))
)
)
}
@@ -181,7 +181,7 @@ def inclusion_only_unlimited_args(*args):
"""Expected inclusion_only_unlimited_args __doc__"""
return {
"result": "inclusion_only_unlimited_args - Expected result: %s" % (
- ', '.join(six.text_type(arg) for arg in args)
+ ', '.join(str(arg) for arg in args)
)
}
@@ -194,7 +194,7 @@ def inclusion_only_unlimited_args_from_template(*args):
"""Expected inclusion_only_unlimited_args_from_template __doc__"""
return {
"result": "inclusion_only_unlimited_args_from_template - Expected result: %s" % (
- ', '.join(six.text_type(arg) for arg in args)
+ ', '.join(str(arg) for arg in args)
)
}
@@ -217,7 +217,7 @@ def inclusion_unlimited_args_kwargs(one, two='hi', *args, **kwargs):
# Sort the dictionary by key to guarantee the order for testing.
sorted_kwarg = sorted(six.iteritems(kwargs), key=operator.itemgetter(0))
return {"result": "inclusion_unlimited_args_kwargs - Expected result: %s / %s" % (
- ', '.join(six.text_type(arg) for arg in [one, two] + list(args)),
+ ', '.join(str(arg) for arg in [one, two] + list(args)),
', '.join('%s=%s' % (k, v) for (k, v) in sorted_kwarg)
)}
diff --git a/tests/template_tests/test_unicode.py b/tests/template_tests/test_unicode.py
index f6471e72e0..dbd18eb495 100644
--- a/tests/template_tests/test_unicode.py
+++ b/tests/template_tests/test_unicode.py
@@ -2,7 +2,6 @@ from unittest import TestCase
from django.template import Context, Engine
from django.template.base import TemplateEncodingError
-from django.utils import six
from django.utils.safestring import SafeData
@@ -28,5 +27,5 @@ class UnicodeTests(TestCase):
# they all render the same (and are returned as unicode objects and
# "safe" objects as well, for auto-escaping purposes).
self.assertEqual(t1.render(c3), t2.render(c3))
- self.assertIsInstance(t1.render(c3), six.text_type)
+ self.assertIsInstance(t1.render(c3), str)
self.assertIsInstance(t1.render(c3), SafeData)
diff --git a/tests/test_utils/tests.py b/tests/test_utils/tests.py
index e63c6774ae..4d29f1a491 100644
--- a/tests/test_utils/tests.py
+++ b/tests/test_utils/tests.py
@@ -226,7 +226,7 @@ class AssertQuerysetEqualTests(TestCase):
class CaptureQueriesContextManagerTests(TestCase):
def setUp(self):
- self.person_pk = six.text_type(Person.objects.create(name='test').pk)
+ self.person_pk = str(Person.objects.create(name='test').pk)
def test_simple(self):
with CaptureQueriesContext(connection) as captured_queries:
diff --git a/tests/update/models.py b/tests/update/models.py
index 1fbab38ca9..bfcc29bee9 100644
--- a/tests/update/models.py
+++ b/tests/update/models.py
@@ -4,7 +4,6 @@ updates.
"""
from django.db import models
-from django.utils import six
class DataPoint(models.Model):
@@ -13,7 +12,7 @@ class DataPoint(models.Model):
another_value = models.CharField(max_length=20, blank=True)
def __str__(self):
- return six.text_type(self.name)
+ return self.name
class RelatedPoint(models.Model):
@@ -21,7 +20,7 @@ class RelatedPoint(models.Model):
data = models.ForeignKey(DataPoint, models.CASCADE)
def __str__(self):
- return six.text_type(self.name)
+ return self.name
class A(models.Model):
diff --git a/tests/urlpatterns_reverse/tests.py b/tests/urlpatterns_reverse/tests.py
index 157479a579..62d199c030 100644
--- a/tests/urlpatterns_reverse/tests.py
+++ b/tests/urlpatterns_reverse/tests.py
@@ -20,7 +20,6 @@ from django.urls import (
NoReverseMatch, RegexURLPattern, RegexURLResolver, Resolver404,
ResolverMatch, get_callable, get_resolver, resolve, reverse, reverse_lazy,
)
-from django.utils import six
from . import middleware, urlconf_outer, views
from .utils import URLObject
@@ -336,13 +335,6 @@ class URLPatternReverse(SimpleTestCase):
'/script:name/optional/foo:bar/'
)
- def test_reverse_returns_unicode(self):
- name, expected, args, kwargs = test_data[0]
- self.assertIsInstance(
- reverse(name, args=args, kwargs=kwargs),
- six.text_type
- )
-
def test_view_not_found_message(self):
msg = (
"Reverse for 'non-existent-view' not found. 'non-existent-view' "
diff --git a/tests/utils_tests/test_encoding.py b/tests/utils_tests/test_encoding.py
index b4e7b9c0ac..faf30a59c0 100644
--- a/tests/utils_tests/test_encoding.py
+++ b/tests/utils_tests/test_encoding.py
@@ -1,7 +1,6 @@
import datetime
import unittest
-from django.utils import six
from django.utils.encoding import (
escape_uri_path, filepath_to_uri, force_bytes, force_text, iri_to_uri,
smart_text, uri_to_iri,
@@ -27,7 +26,7 @@ class TestEncodingUtils(unittest.TestCase):
def test_force_text_lazy(self):
s = SimpleLazyObject(lambda: 'x')
- self.assertTrue(issubclass(type(force_text(s)), six.text_type))
+ self.assertTrue(issubclass(type(force_text(s)), str))
def test_force_bytes_exception(self):
"""
diff --git a/tests/utils_tests/test_functional.py b/tests/utils_tests/test_functional.py
index 0ca534445f..f53e212f93 100644
--- a/tests/utils_tests/test_functional.py
+++ b/tests/utils_tests/test_functional.py
@@ -1,6 +1,5 @@
import unittest
-from django.utils import six
from django.utils.functional import cached_property, lazy
@@ -45,8 +44,8 @@ class FunctionalTestCase(unittest.TestCase):
return b"\xc3\x8e am \xc4\x81 binary \xc7\xa8l\xc3\xa2zz."
t = lazy(lambda: Klazz(), Klazz)()
- self.assertEqual(six.text_type(t), "Î am ā Ǩlâzz.")
- self.assertEqual(six.binary_type(t), b"\xc3\x8e am \xc4\x81 binary \xc7\xa8l\xc3\xa2zz.")
+ self.assertEqual(str(t), "Î am ā Ǩlâzz.")
+ self.assertEqual(bytes(t), b"\xc3\x8e am \xc4\x81 binary \xc7\xa8l\xc3\xa2zz.")
def test_cached_property(self):
"""
@@ -99,7 +98,7 @@ class FunctionalTestCase(unittest.TestCase):
def test_lazy_repr_text(self):
original_object = 'Lazy translation text'
- lazy_obj = lazy(lambda: original_object, six.text_type)
+ lazy_obj = lazy(lambda: original_object, str)
self.assertEqual(repr(original_object), repr(lazy_obj()))
def test_lazy_repr_int(self):
diff --git a/tests/utils_tests/test_lazyobject.py b/tests/utils_tests/test_lazyobject.py
index 588e85afc5..8c9b997b3c 100644
--- a/tests/utils_tests/test_lazyobject.py
+++ b/tests/utils_tests/test_lazyobject.py
@@ -73,7 +73,7 @@ class LazyObjectTestCase(TestCase):
def test_text(self):
obj = self.lazy_wrap('foo')
- self.assertEqual(six.text_type(obj), 'foo')
+ self.assertEqual(str(obj), 'foo')
def test_bool(self):
# Refs #21840
diff --git a/tests/utils_tests/test_safestring.py b/tests/utils_tests/test_safestring.py
index 96f42d5ddd..9e99b6e20b 100644
--- a/tests/utils_tests/test_safestring.py
+++ b/tests/utils_tests/test_safestring.py
@@ -1,6 +1,6 @@
from django.template import Context, Template
from django.test import SimpleTestCase
-from django.utils import html, six, text
+from django.utils import html, text
from django.utils.encoding import force_bytes
from django.utils.functional import lazy, lazystr
from django.utils.safestring import SafeData, mark_safe
@@ -8,7 +8,7 @@ from django.utils.safestring import SafeData, mark_safe
lazybytes = lazy(force_bytes, bytes)
-class customescape(six.text_type):
+class customescape(str):
def __html__(self):
# implement specific and obviously wrong escaping
# in order to be able to tell for sure when it runs
diff --git a/tests/utils_tests/test_text.py b/tests/utils_tests/test_text.py
index 9128fb0247..22695277a4 100644
--- a/tests/utils_tests/test_text.py
+++ b/tests/utils_tests/test_text.py
@@ -1,7 +1,7 @@
import json
from django.test import SimpleTestCase
-from django.utils import six, text
+from django.utils import text
from django.utils.functional import lazystr
from django.utils.text import format_lazy
from django.utils.translation import override, ugettext_lazy
@@ -161,7 +161,6 @@ class TestUtilsText(SimpleTestCase):
"""normalize_newlines should be able to handle bytes too"""
normalized = text.normalize_newlines(b"abc\ndef\rghi\r\n")
self.assertEqual(normalized, "abc\ndef\nghi\n")
- self.assertIsInstance(normalized, six.text_type)
def test_phone2numeric(self):
numeric = text.phone2numeric('0800 flowers')