Permalink
Browse files

Refs #23919 -- Removed unneeded str() calls

  • Loading branch information...
claudep committed Jan 20, 2017
1 parent 4e729fe commit 042b7350a080cc964f913faf1cf7f0097f650a58
Showing with 117 additions and 165 deletions.
  1. +1 −1 django/contrib/gis/admin/widgets.py
  2. +2 −2 django/contrib/gis/db/backends/postgis/adapter.py
  3. +1 −1 django/contrib/gis/db/models/functions.py
  4. +1 −1 django/contrib/gis/gdal/datasource.py
  5. +2 −2 django/contrib/gis/gdal/driver.py
  6. +2 −2 django/contrib/gis/gdal/envelope.py
  7. +2 −2 django/contrib/gis/gdal/geometries.py
  8. +1 −1 django/contrib/gis/geos/coordseq.py
  9. +1 −1 django/contrib/gis/geos/geometry.py
  10. +2 −2 django/contrib/gis/geos/mutable_list.py
  11. +1 −1 django/contrib/gis/geos/point.py
  12. +4 −4 django/core/handlers/wsgi.py
  13. +1 −1 django/core/mail/message.py
  14. +4 −4 django/core/management/commands/makemessages.py
  15. +1 −1 django/core/management/commands/runserver.py
  16. +1 −1 django/core/servers/basehttp.py
  17. +7 −7 django/db/backends/sqlite3/base.py
  18. +4 −4 django/db/models/base.py
  19. +2 −4 django/db/models/fields/__init__.py
  20. +1 −1 django/db/models/fields/files.py
  21. +1 −1 django/db/models/indexes.py
  22. +4 −4 django/http/cookie.py
  23. +2 −2 django/http/request.py
  24. +1 −2 django/http/response.py
  25. +12 −12 django/test/client.py
  26. +1 −1 django/test/selenium.py
  27. +1 −1 django/urls/resolvers.py
  28. +1 −1 django/utils/html.py
  29. +3 −3 django/utils/http.py
  30. +1 −1 django/utils/safestring.py
  31. +1 −2 django/utils/translation/trans_real.py
  32. +1 −1 django/utils/version.py
  33. +3 −4 tests/admin_scripts/tests.py
  34. +1 −4 tests/auth_tests/test_management.py
  35. +4 −4 tests/builtin_server/tests.py
  36. +2 −2 tests/forms_tests/tests/tests.py
  37. +1 −1 tests/get_object_or_404/tests.py
  38. +1 −1 tests/get_or_create/tests.py
  39. +12 −19 tests/httpwrappers/tests.py
  40. +1 −1 tests/i18n/test_compilation.py
  41. +4 −18 tests/i18n/tests.py
  42. +10 −10 tests/mail/tests.py
  43. +2 −19 tests/migrations/test_writer.py
  44. +1 −1 tests/servers/test_basehttp.py
  45. +2 −2 tests/str/tests.py
  46. +2 −2 tests/urlpatterns_reverse/tests.py
  47. +1 −3 tests/utils_tests/test_encoding.py
@@ -83,7 +83,7 @@ def map_options(self):
# JavaScript construction utilities for the Bounds and Projection.
def ol_bounds(extent):
- return 'new OpenLayers.Bounds(%s)' % str(extent)
+ return 'new OpenLayers.Bounds(%s)' % extent
def ol_projection(srid):
return 'new OpenLayers.Projection("EPSG:%s")' % srid
@@ -58,9 +58,9 @@ def getquoted(self):
"""
if self.is_geometry:
# Psycopg will figure out whether to use E'\\000' or '\000'.
- return str('%s(%s)' % (
+ return '%s(%s)' % (
'ST_GeogFromWKB' if self.geography else 'ST_GeomFromEWKB',
- self._adapter.getquoted().decode())
+ self._adapter.getquoted().decode()
)
else:
# For rasters, add explicit type cast to WKB string.
@@ -65,7 +65,7 @@ def _handle_param(self, value, param_name='', check_types=None):
if check_types and not isinstance(value, check_types):
raise TypeError(
"The %s parameter has the wrong type: should be %s." % (
- param_name, str(check_types))
+ param_name, check_types)
)
return value
@@ -109,7 +109,7 @@ def __len__(self):
def __str__(self):
"Returns OGR GetName and Driver for the Data Source."
- return '%s (%s)' % (self.name, str(self.driver))
+ return '%s (%s)' % (self.name, self.driver)
@property
def layer_count(self):
@@ -60,11 +60,11 @@ def __init__(self, dr_input):
elif isinstance(dr_input, c_void_p):
driver = dr_input
else:
- raise GDALException('Unrecognized input type for GDAL/OGR Driver: %s' % str(type(dr_input)))
+ raise GDALException('Unrecognized input type for GDAL/OGR Driver: %s' % type(dr_input))
# Making sure we get a valid pointer to the OGR Driver
if not driver:
- raise GDALException('Could not initialize GDAL/OGR Driver on input: %s' % str(dr_input))
+ raise GDALException('Could not initialize GDAL/OGR Driver on input: %s' % dr_input)
self.ptr = driver
def __str__(self):
@@ -51,7 +51,7 @@ def __init__(self, *args):
else:
self._from_sequence(args[0])
else:
- raise TypeError('Incorrect type of argument: %s' % str(type(args[0])))
+ raise TypeError('Incorrect type of argument: %s' % type(args[0]))
elif len(args) == 4:
# Individual parameters passed in.
# Thanks to ww for the help
@@ -123,7 +123,7 @@ def expand_to_include(self, *args):
else:
raise GDALException('Incorrect number of tuple elements (%d).' % len(args[0]))
else:
- raise TypeError('Incorrect type of argument: %s' % str(type(args[0])))
+ raise TypeError('Incorrect type of argument: %s' % type(args[0]))
elif len(args) == 2:
# An x and an y parameter were passed in
return self.expand_to_include((args[0], args[1], args[0], args[1]))
@@ -109,7 +109,7 @@ def __init__(self, geom_input, srs=None):
# Now checking the Geometry pointer before finishing initialization
# by setting the pointer for the object.
if not g:
- raise GDALException('Cannot create OGR Geometry from input: %s' % str(geom_input))
+ raise GDALException('Cannot create OGR Geometry from input: %s' % geom_input)
self.ptr = g
# Assigning the SpatialReference object to the geometry, if valid.
@@ -549,7 +549,7 @@ def __getitem__(self, index):
elif dim == 3:
return (x.value, y.value, z.value)
else:
- raise OGRIndexError('index out of range: %s' % str(index))
+ raise OGRIndexError('index out of range: %s' % index)
def __iter__(self):
"Iterates over each point in the LineString."
@@ -73,7 +73,7 @@ def _checkindex(self, index):
"Checks the given index."
sz = self.size
if (sz < 1) or (index < 0) or (index >= sz):
- raise IndexError('invalid GEOS Geometry index: %s' % str(index))
+ raise IndexError('invalid GEOS Geometry index: %s' % index)
def _checkdim(self, dim):
"Checks the given dimension."
@@ -73,7 +73,7 @@ def __init__(self, geo_input, srid=None):
g = capi.geom_clone(geo_input.ptr)
else:
# Invalid geometry type.
- raise TypeError('Improper geometry input type: %s' % str(type(geo_input)))
+ raise TypeError('Improper geometry input type: %s' % type(geo_input))
if g:
# Setting the pointer object with a valid pointer.
@@ -179,7 +179,7 @@ def index(self, val):
for i in range(0, len(self)):
if self[i] == val:
return i
- raise ValueError('%s not found in object' % str(val))
+ raise ValueError('%s not found in object' % val)
# ## Mutating ##
def append(self, val):
@@ -242,7 +242,7 @@ def _checkindex(self, index, correct=True):
return index
if correct and -length <= index < 0:
return index + length
- raise IndexError('invalid index: %s' % str(index))
+ raise IndexError('invalid index: %s' % index)
def _check_allowed(self, items):
if hasattr(self, '_allowed'):
@@ -56,7 +56,7 @@ def _create_point(cls, ndim, coords):
return capi.create_point(None)
if ndim < 2 or ndim > 3:
- raise TypeError('Invalid point dimension: %s' % str(ndim))
+ raise TypeError('Invalid point dimension: %s' % ndim)
cs = capi.create_cs(c_uint(1), c_uint(ndim))
i = iter(coords)
@@ -153,9 +153,9 @@ def __call__(self, environ, start_response):
response._handler_class = self.__class__
status = '%d %s' % (response.status_code, response.reason_phrase)
- response_headers = [(str(k), str(v)) for k, v in response.items()]
+ response_headers = list(response.items())
for c in response.cookies.values():
- response_headers.append((str('Set-Cookie'), str(c.output(header=''))))
+ response_headers.append(('Set-Cookie', c.output(header='')))
start_response(status, response_headers)
if getattr(response, 'file_to_stream', None) is not None and environ.get('wsgi.file_wrapper'):
response = environ['wsgi.file_wrapper'](response.file_to_stream)
@@ -208,9 +208,9 @@ def get_bytes_from_wsgi(environ, key, default):
"""
Get a value from the WSGI environ dictionary as bytes.
- key and default should be str objects.
+ key and default should be strings.
"""
- value = environ.get(str(key), str(default))
+ value = environ.get(key, default)
# Non-ASCII values in the WSGI environ are arbitrarily decoded with
# ISO-8859-1. This is wrong for Django websites where UTF-8 is the default.
# Re-encode to recover the original bytestring.
@@ -68,7 +68,7 @@ def forbid_multi_line_headers(name, val, encoding):
else:
if name.lower() == 'subject':
val = Header(val).encode()
- return str(name), val
+ return name, val
def split_addr(addr, encoding):
@@ -398,7 +398,7 @@ def build_potfiles(self):
self.process_files(file_list)
potfiles = []
for path in self.locale_paths:
- potfile = os.path.join(path, '%s.pot' % str(self.domain))
+ potfile = os.path.join(path, '%s.pot' % self.domain)
if not os.path.exists(potfile):
continue
args = ['msguniq'] + self.msguniq_options + [potfile]
@@ -417,7 +417,7 @@ def build_potfiles(self):
def remove_potfiles(self):
for path in self.locale_paths:
- pot_path = os.path.join(path, '%s.pot' % str(self.domain))
+ pot_path = os.path.join(path, '%s.pot' % self.domain)
if os.path.exists(pot_path):
os.unlink(pot_path)
@@ -583,7 +583,7 @@ def process_locale_dir(self, locale_dir, files):
)
for build_file in build_files:
msgs = build_file.postprocess_messages(msgs)
- potfile = os.path.join(locale_dir, '%s.pot' % str(self.domain))
+ potfile = os.path.join(locale_dir, '%s.pot' % self.domain)
write_pot_file(potfile, msgs)
for build_file in build_files:
@@ -599,7 +599,7 @@ def write_po_file(self, potfile, locale):
basedir = os.path.join(os.path.dirname(potfile), locale, 'LC_MESSAGES')
if not os.path.isdir(basedir):
os.makedirs(basedir)
- pofile = os.path.join(basedir, '%s.po' % str(self.domain))
+ pofile = os.path.join(basedir, '%s.po' % self.domain)
if os.path.exists(pofile):
args = ['msgmerge'] + self.msgmerge_options + [pofile, potfile]
@@ -56,7 +56,7 @@ def execute(self, *args, **options):
# We rely on the environment because it's currently the only
# way to reach WSGIRequestHandler. This seems an acceptable
# compromise considering `runserver` runs indefinitely.
- os.environ[str("DJANGO_COLORS")] = str("nocolor")
+ os.environ["DJANGO_COLORS"] = "nocolor"
super(Command, self).execute(*args, **options)
def get_handler(self, *args, **options):
@@ -103,7 +103,7 @@ def log_message(self, format, *args):
}
if args[1][0] == '4':
# 0x16 = Handshake, 0x03 = SSL 3.0 or TLS 1.x
- if args[0].startswith(str('\x16\x03')):
+ if args[0].startswith('\x16\x03'):
extra['status_code'] = 500
logger.error(
"You're accessing the development server over HTTPS, but "
@@ -45,13 +45,13 @@ def decoder(conv_func):
return lambda s: conv_func(s.decode('utf-8'))
-Database.register_converter(str("bool"), decoder(lambda s: s == '1'))
-Database.register_converter(str("time"), decoder(parse_time))
-Database.register_converter(str("date"), decoder(parse_date))
-Database.register_converter(str("datetime"), decoder(parse_datetime))
-Database.register_converter(str("timestamp"), decoder(parse_datetime))
-Database.register_converter(str("TIMESTAMP"), decoder(parse_datetime))
-Database.register_converter(str("decimal"), decoder(backend_utils.typecast_decimal))
+Database.register_converter("bool", decoder(lambda s: s == '1'))
+Database.register_converter("time", decoder(parse_time))
+Database.register_converter("date", decoder(parse_date))
+Database.register_converter("datetime", decoder(parse_datetime))
+Database.register_converter("timestamp", decoder(parse_datetime))
+Database.register_converter("TIMESTAMP", decoder(parse_datetime))
+Database.register_converter("decimal", decoder(backend_utils.typecast_decimal))
Database.register_adapter(decimal.Decimal, backend_utils.rev_typecast_decimal)
View
@@ -35,10 +35,10 @@
class Deferred:
def __repr__(self):
- return str('<Deferred field>')
+ return '<Deferred field>'
def __str__(self):
- return str('<Deferred field>')
+ return '<Deferred field>'
DEFERRED = Deferred()
@@ -118,7 +118,7 @@ def __new__(cls, name, bases, attrs):
new_class.add_to_class(
'DoesNotExist',
subclass_exception(
- str('DoesNotExist'),
+ 'DoesNotExist',
tuple(
x.DoesNotExist for x in parents if hasattr(x, '_meta') and not x._meta.abstract
) or (ObjectDoesNotExist,),
@@ -127,7 +127,7 @@ def __new__(cls, name, bases, attrs):
new_class.add_to_class(
'MultipleObjectsReturned',
subclass_exception(
- str('MultipleObjectsReturned'),
+ 'MultipleObjectsReturned',
tuple(
x.MultipleObjectsReturned for x in parents if hasattr(x, '_meta') and not x._meta.abstract
) or (MultipleObjectsReturned,),
@@ -32,9 +32,7 @@
from django.utils.text import capfirst
from django.utils.translation import ugettext_lazy as _
-# Avoid "TypeError: Item in ``from list'' not a string" -- unicode_literals
-# makes these strings unicode
-__all__ = [str(x) for x in (
+__all__ = [
'AutoField', 'BLANK_CHOICE_DASH', 'BigAutoField', 'BigIntegerField',
'BinaryField', 'BooleanField', 'CharField', 'CommaSeparatedIntegerField',
'DateField', 'DateTimeField', 'DecimalField', 'DurationField',
@@ -43,7 +41,7 @@
'NOT_PROVIDED', 'NullBooleanField', 'PositiveIntegerField',
'PositiveSmallIntegerField', 'SlugField', 'SmallIntegerField', 'TextField',
'TimeField', 'URLField', 'UUIDField',
-)]
+]
class Empty:
@@ -277,7 +277,7 @@ def get_internal_type(self):
def get_prep_value(self, value):
"Returns field's value prepared for saving into a database."
value = super(FileField, self).get_prep_value(value)
- # Need to convert File objects provided via a form to unicode for database insertion
+ # Need to convert File objects provided via a form to string for database insertion
if value is None:
return None
return str(value)
@@ -2,7 +2,7 @@
from django.utils.encoding import force_bytes
-__all__ = [str('Index')]
+__all__ = ['Index']
# The max length of the names of the indexes (restricted to 30 due to Oracle)
MAX_NAME_LENGTH = 30
View
@@ -22,13 +22,13 @@ def parse_cookie(cookie):
Return a dictionary parsed from a `Cookie:` header string.
"""
cookiedict = {}
- for chunk in cookie.split(str(';')):
- if str('=') in chunk:
- key, val = chunk.split(str('='), 1)
+ for chunk in cookie.split(';'):
+ if '=' in chunk:
+ key, val = chunk.split('=', 1)
else:
# Assume an empty name per
# https://bugzilla.mozilla.org/show_bug.cgi?id=169091
- key, val = str(''), chunk
+ key, val = '', chunk
key, val = key.strip(), val.strip()
if key or val:
# unquote using Python's algorithm.
View
@@ -509,11 +509,11 @@ def encode(k, v):
# this slightly more restricted function, used by QueryDict.
def bytes_to_text(s, encoding):
"""
- Converts basestring objects to unicode, using the given encoding. Illegally
+ Convert bytes objects to strings, using the given encoding. Illegally
encoded input characters are replaced with Unicode "unknown" codepoint
(\ufffd).
- Returns any non-basestring objects without change.
+ Return any non-bytes objects without change.
"""
if isinstance(s, bytes):
return str(s, encoding, 'replace')
View
@@ -124,8 +124,7 @@ def _convert_to_charset(self, value, charset, mime_encode=False):
value = value.decode(charset)
except UnicodeError as e:
if mime_encode:
- # Wrapping in str() is a workaround for #12422 under Python 2.
- value = str(Header(value, 'utf-8', maxlinelen=sys.maxsize).encode())
+ value = Header(value, 'utf-8', maxlinelen=sys.maxsize).encode()
else:
e.reason += ', HTTP response headers must be in %s format' % charset
raise
View
@@ -281,15 +281,15 @@ def _base_environ(self, **request):
# See http://www.python.org/dev/peps/pep-3333/#environ-variables
environ = {
'HTTP_COOKIE': self.cookies.output(header='', sep='; '),
- 'PATH_INFO': str('/'),
- 'REMOTE_ADDR': str('127.0.0.1'),
- 'REQUEST_METHOD': str('GET'),
- 'SCRIPT_NAME': str(''),
- 'SERVER_NAME': str('testserver'),
- 'SERVER_PORT': str('80'),
- 'SERVER_PROTOCOL': str('HTTP/1.1'),
+ 'PATH_INFO': '/',
+ 'REMOTE_ADDR': '127.0.0.1',
+ 'REQUEST_METHOD': 'GET',
+ 'SCRIPT_NAME': '',
+ 'SERVER_NAME': 'testserver',
+ 'SERVER_PORT': '80',
+ 'SERVER_PROTOCOL': 'HTTP/1.1',
'wsgi.version': (1, 0),
- 'wsgi.url_scheme': str('http'),
+ 'wsgi.url_scheme': 'http',
'wsgi.input': FakePayload(b''),
'wsgi.errors': self.errors,
'wsgi.multiprocess': True,
@@ -393,14 +393,14 @@ def generic(self, method, path, data='',
data = force_bytes(data, settings.DEFAULT_CHARSET)
r = {
'PATH_INFO': self._get_path(parsed),
- 'REQUEST_METHOD': str(method),
- 'SERVER_PORT': str('443') if secure else str('80'),
- 'wsgi.url_scheme': str('https') if secure else str('http'),
+ 'REQUEST_METHOD': method,
+ 'SERVER_PORT': '443' if secure else '80',
+ 'wsgi.url_scheme': 'https' if secure else 'http',
}
if data:
r.update({
'CONTENT_LENGTH': len(data),
- 'CONTENT_TYPE': str(content_type),
+ 'CONTENT_TYPE': content_type,
'wsgi.input': FakePayload(data),
})
r.update(extra)
Oops, something went wrong.

0 comments on commit 042b735

Please sign in to comment.