Refs #23919 -- Removed six.<various>_types usage

Thanks Tim Graham and Simon Charette for the reviews.
This commit is contained in:
Claude Paroz 2016-12-29 16:27:49 +01:00
parent f6acd1d271
commit 7b2f2e74ad
213 changed files with 574 additions and 763 deletions

View File

@ -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)

View File

@ -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)

View File

@ -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),

View File

@ -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)

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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()

View File

@ -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:

View File

@ -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

View File

@ -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:

View File

@ -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)

View File

@ -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):

View File

@ -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)

View File

@ -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()

View File

@ -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)

View File

@ -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)

View File

@ -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)

View File

@ -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:

View File

@ -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:

View File

@ -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)

View File

@ -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()

View File

@ -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:

View File

@ -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:

View File

@ -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

View File

@ -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.

View File

@ -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

View File

@ -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.')

View File

@ -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)

View File

@ -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.

View File

@ -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:

View File

@ -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))

View File

@ -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]

View File

@ -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]

View File

@ -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)))

View File

@ -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

View File

@ -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):

View File

@ -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}

View File

@ -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

View File

@ -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

View File

@ -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]

View File

@ -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

View File

@ -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'):

View File

@ -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):

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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)

View File

@ -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)

View File

@ -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')

View File

@ -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)

View File

@ -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.

View File

@ -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:

View File

@ -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:

View File

@ -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__.

View File

@ -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

View File

@ -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)

View File

@ -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

View File

@ -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

View File

@ -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)

View File

@ -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):
"""

View File

@ -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()

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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"

View File

@ -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:

View File

@ -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)

View File

@ -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:

View File

@ -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

View File

@ -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

View File

@ -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)

View File

@ -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:

View File

@ -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

View File

@ -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
]

View File

@ -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

View File

@ -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."

View File

@ -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" % (

View File

@ -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:

View File

@ -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

View File

@ -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:

View File

@ -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:

View File

@ -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

View File

@ -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]

View File

@ -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)

View File

@ -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,

View File

@ -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,

View File

@ -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)

View File

@ -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]

View File

@ -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

View File

@ -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

View File

@ -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:

View File

@ -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

View File

@ -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:

View File

@ -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:

View File

@ -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:

View File

@ -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)

View File

@ -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 '

View File

@ -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

Some files were not shown because too many files have changed in this diff Show More