From 115318051c092f6ca8240262bd8b17b9e56ab838 Mon Sep 17 00:00:00 2001 From: Aymeric Augustin Date: Mon, 2 Sep 2013 12:06:32 +0200 Subject: [PATCH] [1.6.x] Replaced "not PY3" by "PY2", new in six 1.4.0. Conflicts: django/db/backends/oracle/base.py django/db/backends/sqlite3/base.py django/db/models/base.py Backport of 365c3e8b from master. --- django/contrib/auth/management/__init__.py | 2 +- django/contrib/auth/tests/test_basic.py | 4 ++-- django/core/mail/message.py | 2 +- django/db/backends/mysql/base.py | 2 +- django/db/backends/oracle/base.py | 10 +++++----- django/db/backends/sqlite3/base.py | 2 +- django/db/models/base.py | 2 +- django/http/cookie.py | 2 +- django/template/loaders/app_directories.py | 4 ++-- django/template/loaders/eggs.py | 2 +- django/utils/_os.py | 6 +++--- django/utils/encoding.py | 2 +- django/utils/feedgenerator.py | 4 ++-- django/utils/functional.py | 2 +- django/utils/http.py | 4 ++-- django/utils/text.py | 2 +- docs/topics/python3.txt | 10 ++++------ tests/base/models.py | 2 +- tests/basic/tests.py | 2 +- tests/defaultfilters/tests.py | 2 +- tests/httpwrappers/tests.py | 14 +++++++------- tests/i18n/tests.py | 2 +- tests/signing/tests.py | 4 ++-- tests/test_utils/doctest_output.py | 2 +- tests/utils_tests/test_datastructures.py | 2 +- tests/utils_tests/test_http.py | 4 ++-- tests/utils_tests/test_simplelazyobject.py | 2 +- 27 files changed, 48 insertions(+), 50 deletions(-) diff --git a/django/contrib/auth/management/__init__.py b/django/contrib/auth/management/__init__.py index 1f338469f8..7b0f5ad548 100644 --- a/django/contrib/auth/management/__init__.py +++ b/django/contrib/auth/management/__init__.py @@ -141,7 +141,7 @@ def get_system_username(): # if there is no corresponding entry in the /etc/passwd file # (a very restricted chroot environment, for example). return '' - if not six.PY3: + if six.PY2: try: result = result.decode(DEFAULT_LOCALE_ENCODING) except UnicodeDecodeError: diff --git a/django/contrib/auth/tests/test_basic.py b/django/contrib/auth/tests/test_basic.py index 6b1dd3af05..8dc9af5d85 100644 --- a/django/contrib/auth/tests/test_basic.py +++ b/django/contrib/auth/tests/test_basic.py @@ -16,7 +16,7 @@ from django.test.signals import setting_changed from django.test.utils import override_settings from django.utils import translation from django.utils.encoding import force_str -from django.utils.six import binary_type, PY3, StringIO +from django.utils.six import binary_type, PY2, StringIO @receiver(setting_changed) @@ -39,7 +39,7 @@ def mock_inputs(inputs): class mock_getpass: @staticmethod def getpass(prompt=b'Password: ', stream=None): - if not PY3: + if PY2: # getpass on Windows only supports prompt as bytestring (#19807) assert isinstance(prompt, binary_type) return inputs['password'] diff --git a/django/core/mail/message.py b/django/core/mail/message.py index 98ab3c9075..a3b36df832 100644 --- a/django/core/mail/message.py +++ b/django/core/mail/message.py @@ -322,7 +322,7 @@ class EmailMessage(object): try: filename.encode('ascii') except UnicodeEncodeError: - if not six.PY3: + if six.PY2: filename = filename.encode('utf-8') filename = ('utf-8', '', filename) attachment.add_header('Content-Disposition', 'attachment', diff --git a/django/db/backends/mysql/base.py b/django/db/backends/mysql/base.py index d10be94f43..fa64175ffc 100644 --- a/django/db/backends/mysql/base.py +++ b/django/db/backends/mysql/base.py @@ -409,7 +409,7 @@ class DatabaseWrapper(BaseDatabaseWrapper): 'conv': django_conversions, 'charset': 'utf8', } - if not six.PY3: + if six.PY2: kwargs['use_unicode'] = True settings_dict = self.settings_dict if settings_dict['USER']: diff --git a/django/db/backends/oracle/base.py b/django/db/backends/oracle/base.py index 6c510f34b5..9e7dd03fc2 100644 --- a/django/db/backends/oracle/base.py +++ b/django/db/backends/oracle/base.py @@ -267,7 +267,7 @@ WHEN (new.%(col_name)s IS NULL) # http://cx-oracle.sourceforge.net/html/cursor.html#Cursor.statement # The DB API definition does not define this attribute. statement = cursor.statement - if statement and not six.PY3 and not isinstance(statement, unicode): + if statement and six.PY2 and not isinstance(statement, unicode): statement = statement.decode('utf-8') # Unlike Psycopg's `query` and MySQLdb`'s `_last_executed`, CxOracle's # `statement` doesn't contain the query parameters. refs #20010. @@ -576,7 +576,7 @@ class DatabaseWrapper(BaseDatabaseWrapper): cursor.execute("SELECT 1 FROM DUAL WHERE DUMMY %s" % self._standard_operators['contains'], ['X']) - except DatabaseError: + except DatabaseError: self.operators = self._likec_operators else: self.operators = self._standard_operators @@ -778,7 +778,7 @@ class FormatStylePlaceholderCursor(object): for i, value in enumerate(params): if value.input_size: sizes[i] = value.input_size - self.setinputsizes(*sizes) + self.setinputsizes(*sizes) def _param_generator(self, params): # Try dict handling; if that fails, treat as sequence @@ -806,7 +806,7 @@ class FormatStylePlaceholderCursor(object): args = [(':arg%d' % i) for i in range(len(params))] query = convert_unicode(query % tuple(args), self.charset) return query, self._format_params(params) - + def execute(self, query, params=None): query, params = self._fix_for_params(query, params) self._guess_input_sizes([params]) @@ -825,7 +825,7 @@ class FormatStylePlaceholderCursor(object): # uniform treatment for sequences and iterables params_iter = iter(params) query, firstparams = self._fix_for_params(query, next(params_iter)) - # we build a list of formatted params; as we're going to traverse it + # we build a list of formatted params; as we're going to traverse it # more than once, we can't make it lazy by using a generator formatted = [firstparams]+[self._format_params(p) for p in params_iter] self._guess_input_sizes(formatted) diff --git a/django/db/backends/sqlite3/base.py b/django/db/backends/sqlite3/base.py index 3a0a9f57b7..2255cc2a8c 100644 --- a/django/db/backends/sqlite3/base.py +++ b/django/db/backends/sqlite3/base.py @@ -78,7 +78,7 @@ Database.register_converter(str("decimal"), decoder(util.typecast_decimal)) Database.register_adapter(datetime.datetime, adapt_datetime_with_timezone_support) Database.register_adapter(decimal.Decimal, util.rev_typecast_decimal) -if not six.PY3 and Database.version_info >= (2, 4, 1): +if six.PY2 and Database.version_info >= (2, 4, 1): # Starting in 2.4.1, the str type is not accepted anymore, therefore, # we convert all str objects to Unicode # As registering a adapter for a primitive type causes a small diff --git a/django/db/models/base.py b/django/db/models/base.py index 29846bcfa2..dfb4fae24c 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -426,7 +426,7 @@ class Model(six.with_metaclass(ModelBase)): return force_str('<%s: %s>' % (self.__class__.__name__, u)) def __str__(self): - if not six.PY3 and hasattr(self, '__unicode__'): + if six.PY2 and hasattr(self, '__unicode__'): if type(self).__unicode__ == Model.__str__: klass_name = type(self).__name__ raise RuntimeError("%s.__unicode__ is aliased to __str__. Did" diff --git a/django/http/cookie.py b/django/http/cookie.py index 50ff549caf..b0b5350036 100644 --- a/django/http/cookie.py +++ b/django/http/cookie.py @@ -49,7 +49,7 @@ else: if not _cookie_allows_colon_in_names: def load(self, rawdata): self.bad_cookies = set() - if not six.PY3 and isinstance(rawdata, six.text_type): + if six.PY2 and isinstance(rawdata, six.text_type): rawdata = force_str(rawdata) super(SimpleCookie, self).load(rawdata) for key in self.bad_cookies: diff --git a/django/template/loaders/app_directories.py b/django/template/loaders/app_directories.py index cea01558d9..c82817a2d8 100644 --- a/django/template/loaders/app_directories.py +++ b/django/template/loaders/app_directories.py @@ -15,7 +15,7 @@ from django.utils.importlib import import_module from django.utils import six # At compile time, cache the directories to search. -if not six.PY3: +if six.PY2: fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding() app_template_dirs = [] for app in settings.INSTALLED_APPS: @@ -25,7 +25,7 @@ for app in settings.INSTALLED_APPS: raise ImproperlyConfigured('ImportError %s: %s' % (app, e.args[0])) template_dir = os.path.join(os.path.dirname(mod.__file__), 'templates') if os.path.isdir(template_dir): - if not six.PY3: + if six.PY2: template_dir = template_dir.decode(fs_encoding) app_template_dirs.append(template_dir) diff --git a/django/template/loaders/eggs.py b/django/template/loaders/eggs.py index b7dcc75be3..7da180323a 100644 --- a/django/template/loaders/eggs.py +++ b/django/template/loaders/eggs.py @@ -27,7 +27,7 @@ class Loader(BaseLoader): resource = resource_string(app, pkg_name) except Exception: continue - if not six.PY3: + if six.PY2: resource = resource.decode(settings.FILE_CHARSET) return (resource, 'egg:%s:%s' % (app, pkg_name)) raise TemplateDoesNotExist(template_name) diff --git a/django/utils/_os.py b/django/utils/_os.py index 607e02c94d..3e60c1082c 100644 --- a/django/utils/_os.py +++ b/django/utils/_os.py @@ -12,7 +12,7 @@ except NameError: class WindowsError(Exception): pass -if not six.PY3: +if six.PY2: fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding() @@ -38,7 +38,7 @@ def upath(path): """ Always return a unicode path. """ - if not six.PY3 and not isinstance(path, six.text_type): + if six.PY2 and not isinstance(path, six.text_type): return path.decode(fs_encoding) return path @@ -47,7 +47,7 @@ def npath(path): Always return a native path, that is unicode on Python 3 and bytestring on Python 2. """ - if not six.PY3 and not isinstance(path, bytes): + if six.PY2 and not isinstance(path, bytes): return path.encode(fs_encoding) return path diff --git a/django/utils/encoding.py b/django/utils/encoding.py index adab0d0712..116178c4c2 100644 --- a/django/utils/encoding.py +++ b/django/utils/encoding.py @@ -54,7 +54,7 @@ def python_2_unicode_compatible(klass): To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. """ - if not six.PY3: + if six.PY2: klass.__unicode__ = klass.__str__ klass.__str__ = lambda self: self.__unicode__().encode('utf-8') return klass diff --git a/django/utils/feedgenerator.py b/django/utils/feedgenerator.py index 7eba842a89..ed9ddda6fe 100644 --- a/django/utils/feedgenerator.py +++ b/django/utils/feedgenerator.py @@ -46,7 +46,7 @@ def rfc2822_date(date): dow = days[date.weekday()] month = months[date.month - 1] time_str = date.strftime('%s, %%d %s %%Y %%H:%%M:%%S ' % (dow, month)) - if not six.PY3: # strftime returns a byte string in Python 2 + if six.PY2: # strftime returns a byte string in Python 2 time_str = time_str.decode('utf-8') if is_aware(date): offset = date.tzinfo.utcoffset(date) @@ -60,7 +60,7 @@ def rfc3339_date(date): # Support datetime objects older than 1900 date = datetime_safe.new_datetime(date) time_str = date.strftime('%Y-%m-%dT%H:%M:%S') - if not six.PY3: # strftime returns a byte string in Python 2 + if six.PY2: # strftime returns a byte string in Python 2 time_str = time_str.decode('utf-8') if is_aware(date): offset = date.tzinfo.utcoffset(date) diff --git a/django/utils/functional.py b/django/utils/functional.py index 93befcf59e..6c6399971b 100644 --- a/django/utils/functional.py +++ b/django/utils/functional.py @@ -162,7 +162,7 @@ def lazy(func, *resultclasses): return hash(self.__cast()) def __mod__(self, rhs): - if self._delegate_bytes and not six.PY3: + if self._delegate_bytes and six.PY2: return bytes(self) % rhs elif self._delegate_text: return six.text_type(self) % rhs diff --git a/django/utils/http.py b/django/utils/http.py index ffaf4e9657..85af230dd2 100644 --- a/django/utils/http.py +++ b/django/utils/http.py @@ -171,7 +171,7 @@ def base36_to_int(s): value = int(s, 36) # ... then do a final check that the value will fit into an int to avoid # returning a long (#15067). The long type was removed in Python 3. - if not six.PY3 and value > sys.maxint: + if six.PY2 and value > sys.maxint: raise ValueError("Base36 input too large") return value @@ -183,7 +183,7 @@ def int_to_base36(i): factor = 0 if i < 0: raise ValueError("Negative base36 conversion input.") - if not six.PY3: + if six.PY2: if not isinstance(i, six.integer_types): raise TypeError("Non-integer base36 conversion input.") if i > sys.maxint: diff --git a/django/utils/text.py b/django/utils/text.py index 7bb8e7eb3e..6329b36df8 100644 --- a/django/utils/text.py +++ b/django/utils/text.py @@ -12,7 +12,7 @@ from django.utils.six.moves import html_entities from django.utils.translation import ugettext_lazy, ugettext as _, pgettext from django.utils.safestring import mark_safe -if not six.PY3: +if six.PY2: # Import force_unicode even though this module doesn't use it, because some # people rely on it being here. from django.utils.encoding import force_unicode diff --git a/docs/topics/python3.txt b/docs/topics/python3.txt index 9a0438e9e5..8f2306962b 100644 --- a/docs/topics/python3.txt +++ b/docs/topics/python3.txt @@ -376,15 +376,13 @@ explicitly tries both locations, as follows:: except ImportError: # Python 2 from urlparse import urlparse, urlunparse -PY3 +PY2 ~~~ -If you need different code in Python 2 and Python 3, check :data:`six.PY3`:: +If you need different code in Python 2 and Python 3, check :data:`six.PY2`:: - if six.PY3: - # do stuff Python 3-wise - else: - # do stuff Python 2-wise + if six.PY2: + # compatibility code for Python 2 This is a last resort solution when :mod:`six` doesn't provide an appropriate function. diff --git a/tests/base/models.py b/tests/base/models.py index d47ddcfd66..98d379337c 100644 --- a/tests/base/models.py +++ b/tests/base/models.py @@ -19,7 +19,7 @@ class MyModel(six.with_metaclass(CustomBaseModel, models.Model)): # This is done to ensure that for Python2 only, defining metaclasses # still does not fail to create the model. -if not six.PY3: +if six.PY2: class MyModel(models.Model): """Model subclass with a custom base using __metaclass__.""" __metaclass__ = CustomBaseModel diff --git a/tests/basic/tests.py b/tests/basic/tests.py index d8c0964288..6795abb0e7 100644 --- a/tests/basic/tests.py +++ b/tests/basic/tests.py @@ -350,7 +350,7 @@ class ModelTest(TestCase): ""]) # Slicing works with longs (Python 2 only -- Python 3 doesn't have longs). - if not six.PY3: + if six.PY2: self.assertEqual(Article.objects.all()[long(0)], a) self.assertQuerysetEqual(Article.objects.all()[long(1):long(3)], ["", ""]) diff --git a/tests/defaultfilters/tests.py b/tests/defaultfilters/tests.py index 56b32ae623..ca8d99340a 100644 --- a/tests/defaultfilters/tests.py +++ b/tests/defaultfilters/tests.py @@ -88,7 +88,7 @@ class DefaultFiltersTests(TestCase): # The test above fails because of Python 2's float handling. Floats with # many zeroes after the decimal point should be passed in as another type # such as unicode or Decimal. - if not six.PY3: + if six.PY2: test_floatformat_py2_fail = unittest.expectedFailure(test_floatformat_py2_fail) diff --git a/tests/httpwrappers/tests.py b/tests/httpwrappers/tests.py index 8e0c415623..7eb11b1dc7 100644 --- a/tests/httpwrappers/tests.py +++ b/tests/httpwrappers/tests.py @@ -46,7 +46,7 @@ class QueryDictTests(unittest.TestCase): def test_immutable_basic_operations(self): q = QueryDict(str('')) self.assertEqual(q.getlist('foo'), []) - if not six.PY3: + if six.PY2: self.assertEqual(q.has_key('foo'), False) self.assertEqual('foo' in q, False) self.assertEqual(list(six.iteritems(q)), []) @@ -72,10 +72,10 @@ class QueryDictTests(unittest.TestCase): self.assertRaises(AttributeError, q.setlist, 'foo', ['bar']) self.assertRaises(AttributeError, q.appendlist, 'foo', ['bar']) - if not six.PY3: + if six.PY2: self.assertTrue(q.has_key('foo')) self.assertTrue('foo' in q) - if not six.PY3: + if six.PY2: self.assertFalse(q.has_key('bar')) self.assertFalse('bar' in q) @@ -131,7 +131,7 @@ class QueryDictTests(unittest.TestCase): q.appendlist('foo', 'another') self.assertEqual(q.getlist('foo'), ['bar', 'baz', 'another']) self.assertEqual(q['foo'], 'another') - if not six.PY3: + if six.PY2: self.assertTrue(q.has_key('foo')) self.assertTrue('foo' in q) @@ -176,10 +176,10 @@ class QueryDictTests(unittest.TestCase): self.assertRaises(AttributeError, q.setlist, 'foo', ['bar', 'baz']) self.assertRaises(AttributeError, q.appendlist, 'foo', ['bar']) - if not six.PY3: + if six.PY2: self.assertEqual(q.has_key('vote'), True) self.assertEqual('vote' in q, True) - if not six.PY3: + if six.PY2: self.assertEqual(q.has_key('foo'), False) self.assertEqual('foo' in q, False) self.assertEqual(list(six.iteritems(q)), [('vote', 'no')]) @@ -195,7 +195,7 @@ class QueryDictTests(unittest.TestCase): self.assertRaises(AttributeError, q.setdefault, 'foo', 'bar') self.assertRaises(AttributeError, q.__delitem__, 'vote') - if not six.PY3: + if six.PY2: def test_invalid_input_encoding(self): """ QueryDicts must be able to handle invalid input encoding (in this diff --git a/tests/i18n/tests.py b/tests/i18n/tests.py index bd61943cc1..79faa4d01b 100644 --- a/tests/i18n/tests.py +++ b/tests/i18n/tests.py @@ -89,7 +89,7 @@ class TranslationTests(TransRealMixin, TestCase): s4 = ugettext_lazy('Some other string') self.assertEqual(False, s == s4) - if not six.PY3: + if six.PY2: # On Python 2, gettext_lazy should not transform a bytestring to unicode self.assertEqual(gettext_lazy(b"test").upper(), b"TEST") diff --git a/tests/signing/tests.py b/tests/signing/tests.py index 05c8b3dc74..5c5c2b1da7 100644 --- a/tests/signing/tests.py +++ b/tests/signing/tests.py @@ -48,7 +48,7 @@ class TestSigner(TestCase): 'jkw osanteuh ,rcuh nthu aou oauh ,ud du', '\u2019', ] - if not six.PY3: + if six.PY2: examples.append(b'a byte string') for example in examples: signed = signer.sign(example) @@ -79,7 +79,7 @@ class TestSigner(TestCase): 'a unicode string \u2019', {'a': 'dictionary'}, ] - if not six.PY3: + if six.PY2: objects.append(b'a byte string') for o in objects: self.assertNotEqual(o, signing.dumps(o)) diff --git a/tests/test_utils/doctest_output.py b/tests/test_utils/doctest_output.py index 724364428a..0d1e94d037 100644 --- a/tests/test_utils/doctest_output.py +++ b/tests/test_utils/doctest_output.py @@ -59,7 +59,7 @@ __test__ = {"API_TEST": r""" """} -if not six.PY3: +if six.PY2: __test__["API_TEST"] += """ >>> def produce_long(): ... return 42L diff --git a/tests/utils_tests/test_datastructures.py b/tests/utils_tests/test_datastructures.py index 5829e7c2d7..2692b85a7d 100644 --- a/tests/utils_tests/test_datastructures.py +++ b/tests/utils_tests/test_datastructures.py @@ -50,7 +50,7 @@ class SortedDictTests(SimpleTestCase): self.d2[7] = 'lucky number 7' self.assertEqual(list(six.iterkeys(self.d2)), [1, 9, 0, 7]) - if not six.PY3: + if six.PY2: def test_change_keys(self): """ Changing the keys won't do anything, it's only a copy of the diff --git a/tests/utils_tests/test_http.py b/tests/utils_tests/test_http.py index 6d3bc025af..c9959918a2 100644 --- a/tests/utils_tests/test_http.py +++ b/tests/utils_tests/test_http.py @@ -115,12 +115,12 @@ class TestUtilsHttp(unittest.TestCase): # reciprocity works for n in [0, 1, 1000, 1000000]: self.assertEqual(n, http.base36_to_int(http.int_to_base36(n))) - if not six.PY3: + if six.PY2: self.assertEqual(sys.maxint, http.base36_to_int(http.int_to_base36(sys.maxint))) # bad input self.assertRaises(ValueError, http.int_to_base36, -1) - if not six.PY3: + if six.PY2: self.assertRaises(ValueError, http.int_to_base36, sys.maxint + 1) for n in ['1', 'foo', {1: 2}, (1, 2, 3), 3.141]: self.assertRaises(TypeError, http.int_to_base36, n) diff --git a/tests/utils_tests/test_simplelazyobject.py b/tests/utils_tests/test_simplelazyobject.py index 4c01bd3adf..1b3393cdd8 100644 --- a/tests/utils_tests/test_simplelazyobject.py +++ b/tests/utils_tests/test_simplelazyobject.py @@ -178,7 +178,7 @@ class TestUtilsSimpleLazyObject(TestCase): pickled = pickle.dumps(x, 1) pickled = pickle.dumps(x, 2) - if not six.PY3: + if six.PY2: import cPickle # This would fail with "TypeError: expected string or Unicode object, NoneType found".