Skip to content

Commit 1c46699

Browse files
authored
Refs #23919 -- Removed misc Python 2/3 references.
1 parent 11856ea commit 1c46699

File tree

22 files changed

+62
-115
lines changed

22 files changed

+62
-115
lines changed

django/apps/config.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,8 @@ def _path_from_module(self, module):
5757
"""Attempt to determine app's filesystem path from its module."""
5858
# See #21874 for extended discussion of the behavior of this method in
5959
# various cases.
60-
# Convert paths to list because Python 3's _NamespacePath does not
61-
# support indexing.
60+
# Convert paths to list because Python's _NamespacePath doesn't support
61+
# indexing.
6262
paths = list(getattr(module, '__path__', []))
6363
if len(paths) != 1:
6464
filename = getattr(module, '__file__', None)

django/contrib/auth/hashers.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -419,8 +419,7 @@ def encode(self, password, salt):
419419
# Hash the password prior to using bcrypt to prevent password
420420
# truncation as described in #20138.
421421
if self.digest is not None:
422-
# Use binascii.hexlify() because a hex encoded bytestring is
423-
# Unicode on Python 3.
422+
# Use binascii.hexlify() because a hex encoded bytestring is str.
424423
password = binascii.hexlify(self.digest(force_bytes(password)).digest())
425424
else:
426425
password = force_bytes(password)

django/contrib/auth/views.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,7 @@ def password_reset_confirm(request, uidb64=None, token=None,
298298
else:
299299
post_reset_redirect = resolve_url(post_reset_redirect)
300300
try:
301-
# urlsafe_base64_decode() decodes to bytestring on Python 3
301+
# urlsafe_base64_decode() decodes to bytestring
302302
uid = force_text(urlsafe_base64_decode(uidb64))
303303
user = UserModel._default_manager.get(pk=uid)
304304
except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist):
@@ -442,7 +442,7 @@ def dispatch(self, *args, **kwargs):
442442

443443
def get_user(self, uidb64):
444444
try:
445-
# urlsafe_base64_decode() decodes to bytestring on Python 3
445+
# urlsafe_base64_decode() decodes to bytestring
446446
uid = force_text(urlsafe_base64_decode(uidb64))
447447
user = UserModel._default_manager.get(pk=uid)
448448
except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist):

django/core/mail/message.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -324,8 +324,8 @@ def attach(self, filename=None, content=None, mimetype=None):
324324
try:
325325
content = content.decode('utf-8')
326326
except UnicodeDecodeError:
327-
# If mimetype suggests the file is text but it's actually
328-
# binary, read() will raise a UnicodeDecodeError on Python 3.
327+
# If mimetype suggests the file is text but it's
328+
# actually binary, read() raises a UnicodeDecodeError.
329329
mimetype = DEFAULT_ATTACHMENT_MIME_TYPE
330330

331331
self.attachments.append((filename, content, mimetype))

django/core/management/commands/shell.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ def python(self, options):
5353
import rlcompleter
5454
readline.set_completer(rlcompleter.Completer(imported_objects).complete)
5555
# Enable tab completion on systems using libedit (e.g. Mac OSX).
56-
# These lines are copied from Lib/site.py on Python 3.4.
56+
# These lines are copied from Python's Lib/site.py.
5757
readline_doc = getattr(readline, '__doc__', '')
5858
if readline_doc is not None and 'libedit' in readline_doc:
5959
readline.parse_and_bind("bind ^I rl_complete")

django/db/backends/oracle/base.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -322,8 +322,7 @@ def __init__(self, param, cursor, strings_only=False):
322322
param = Oracle_datetime.from_datetime(param)
323323

324324
string_size = 0
325-
# Oracle doesn't recognize True and False correctly in Python 3.
326-
# The conversion done below works both in 2 and 3.
325+
# Oracle doesn't recognize True and False correctly.
327326
if param is True:
328327
param = 1
329328
elif param is False:

django/db/migrations/serializer.py

+8-14
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
import re
99
import types
1010
import uuid
11-
from importlib import import_module
1211

1312
from django.db import models
1413
from django.db.migrations.operations.base import Operation
@@ -155,20 +154,15 @@ def serialize(self):
155154
raise ValueError("Cannot serialize function: lambda")
156155
if self.value.__module__ is None:
157156
raise ValueError("Cannot serialize function %r: No module" % self.value)
158-
# Python 3 is a lot easier, and only uses this branch if it's not local.
159-
if getattr(self.value, "__qualname__", None) and getattr(self.value, "__module__", None):
160-
if "<" not in self.value.__qualname__: # Qualname can include <locals>
161-
return "%s.%s" % \
162-
(self.value.__module__, self.value.__qualname__), {"import %s" % self.value.__module__}
163-
# Fallback version
157+
164158
module_name = self.value.__module__
165-
# Make sure it's actually there
166-
module = import_module(module_name)
167-
if not hasattr(module, self.value.__name__):
168-
raise ValueError(
169-
"Could not find function %s in %s.\n" % (self.value.__name__, module_name)
170-
)
171-
return "%s.%s" % (module_name, self.value.__name__), {"import %s" % module_name}
159+
160+
if '<' not in self.value.__qualname__: # Qualname can include <locals>
161+
return '%s.%s' % (module_name, self.value.__qualname__), {'import %s' % self.value.__module__}
162+
163+
raise ValueError(
164+
'Could not find function %s in %s.\n' % (self.value.__name__, module_name)
165+
)
172166

173167

174168
class FunctoolsPartialSerializer(BaseSerializer):

django/test/runner.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -258,8 +258,7 @@ def default_test_processes():
258258
"""
259259
# The current implementation of the parallel test runner requires
260260
# multiprocessing to start subprocesses with fork().
261-
# On Python 3.4+: if multiprocessing.get_start_method() != 'fork':
262-
if not hasattr(os, 'fork'):
261+
if multiprocessing.get_start_method() != 'fork':
263262
return 1
264263
try:
265264
return int(os.environ['DJANGO_TEST_PROCESSES'])

docs/internals/howto-release-django.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -303,7 +303,7 @@ Now you're ready to actually put the release out there. To do this:
303303
$ pip install https://www.djangoproject.com/m/releases/$MAJOR_VERSION/Django-$RELEASE_VERSION.tar.gz
304304
$ deactivate
305305
$ mktmpenv
306-
$ pip install https://www.djangoproject.com/m/releases/$MAJOR_VERSION/Django-$RELEASE_VERSION-py2.py3-none-any.whl
306+
$ pip install https://www.djangoproject.com/m/releases/$MAJOR_VERSION/Django-$RELEASE_VERSION-py3-none-any.whl
307307
$ deactivate
308308

309309
This just tests that the tarballs are available (i.e. redirects are up) and

docs/ref/contrib/gis/install/geodjango_setup.bat

-8
This file was deleted.

docs/ref/contrib/gis/install/index.txt

+4-7
Original file line numberDiff line numberDiff line change
@@ -463,23 +463,20 @@ executable with ``cmd.exe``, will set this up:
463463
.. code-block:: bat
464464

465465
set OSGEO4W_ROOT=C:\OSGeo4W
466-
set PYTHON_ROOT=C:\Python27
466+
set PYTHON_ROOT=C:\Python3X
467467
set GDAL_DATA=%OSGEO4W_ROOT%\share\gdal
468468
set PROJ_LIB=%OSGEO4W_ROOT%\share\proj
469469
set PATH=%PATH%;%PYTHON_ROOT%;%OSGEO4W_ROOT%\bin
470470
reg ADD "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path /t REG_EXPAND_SZ /f /d "%PATH%"
471471
reg ADD "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v GDAL_DATA /t REG_EXPAND_SZ /f /d "%GDAL_DATA%"
472472
reg ADD "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v PROJ_LIB /t REG_EXPAND_SZ /f /d "%PROJ_LIB%"
473473

474-
For your convenience, these commands are available in the executable batch
475-
script, :download:`geodjango_setup.bat`.
476-
477474
.. note::
478475

479476
Administrator privileges are required to execute these commands.
480-
To do this, right-click on :download:`geodjango_setup.bat` and select
481-
:menuselection:`Run as administrator`. You need to log out and log back in again
482-
for the settings to take effect.
477+
To do this, create a ``bat`` script with the commands, right-click it, and
478+
select :menuselection:`Run as administrator`. You need to log out and log
479+
back in again for the settings to take effect.
483480

484481
.. note::
485482

setup.cfg

-3
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,3 @@ not_skip = __init__.py
1818

1919
[metadata]
2020
license-file = LICENSE
21-
22-
[wheel]
23-
universal = 1

setup.py

-2
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,6 @@
6161
'License :: OSI Approved :: BSD License',
6262
'Operating System :: OS Independent',
6363
'Programming Language :: Python',
64-
'Programming Language :: Python :: 2',
65-
'Programming Language :: Python :: 2.7',
6664
'Programming Language :: Python :: 3',
6765
'Programming Language :: Python :: 3.4',
6866
'Programming Language :: Python :: 3.5',

tests/README.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ install some requirements and run the tests::
33

44
$ cd tests
55
$ pip install -e ..
6-
$ pip install -r requirements/py3.txt # or py2.txt
6+
$ pip install -r requirements/py3.txt
77
$ ./runtests.py
88

99
For more information about the test suite, see

tests/auth_tests/test_hashers.py

-1
Original file line numberDiff line numberDiff line change
@@ -434,7 +434,6 @@ def test_load_library_no_algorithm(self):
434434

435435
def test_load_library_importerror(self):
436436
PlainHasher = type('PlainHasher', (BasePasswordHasher,), {'algorithm': 'plain', 'library': 'plain'})
437-
# Python 3 adds quotes around module name
438437
msg = "Couldn't load 'PlainHasher' algorithm library: No module named 'plain'"
439438
with self.assertRaisesMessage(ValueError, msg):
440439
PlainHasher()._load_library()

tests/cache/tests.py

-4
Original file line numberDiff line numberDiff line change
@@ -1912,10 +1912,6 @@ def test_middleware_doesnt_cache_streaming_response(self):
19121912
get_cache_data = FetchFromCacheMiddleware().process_request(request)
19131913
self.assertIsNone(get_cache_data)
19141914

1915-
# This test passes on Python < 3.3 even without the corresponding code
1916-
# in UpdateCacheMiddleware, because pickling a StreamingHttpResponse
1917-
# fails (http://bugs.python.org/issue14288). LocMemCache silently
1918-
# swallows the exception and doesn't store the response in cache.
19191915
content = ['Check for cache with streaming content.']
19201916
response = StreamingHttpResponse(content)
19211917
UpdateCacheMiddleware().process_response(request, response)

tests/i18n/test_extraction.py

+18-23
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
from django.core.management.utils import find_command
1717
from django.test import SimpleTestCase, override_settings
1818
from django.test.utils import captured_stderr, captured_stdout
19+
from django.utils._os import symlinks_supported
1920
from django.utils.translation import TranslatorCommentWarning
2021

2122
from .utils import POFileAssertionMixin, RunInTmpDirMixin, copytree
@@ -382,7 +383,10 @@ def test_makemessages_gettext_version(self, mocked_popen_wrapper):
382383
cmd.gettext_version
383384

384385
def test_po_file_encoding_when_updating(self):
385-
"""Update of PO file doesn't corrupt it with non-UTF-8 encoding on Python3+Windows (#23271)"""
386+
"""
387+
Update of PO file doesn't corrupt it with non-UTF-8 encoding on Windows
388+
(#23271).
389+
"""
386390
BR_PO_BASE = 'locale/pt_BR/LC_MESSAGES/django'
387391
shutil.copyfile(BR_PO_BASE + '.pristine', BR_PO_BASE + '.po')
388392
management.call_command('makemessages', locale=['pt_BR'], verbosity=0)
@@ -472,29 +476,20 @@ def setUp(self):
472476
self.symlinked_dir = os.path.join(self.test_dir, 'templates_symlinked')
473477

474478
def test_symlink(self):
475-
# On Python < 3.2 os.symlink() exists only on Unix
476-
if hasattr(os, 'symlink'):
477-
if os.path.exists(self.symlinked_dir):
478-
self.assertTrue(os.path.islink(self.symlinked_dir))
479-
else:
480-
# On Python >= 3.2) os.symlink() exists always but then can
481-
# fail at runtime when user hasn't the needed permissions on
482-
# Windows versions that support symbolink links (>= 6/Vista).
483-
# See Python issue 9333 (http://bugs.python.org/issue9333).
484-
# Skip the test in that case
485-
try:
486-
os.symlink(os.path.join(self.test_dir, 'templates'), self.symlinked_dir)
487-
except (OSError, NotImplementedError):
488-
self.skipTest("os.symlink() is available on this OS but can't be used by this user.")
489-
os.chdir(self.test_dir)
490-
management.call_command('makemessages', locale=[LOCALE], verbosity=0, symlinks=True)
491-
self.assertTrue(os.path.exists(self.PO_FILE))
492-
with open(self.PO_FILE, 'r') as fp:
493-
po_contents = fp.read()
494-
self.assertMsgId('This literal should be included.', po_contents)
495-
self.assertLocationCommentPresent(self.PO_FILE, None, 'templates_symlinked', 'test.html')
479+
if os.path.exists(self.symlinked_dir):
480+
self.assertTrue(os.path.islink(self.symlinked_dir))
496481
else:
497-
self.skipTest("os.symlink() not available on this OS + Python version combination.")
482+
if symlinks_supported():
483+
os.symlink(os.path.join(self.test_dir, 'templates'), self.symlinked_dir)
484+
else:
485+
self.skipTest("os.symlink() not available on this OS + Python version combination.")
486+
os.chdir(self.test_dir)
487+
management.call_command('makemessages', locale=[LOCALE], verbosity=0, symlinks=True)
488+
self.assertTrue(os.path.exists(self.PO_FILE))
489+
with open(self.PO_FILE, 'r') as fp:
490+
po_contents = fp.read()
491+
self.assertMsgId('This literal should be included.', po_contents)
492+
self.assertLocationCommentPresent(self.PO_FILE, None, 'templates_symlinked', 'test.html')
498493

499494

500495
class CopyPluralFormsExtractorTests(ExtractorTests):

tests/mail/tests.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,6 @@ def test_space_continuation(self):
192192
193193
)
194194
message = email.message()
195-
# Note that in Python 3, maximum line length has increased from 76 to 78
196195
self.assertEqual(
197196
message['Subject'].encode(),
198197
b'Long subject lines that get wrapped should contain a space continuation\n'
@@ -1157,8 +1156,8 @@ def process_message(self, peer, mailfrom, rcpttos, data):
11571156

11581157
if mailfrom != maddr:
11591158
# According to the spec, mailfrom does not necessarily match the
1160-
# From header - on Python 3 this is the case where the local part
1161-
# isn't encoded, so try to correct that.
1159+
# From header - this is the case where the local part isn't
1160+
# encoded, so try to correct that.
11621161
lp, domain = mailfrom.split('@', 1)
11631162
lp = Header(lp, 'utf-8').encode()
11641163
mailfrom = '@'.join([lp, domain])

tests/migrations/test_commands.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -672,8 +672,8 @@ def test_makemigrations_order(self):
672672
module = 'migrations.test_migrations_order'
673673
with self.temporary_migration_module(module=module) as migration_dir:
674674
if hasattr(importlib, 'invalidate_caches'):
675-
# Python 3 importlib caches os.listdir() on some platforms like
676-
# Mac OS X (#23850).
675+
# importlib caches os.listdir() on some platforms like Mac OS X
676+
# (#23850).
677677
importlib.invalidate_caches()
678678
call_command('makemigrations', 'migrations', '--empty', '-n', 'a', '-v', '0')
679679
self.assertTrue(os.path.exists(os.path.join(migration_dir, '0002_a.py')))
@@ -1202,8 +1202,8 @@ def cmd(migration_count, migration_name, *args):
12021202
content = cmd("0001", migration_name_0001)
12031203
self.assertIn("dependencies=[\n]", content)
12041204

1205-
# Python 3 importlib caches os.listdir() on some platforms like
1206-
# Mac OS X (#23850).
1205+
# importlib caches os.listdir() on some platforms like Mac OS X
1206+
# (#23850).
12071207
if hasattr(importlib, 'invalidate_caches'):
12081208
importlib.invalidate_caches()
12091209

tests/migrations/test_writer.py

+11-14
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,12 @@ def deconstruct(self):
4040
)
4141

4242

43+
class TestModel1(object):
44+
def upload_to(self):
45+
return '/somewhere/dynamic/'
46+
thing = models.FileField(upload_to=upload_to)
47+
48+
4349
class OperationWriterTests(SimpleTestCase):
4450

4551
def test_empty_signature(self):
@@ -472,21 +478,12 @@ def test_serialize_builtins(self):
472478
self.assertEqual(string, 'range')
473479
self.assertEqual(imports, set())
474480

475-
def test_serialize_local_function_reference(self):
476-
"""
477-
Neither py2 or py3 can serialize a reference in a local scope.
478-
"""
479-
class TestModel2:
480-
def upload_to(self):
481-
return "somewhere dynamic"
482-
thing = models.FileField(upload_to=upload_to)
483-
with self.assertRaises(ValueError):
484-
self.serialize_round_trip(TestModel2.thing)
481+
def test_serialize_unbound_method_reference(self):
482+
"""An unbound method used within a class body can be serialized."""
483+
self.serialize_round_trip(TestModel1.thing)
485484

486-
def test_serialize_local_function_reference_message(self):
487-
"""
488-
Make sure user is seeing which module/function is the issue
489-
"""
485+
def test_serialize_local_function_reference(self):
486+
"""A reference in a local scope can't be serialized."""
490487
class TestModel2:
491488
def upload_to(self):
492489
return "somewhere dynamic"

tests/test_client/test_conditional_content_removal.py

+1-10
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,10 @@
11
import gzip
2-
import io
32

43
from django.http import HttpRequest, HttpResponse, StreamingHttpResponse
54
from django.test import SimpleTestCase
65
from django.test.client import conditional_content_removal
76

87

9-
# based on Python 3.3's gzip.compress
10-
def gzip_compress(data):
11-
buf = io.BytesIO()
12-
with gzip.GzipFile(fileobj=buf, mode='wb', compresslevel=0) as f:
13-
f.write(data)
14-
return buf.getvalue()
15-
16-
178
class ConditionalContentTests(SimpleTestCase):
189

1910
def test_conditional_content_removal(self):
@@ -43,7 +34,7 @@ def test_conditional_content_removal(self):
4334
self.assertEqual(b''.join(res), b'')
4435

4536
# Issue #20472
46-
abc = gzip_compress(b'abc')
37+
abc = gzip.compress(b'abc')
4738
res = HttpResponse(abc, status=304)
4839
res['Content-Encoding'] = 'gzip'
4940
conditional_content_removal(req, res)

0 commit comments

Comments
 (0)