[Mesa-dev] [PATCH 21/26] python: Use key-functions when sorting containers
Eric Engestrom
eric.engestrom at intel.com
Thu Jul 5 16:59:52 UTC 2018
On Thursday, 2018-07-05 09:38:19 -0700, Dylan Baker wrote:
> Quoting Mathieu Bridon (2018-07-05 06:17:52)
> > In Python 2, the traditional way to sort containers was to use a
> > comparison function (which returned either -1, 0 or 1 when passed two
> > objects) and pass that as the "cmp" argument to the container's sort()
> > method.
> >
> > Python 2.4 introduced key-functions, which instead only operate on a
> > given item, and return a sorting key for this item.
> >
> > In general, this runs faster, because the cmp-function has to get run
> > multiple times for each item of the container.
> >
> > Python 3 removed the cmp-function, enforcing usage of key-functions
> > instead.
> >
> > This change makes the script compatible with Python 2 and Python 3.
> >
> > Signed-off-by: Mathieu Bridon <bochecha at daitauha.fr>
> > ---
> > src/mapi/mapi_abi.py | 5 +++--
> > 1 file changed, 3 insertions(+), 2 deletions(-)
> >
> > diff --git a/src/mapi/mapi_abi.py b/src/mapi/mapi_abi.py
> > index 67fdb10650..19fdc4572a 100644
> > --- a/src/mapi/mapi_abi.py
> > +++ b/src/mapi/mapi_abi.py
> > @@ -32,6 +32,7 @@ import os
> > GLAPI = os.path.join(".", os.path.dirname(sys.argv[0]), "glapi/gen")
> > sys.path.append(GLAPI)
> >
> > +from operator import attrgetter
> > import re
> > from optparse import OptionParser
> > import gl_XML
> > @@ -305,7 +306,7 @@ class ABIPrinter(object):
> >
> > # sort entries by their names
> > self.entries_sorted_by_names = self.entries[:]
> > - self.entries_sorted_by_names.sort(lambda x, y: cmp(x.name, y.name))
> > + self.entries_sorted_by_names.sort(key=attrgetter('name'))
>
> how about:
> self.entries_sorted_by_names = list(sorted(self.entries, key=attrgetter('name')))
>
> To avoid the copy and in-place sort.
Good idea; with that:
Reviewed-by: Eric Engestrom <eric.engestrom at intel.com>
>
> >
> > self.indent = ' ' * 3
> > self.noop_warn = 'noop_warn'
> > @@ -455,7 +456,7 @@ class ABIPrinter(object):
> > """Return the string pool for use by stubs."""
> > # sort entries by their names
> > sorted_entries = self.entries[:]
> > - sorted_entries.sort(lambda x, y: cmp(x.name, y.name))
> > + sorted_entries.sort(key=attrgetter('name'))
> >
> > pool = []
> > offsets = {}
> > --
> > 2.17.1
> >
> > _______________________________________________
> > mesa-dev mailing list
> > mesa-dev at lists.freedesktop.org
> > https://lists.freedesktop.org/mailman/listinfo/mesa-dev
More information about the mesa-dev
mailing list