Merge ~cjwatson/launchpad:py3-cmp into launchpad:master

Proposed by Colin Watson
Status: Merged
Approved by: Colin Watson
Approved revision: 688851cb3b5ebb14c232712a95400bafe078aef7
Merge reported by: Otto Co-Pilot
Merged at revision: not available
Proposed branch: ~cjwatson/launchpad:py3-cmp
Merge into: launchpad:master
Diff against target: 406 lines (+64/-77)
10 files modified
lib/lp/archivepublisher/domination.py (+8/-4)
lib/lp/archivepublisher/tests/test_dominator.py (+10/-6)
lib/lp/archiveuploader/tests/nascentupload-announcements.txt (+1/-4)
lib/lp/bugs/doc/initial-bug-contacts.txt (+2/-4)
lib/lp/registry/browser/product.py (+5/-8)
lib/lp/registry/doc/distribution-mirror.txt (+2/-1)
lib/lp/registry/doc/teammembership-email-notification.txt (+3/-4)
lib/lp/registry/tests/test_distroseriesdifferencecomment.py (+2/-7)
lib/lp/services/doc/orderingcheck.txt (+1/-4)
lib/lp/services/webapp/sorting.py (+30/-35)
Reviewer Review Type Date Requested Status
Ioana Lasc (community) Approve
Review via email: mp+394483@code.launchpad.net

Commit message

Stop using cmp() and sorted(cmp=...)

Description of the change

These are no longer supported in Python 3; we need to use constructions involving sorted(key=...) instead.

To post a comment you must log in.
Revision history for this message
Ioana Lasc (ilasc) :
review: Approve

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
diff --git a/lib/lp/archivepublisher/domination.py b/lib/lp/archivepublisher/domination.py
index 356a2ee..0e9a8b0 100644
--- a/lib/lp/archivepublisher/domination.py
+++ b/lib/lp/archivepublisher/domination.py
@@ -54,6 +54,7 @@ __all__ = ['Dominator']
5454
55from collections import defaultdict55from collections import defaultdict
56from datetime import timedelta56from datetime import timedelta
57from functools import cmp_to_key
57from operator import (58from operator import (
58 attrgetter,59 attrgetter,
59 itemgetter,60 itemgetter,
@@ -198,14 +199,16 @@ class GeneralizedPublication:
198 self.getPackageVersion(pub1), self.getPackageVersion(pub2))199 self.getPackageVersion(pub1), self.getPackageVersion(pub2))
199200
200 if version_comparison == 0:201 if version_comparison == 0:
201 # Use dates as tie breaker.202 # Use dates as tie breaker (idiom equivalent to Python 2's cmp).
202 return cmp(pub1.datecreated, pub2.datecreated)203 return (
204 (pub1.datecreated > pub2.datecreated) -
205 (pub1.datecreated < pub2.datecreated))
203 else:206 else:
204 return version_comparison207 return version_comparison
205208
206 def sortPublications(self, publications):209 def sortPublications(self, publications):
207 """Sort publications from most to least current versions."""210 """Sort publications from most to least current versions."""
208 return sorted(publications, cmp=self.compare, reverse=True)211 return sorted(publications, key=cmp_to_key(self.compare), reverse=True)
209212
210213
211def find_live_source_versions(sorted_pubs):214def find_live_source_versions(sorted_pubs):
@@ -417,7 +420,8 @@ class Dominator:
417 len(sorted_pubs), live_versions)420 len(sorted_pubs), live_versions)
418421
419 # Verify that the publications are really sorted properly.422 # Verify that the publications are really sorted properly.
420 check_order = OrderingCheck(cmp=generalization.compare, reverse=True)423 check_order = OrderingCheck(
424 key=cmp_to_key(generalization.compare), reverse=True)
421425
422 current_dominant = None426 current_dominant = None
423 dominant_version = None427 dominant_version = None
diff --git a/lib/lp/archivepublisher/tests/test_dominator.py b/lib/lp/archivepublisher/tests/test_dominator.py
index 4d073e0..b35596e 100755
--- a/lib/lp/archivepublisher/tests/test_dominator.py
+++ b/lib/lp/archivepublisher/tests/test_dominator.py
@@ -8,6 +8,7 @@ from __future__ import absolute_import, print_function, unicode_literals
8__metaclass__ = type8__metaclass__ = type
99
10import datetime10import datetime
11from functools import cmp_to_key
11from operator import attrgetter12from operator import attrgetter
1213
13import apt_pkg14import apt_pkg
@@ -559,7 +560,8 @@ class TestGeneralizedPublication(TestCaseWithFactory):
559 '1.1v3',560 '1.1v3',
560 ]561 ]
561 spphs = make_spphs_for_versions(self.factory, versions)562 spphs = make_spphs_for_versions(self.factory, versions)
562 sorted_spphs = sorted(spphs, cmp=GeneralizedPublication().compare)563 sorted_spphs = sorted(
564 spphs, key=cmp_to_key(GeneralizedPublication().compare))
563 self.assertEqual(565 self.assertEqual(
564 sorted(versions), list_source_versions(sorted_spphs))566 sorted(versions), list_source_versions(sorted_spphs))
565567
@@ -572,16 +574,18 @@ class TestGeneralizedPublication(TestCaseWithFactory):
572 ]574 ]
573 spphs = make_spphs_for_versions(self.factory, versions)575 spphs = make_spphs_for_versions(self.factory, versions)
574576
575 debian_sorted_versions = sorted(versions, cmp=apt_pkg.version_compare)577 debian_sorted_versions = sorted(
578 versions, key=cmp_to_key(apt_pkg.version_compare))
576579
577 # Assumption: in this case, Debian version ordering is not the580 # Assumption: in this case, Debian version ordering is not the
578 # same as alphabetical version ordering.581 # same as alphabetical version ordering.
579 self.assertNotEqual(sorted(versions), debian_sorted_versions)582 self.assertNotEqual(sorted(versions), debian_sorted_versions)
580583
581 # The compare method produces the Debian ordering.584 # The compare method produces the Debian ordering.
582 sorted_spphs = sorted(spphs, cmp=GeneralizedPublication().compare)585 sorted_spphs = sorted(
586 spphs, key=cmp_to_key(GeneralizedPublication().compare))
583 self.assertEqual(587 self.assertEqual(
584 sorted(versions, cmp=apt_pkg.version_compare),588 sorted(versions, key=cmp_to_key(apt_pkg.version_compare)),
585 list_source_versions(sorted_spphs))589 list_source_versions(sorted_spphs))
586590
587 def test_compare_breaks_tie_with_creation_date(self):591 def test_compare_breaks_tie_with_creation_date(self):
@@ -605,7 +609,7 @@ class TestGeneralizedPublication(TestCaseWithFactory):
605609
606 self.assertEqual(610 self.assertEqual(
607 [spphs[2], spphs[0], spphs[1]],611 [spphs[2], spphs[0], spphs[1]],
608 sorted(spphs, cmp=GeneralizedPublication().compare))612 sorted(spphs, key=cmp_to_key(GeneralizedPublication().compare)))
609613
610 def test_compare_breaks_tie_for_releases_with_same_version(self):614 def test_compare_breaks_tie_for_releases_with_same_version(self):
611 # When two publications are tied for comparison because they615 # When two publications are tied for comparison because they
@@ -629,7 +633,7 @@ class TestGeneralizedPublication(TestCaseWithFactory):
629633
630 self.assertEqual(634 self.assertEqual(
631 [spphs[2], spphs[0], spphs[1]],635 [spphs[2], spphs[0], spphs[1]],
632 sorted(spphs, cmp=GeneralizedPublication().compare))636 sorted(spphs, key=cmp_to_key(GeneralizedPublication().compare)))
633637
634638
635def jumble(ordered_list):639def jumble(ordered_list):
diff --git a/lib/lp/archiveuploader/tests/nascentupload-announcements.txt b/lib/lp/archiveuploader/tests/nascentupload-announcements.txt
index 017601f..cd512c3 100644
--- a/lib/lp/archiveuploader/tests/nascentupload-announcements.txt
+++ b/lib/lp/archiveuploader/tests/nascentupload-announcements.txt
@@ -38,14 +38,11 @@ We need to be logged into the security model in order to get any further
38 >>> switch_dbuser('launchpad')38 >>> switch_dbuser('launchpad')
39 >>> login('foo.bar@canonical.com')39 >>> login('foo.bar@canonical.com')
4040
41Helper functions to examine emails that were sent:41A helper function to examine emails that were sent:
4242
43 >>> from lp.services.mail import stub43 >>> from lp.services.mail import stub
44 >>> from lp.testing.mail_helpers import pop_notifications44 >>> from lp.testing.mail_helpers import pop_notifications
4545
46 >>> def by_to_addrs(a, b):
47 ... return cmp(a[1], b[1])
48
49 >>> def print_addrlist(field):46 >>> def print_addrlist(field):
50 ... for entry in sorted([addr.strip() for addr in field.split(',')]):47 ... for entry in sorted([addr.strip() for addr in field.split(',')]):
51 ... print entry48 ... print entry
diff --git a/lib/lp/bugs/doc/initial-bug-contacts.txt b/lib/lp/bugs/doc/initial-bug-contacts.txt
index 468658c..cd88e6f 100644
--- a/lib/lp/bugs/doc/initial-bug-contacts.txt
+++ b/lib/lp/bugs/doc/initial-bug-contacts.txt
@@ -157,12 +157,10 @@ track why daf received the email. The rational is repeated in the footer
157of the email with the bug title and URL.157of the email with the bug title and URL.
158158
159 >>> import email159 >>> import email
160160 >>> from operator import itemgetter
161 >>> def by_to_addrs(a, b):
162 ... return cmp(a[1], b[1])
163161
164 >>> test_emails = list(stub.test_emails)162 >>> test_emails = list(stub.test_emails)
165 >>> test_emails.sort(by_to_addrs)163 >>> test_emails.sort(key=itemgetter(1))
166164
167 >>> len(test_emails)165 >>> len(test_emails)
168 1166 1
diff --git a/lib/lp/registry/browser/product.py b/lib/lp/registry/browser/product.py
index e7dbe7e..36109fe 100644
--- a/lib/lp/registry/browser/product.py
+++ b/lib/lp/registry/browser/product.py
@@ -664,14 +664,12 @@ class ProductSpecificationsMenu(NavigationMenu, ProductEditLinksMixin,
664 'register_sprint']664 'register_sprint']
665665
666666
667def _cmp_distros(a, b):667def _distro_name_sort_key(name):
668 """Put Ubuntu first, otherwise in alpha order."""668 """Put Ubuntu first, otherwise in alpha order."""
669 if a == 'ubuntu':669 if name == 'ubuntu':
670 return -1670 return (0, )
671 elif b == 'ubuntu':
672 return 1
673 else:671 else:
674 return cmp(a, b)672 return (1, name)
675673
676674
677class ProductSetBreadcrumb(Breadcrumb):675class ProductSetBreadcrumb(Breadcrumb):
@@ -1227,8 +1225,7 @@ class ProductPackagesView(LaunchpadView):
1227 distros[distribution.name] = distro1225 distros[distribution.name] = distro
1228 distro['packagings'].append(packaging)1226 distro['packagings'].append(packaging)
1229 # Now we sort the resulting list of "distro" objects, and return that.1227 # Now we sort the resulting list of "distro" objects, and return that.
1230 distro_names = distros.keys()1228 distro_names = sorted(distros, key=_distro_name_sort_key)
1231 distro_names.sort(cmp=_cmp_distros)
1232 results = [distros[name] for name in distro_names]1229 results = [distros[name] for name in distro_names]
1233 return results1230 return results
12341231
diff --git a/lib/lp/registry/doc/distribution-mirror.txt b/lib/lp/registry/doc/distribution-mirror.txt
index 90bc89e..43e129c 100644
--- a/lib/lp/registry/doc/distribution-mirror.txt
+++ b/lib/lp/registry/doc/distribution-mirror.txt
@@ -341,10 +341,11 @@ up on the public mirror listings.
341 >>> transaction.commit()341 >>> transaction.commit()
342342
343 >>> import email343 >>> import email
344 >>> from operator import itemgetter
344 >>> from lp.services.mail import stub345 >>> from lp.services.mail import stub
345 >>> len(stub.test_emails)346 >>> len(stub.test_emails)
346 2347 2
347 >>> stub.test_emails.sort(lambda a, b: cmp(a[1], b[1])) # sort by to_addr348 >>> stub.test_emails.sort(key=itemgetter(1)) # sort by to_addr
348 >>> from_addr, to_addr, raw_message = stub.test_emails.pop()349 >>> from_addr, to_addr, raw_message = stub.test_emails.pop()
349 >>> msg = email.message_from_string(raw_message)350 >>> msg = email.message_from_string(raw_message)
350 >>> msg['To']351 >>> msg['To']
diff --git a/lib/lp/registry/doc/teammembership-email-notification.txt b/lib/lp/registry/doc/teammembership-email-notification.txt
index c1c323f..201cc48 100644
--- a/lib/lp/registry/doc/teammembership-email-notification.txt
+++ b/lib/lp/registry/doc/teammembership-email-notification.txt
@@ -7,8 +7,7 @@ where we might want to notify only the team admins, but in most of the
7cases we'll be sending two similar (but not identical) notifications:7cases we'll be sending two similar (but not identical) notifications:
8one for all team admins and another for the member.8one for all team admins and another for the member.
99
10 >>> def by_to_addrs(a, b):10 >>> from operator import itemgetter
11 ... return cmp(a[1], b[1])
1211
13 >>> def setStatus(membership, status, reviewer=None, comment=None,12 >>> def setStatus(membership, status, reviewer=None, comment=None,
14 ... silent=False):13 ... silent=False):
@@ -186,7 +185,7 @@ The same goes for approving a proposed member.
186 >>> setStatus(daf_membership, TeamMembershipStatus.APPROVED,185 >>> setStatus(daf_membership, TeamMembershipStatus.APPROVED,
187 ... reviewer=mark, comment='This is a nice guy; I like him')186 ... reviewer=mark, comment='This is a nice guy; I like him')
188 >>> run_mail_jobs()187 >>> run_mail_jobs()
189 >>> stub.test_emails.sort(by_to_addrs)188 >>> stub.test_emails.sort(key=itemgetter(1))
190 >>> len(stub.test_emails)189 >>> len(stub.test_emails)
191 6190 6
192191
@@ -236,7 +235,7 @@ The same for deactivating a membership.
236 >>> setStatus(daf_membership, TeamMembershipStatus.DEACTIVATED,235 >>> setStatus(daf_membership, TeamMembershipStatus.DEACTIVATED,
237 ... reviewer=mark)236 ... reviewer=mark)
238 >>> run_mail_jobs()237 >>> run_mail_jobs()
239 >>> stub.test_emails.sort(by_to_addrs)238 >>> stub.test_emails.sort(key=itemgetter(1))
240 >>> len(stub.test_emails)239 >>> len(stub.test_emails)
241 6240 6
242241
diff --git a/lib/lp/registry/tests/test_distroseriesdifferencecomment.py b/lib/lp/registry/tests/test_distroseriesdifferencecomment.py
index beeaecd..f95aac7 100644
--- a/lib/lp/registry/tests/test_distroseriesdifferencecomment.py
+++ b/lib/lp/registry/tests/test_distroseriesdifferencecomment.py
@@ -6,7 +6,7 @@
6__metaclass__ = type6__metaclass__ = type
77
8from datetime import timedelta8from datetime import timedelta
9from random import randint9from random import random
1010
11from storm.store import Store11from storm.store import Store
12from zope.component import getUtility12from zope.component import getUtility
@@ -31,14 +31,9 @@ def get_comment_source():
31 return getUtility(IDistroSeriesDifferenceCommentSource)31 return getUtility(IDistroSeriesDifferenceCommentSource)
3232
3333
34def flip_coin(*args):
35 """Random comparison function. Returns -1 or 1 randomly."""
36 return 1 - 2 * randint(0, 1)
37
38
39def randomize_list(original_list):34def randomize_list(original_list):
40 """Sort a list (or other iterable) in random order. Return list."""35 """Sort a list (or other iterable) in random order. Return list."""
41 return sorted(original_list, cmp=flip_coin)36 return sorted(original_list, key=lambda _: random)
4237
4338
44class DistroSeriesDifferenceCommentTestCase(TestCaseWithFactory):39class DistroSeriesDifferenceCommentTestCase(TestCaseWithFactory):
diff --git a/lib/lp/services/doc/orderingcheck.txt b/lib/lp/services/doc/orderingcheck.txt
index 9ed2b0b..fe9294f 100644
--- a/lib/lp/services/doc/orderingcheck.txt
+++ b/lib/lp/services/doc/orderingcheck.txt
@@ -29,10 +29,7 @@ Sorting criteria
29The OrderingCheck accepts all the same sorting options (as keyword args)29The OrderingCheck accepts all the same sorting options (as keyword args)
30as Python's built-in sorting functions.30as Python's built-in sorting functions.
3131
32 >>> def sort_cmp(left_item, right_item):32 >>> checker = OrderingCheck(key=lambda v: v, reverse=True)
33 ... return left_item - right_item
34
35 >>> checker = OrderingCheck(cmp=sort_cmp, reverse=True)
36 >>> for number in (3, 2, 1):33 >>> for number in (3, 2, 1):
37 ... checker.check(number)34 ... checker.check(number)
3835
diff --git a/lib/lp/services/webapp/sorting.py b/lib/lp/services/webapp/sorting.py
index dc1a453..6d34142 100644
--- a/lib/lp/services/webapp/sorting.py
+++ b/lib/lp/services/webapp/sorting.py
@@ -16,14 +16,14 @@ import six
16def expand_numbers(unicode_text, fill_digits=4):16def expand_numbers(unicode_text, fill_digits=4):
17 """Return a copy of the string with numbers zero filled.17 """Return a copy of the string with numbers zero filled.
1818
19 >>> expand_numbers(u'hello world')19 >>> print(expand_numbers(u'hello world'))
20 u'hello world'20 hello world
21 >>> expand_numbers(u'0.12.1')21 >>> print(expand_numbers(u'0.12.1'))
22 u'0000.0012.0001'22 0000.0012.0001
23 >>> expand_numbers(u'0.12.1', 2)23 >>> print(expand_numbers(u'0.12.1', 2))
24 u'00.12.01'24 00.12.01
25 >>> expand_numbers(u'branch-2-3.12')25 >>> print(expand_numbers(u'branch-2-3.12'))
26 u'branch-0002-0003.0012'26 branch-0002-0003.0012
2727
28 """28 """
29 assert(isinstance(unicode_text, six.text_type))29 assert(isinstance(unicode_text, six.text_type))
@@ -40,26 +40,22 @@ reversed_numbers_table = dict(
40 zip(map(ord, u'0123456789'), reversed(u'0123456789')))40 zip(map(ord, u'0123456789'), reversed(u'0123456789')))
4141
4242
43def _reversed_number_comparator(lhs_text, rhs_text):43def _reversed_number_sort_key(text):
44 """Return comparison value reversed for numbers only.44 """Return comparison value reversed for numbers only.
4545
46 >>> _reversed_number_comparator(u'9.3', u'2.4')46 >>> print(_reversed_number_sort_key(u'9.3'))
47 -147 0.6
48 >>> _reversed_number_comparator(u'world', u'hello')48 >>> print(_reversed_number_sort_key(u'2.4'))
49 149 7.5
50 >>> _reversed_number_comparator(u'hello world', u'hello world')50 >>> print(_reversed_number_sort_key(u'hello'))
51 051 hello
52 >>> _reversed_number_comparator(u'dev', u'development')52 >>> print(_reversed_number_sort_key(u'bzr-0.13'))
53 -153 bzr-9.86
54 >>> _reversed_number_comparator(u'bzr-0.13', u'bzr-0.08')
55 -1
5654
57 """55 """
58 assert isinstance(lhs_text, six.text_type)56 assert isinstance(text, six.text_type)
59 assert isinstance(rhs_text, six.text_type)57 assert isinstance(text, six.text_type)
60 translated_lhs_text = lhs_text.translate(reversed_numbers_table)58 return text.translate(reversed_numbers_table)
61 translated_rhs_text = rhs_text.translate(reversed_numbers_table)
62 return cmp(translated_lhs_text, translated_rhs_text)
6359
6460
65def _identity(x):61def _identity(x):
@@ -71,13 +67,13 @@ def sorted_version_numbers(sequence, key=_identity):
7167
72 >>> bzr_versions = [u'0.9', u'0.10', u'0.11']68 >>> bzr_versions = [u'0.9', u'0.10', u'0.11']
73 >>> for version in sorted_version_numbers(bzr_versions):69 >>> for version in sorted_version_numbers(bzr_versions):
74 ... print version70 ... print(version)
75 0.1171 0.11
76 0.1072 0.10
77 0.973 0.9
78 >>> bzr_versions = [u'bzr-0.9', u'bzr-0.10', u'bzr-0.11']74 >>> bzr_versions = [u'bzr-0.9', u'bzr-0.10', u'bzr-0.11']
79 >>> for version in sorted_version_numbers(bzr_versions):75 >>> for version in sorted_version_numbers(bzr_versions):
80 ... print version76 ... print(version)
81 bzr-0.1177 bzr-0.11
82 bzr-0.1078 bzr-0.10
83 bzr-0.979 bzr-0.9
@@ -91,7 +87,7 @@ def sorted_version_numbers(sequence, key=_identity):
91 >>> from operator import attrgetter87 >>> from operator import attrgetter
92 >>> for version in sorted_version_numbers(bzr_versions,88 >>> for version in sorted_version_numbers(bzr_versions,
93 ... key=attrgetter('name')):89 ... key=attrgetter('name')):
94 ... print version.name90 ... print(version.name)
95 0.1191 0.11
96 0.1092 0.10
97 0.993 0.9
@@ -101,9 +97,9 @@ def sorted_version_numbers(sequence, key=_identity):
101 foo97 foo
10298
103 """99 """
104 expanded_key = lambda x: expand_numbers(key(x))100 return sorted(
105 return sorted(sequence, key=expanded_key,101 sequence,
106 cmp=_reversed_number_comparator)102 key=lambda x: _reversed_number_sort_key(expand_numbers(key(x))))
107103
108104
109def sorted_dotted_numbers(sequence, key=_identity):105def sorted_dotted_numbers(sequence, key=_identity):
@@ -117,13 +113,13 @@ def sorted_dotted_numbers(sequence, key=_identity):
117113
118 >>> bzr_versions = [u'0.9', u'0.10', u'0.11']114 >>> bzr_versions = [u'0.9', u'0.10', u'0.11']
119 >>> for version in sorted_dotted_numbers(bzr_versions):115 >>> for version in sorted_dotted_numbers(bzr_versions):
120 ... print version116 ... print(version)
121 0.9117 0.9
122 0.10118 0.10
123 0.11119 0.11
124 >>> bzr_versions = [u'bzr-0.9', u'bzr-0.10', u'bzr-0.11']120 >>> bzr_versions = [u'bzr-0.9', u'bzr-0.10', u'bzr-0.11']
125 >>> for version in sorted_dotted_numbers(bzr_versions):121 >>> for version in sorted_dotted_numbers(bzr_versions):
126 ... print version122 ... print(version)
127 bzr-0.9123 bzr-0.9
128 bzr-0.10124 bzr-0.10
129 bzr-0.11125 bzr-0.11
@@ -137,7 +133,7 @@ def sorted_dotted_numbers(sequence, key=_identity):
137 >>> from operator import attrgetter133 >>> from operator import attrgetter
138 >>> for version in sorted_dotted_numbers(bzr_versions,134 >>> for version in sorted_dotted_numbers(bzr_versions,
139 ... key=attrgetter('name')):135 ... key=attrgetter('name')):
140 ... print version.name136 ... print(version.name)
141 0.9137 0.9
142 0.10138 0.10
143 0.11139 0.11
@@ -147,5 +143,4 @@ def sorted_dotted_numbers(sequence, key=_identity):
147 foo143 foo
148144
149 """145 """
150 expanded_key = lambda x: expand_numbers(key(x))146 return sorted(sequence, key=lambda x: expand_numbers(key(x)))
151 return sorted(sequence, key=expanded_key)

Subscribers

People subscribed via source and target branches

to status/vote changes: