[PATCH 2 of 2] coding style: use iterators instead of list comprehensions when possible

Augie Fackler durin42 at gmail.com
Wed Dec 16 23:19:03 CST 2009


On Dec 16, 2009, at 10:08 PM, Nicolas Dumazet wrote:

> # HG changeset patch
> # User Nicolas Dumazet <nicdumz.commits at gmail.com>
> # Date 1260525915 -32400
> # Node ID ceae6ff0555208531dc996a64bf268e5bde4dd4c
> # Parent  bdbd6e8667af6ba2fa42971bb02b003fc48b7633
> coding style: use iterators instead of list comprehensions when  
> possible
>
> Most of the core functions now support any iterable as an argument,  
> and
> f([x for x in ...]) is exactly similar to f(x for x in ...).
> Omitting a level of braces then gives more readable code.

Last time this came up, I think I recall that it was rejected because  
the overhead inherent in generator expressions makes them slower than  
the equivalent list comprehension unless the list is sufficiently  
large that the laziness becomes a win. Did you do any benchmarking?  
Does it make a difference?


> It is in particular true for the following calls:
> * sorted()
> * tuple(), list(), set(), dict()
> * min(), max()
> * str.join()
> * dict.*(), list.extend()
>
> Calls out of this scope were left alone. In particular:
> * list.append()
> * len()
> * return ([x for x in ...], ...)
>
> were ignored, as replacing the comprehensions in those would have  
> just been
> bogus.
>
> Candidates were selected using grep, but changes were done manually.
>
> diff --git a/contrib/memory.py b/contrib/memory.py
> --- a/contrib/memory.py
> +++ b/contrib/memory.py
> @@ -29,8 +29,8 @@
>     finally:
>         if status is not None:
>             status.close()
> -    ui.write_err(", ".join(["%s: %.1f MiB" % (key, value/1024.0)
> -                            for key, value in result.iteritems()])  
> + "\n")
> +    ui.write_err(", ".join("%s: %.1f MiB" % (key, value/1024.0)
> +                            for key, value in result.iteritems()) +  
> "\n")
>
> def extsetup(ui):
>     atexit.register(memusage, ui)
> diff --git a/contrib/simplemerge b/contrib/simplemerge
> --- a/contrib/simplemerge
> +++ b/contrib/simplemerge
> @@ -37,7 +37,7 @@
>         out_opts.append(('%2s%s' % (shortopt and '-%s' % shortopt,
>                                     longopt and ' --%s' % longopt),
>                          '%s' % desc))
> -    opts_len = max([len(opt[0]) for opt in out_opts])
> +    opts_len = max(len(opt[0]) for opt in out_opts)
>     for first, second in out_opts:
>         sys.stdout.write(' %-*s  %s\n' % (opts_len, first, second))
>
> diff --git a/doc/gendoc.py b/doc/gendoc.py
> --- a/doc/gendoc.py
> +++ b/doc/gendoc.py
> @@ -86,7 +86,7 @@
>         # options
>         opt_output = list(d['opts'])
>         if opt_output:
> -            opts_len = max([len(line[0]) for line in opt_output])
> +            opts_len = max(len(line[0]) for line in opt_output)
>             ui.write(_("    options:\n\n"))
>             for optstr, desc in opt_output:
>                 if desc:
> diff --git a/hgext/bugzilla.py b/hgext/bugzilla.py
> --- a/hgext/bugzilla.py
> +++ b/hgext/bugzilla.py
> @@ -192,7 +192,7 @@
>     def filter_real_bug_ids(self, ids):
>         '''filter not-existing bug ids from list.'''
>         self.run('select bug_id from bugs where bug_id in %s' %  
> buglist(ids))
> -        return sorted([c[0] for c in self.cursor.fetchall()])
> +        return sorted(c[0] for c in self.cursor.fetchall())
>
>     def filter_unknown_bug_ids(self, node, ids):
>         '''filter bug ids from list that already refer to this  
> changeset.'''
> diff --git a/hgext/convert/bzr.py b/hgext/convert/bzr.py
> --- a/hgext/convert/bzr.py
> +++ b/hgext/convert/bzr.py
> @@ -239,7 +239,7 @@
>         <http://bazaar-vcs.org/GhostRevision>
>         """
>         parentmap = self.sourcerepo.get_parent_map(ids)
> -        parents = tuple([parent for parent in ids if parent in  
> parentmap])
> +        parents = tuple(parent for parent in ids if parent in  
> parentmap)
>         return parents
>
>     def recode(self, s, encoding=None):
> diff --git a/hgext/convert/convcmd.py b/hgext/convert/convcmd.py
> --- a/hgext/convert/convcmd.py
> +++ b/hgext/convert/convcmd.py
> @@ -189,7 +189,7 @@
>                 return dates[n]
>
>             def picknext(nodes):
> -                return min([(getdate(n), n) for n in nodes])[1]
> +                return min((getdate(n), n) for n in nodes)[1]
>
>             return picknext
>
> diff --git a/hgext/convert/cvs.py b/hgext/convert/cvs.py
> --- a/hgext/convert/cvs.py
> +++ b/hgext/convert/cvs.py
> @@ -76,7 +76,7 @@
>
>                 files = {}
>                 for f in cs.entries:
> -                    files[f.file] = "%s%s" % ('.'.join([str(x) for  
> x in f.revision]),
> +                    files[f.file] = "%s%s" % ('.'.join(str(x) for x  
> in f.revision),
>                                               ['', '(DEAD)'][f.dead])
>
>                 # add current commit to set
> diff --git a/hgext/convert/cvsps.py b/hgext/convert/cvsps.py
> --- a/hgext/convert/cvsps.py
> +++ b/hgext/convert/cvsps.py
> @@ -163,7 +163,7 @@
>         cachefile = root.split(":") + [directory, "cache"]
>         cachefile = ['-'.join(re.findall(r'\w+', s)) for s in  
> cachefile if s]
>         cachefile = os.path.join(cachedir,
> -                                 '.'.join([s for s in cachefile if  
> s]))
> +                                 '.'.join(s for s in cachefile if s))
>
>     if cache == 'update':
>         try:
> @@ -291,7 +291,7 @@
>             match = re_50.match(line)
>             assert match, _('expected revision number')
>             e = logentry(rcs=scache(rcs), file=scache(filename),
> -                    revision=tuple([int(x) for x in  
> match.group(1).split('.')]),
> +                    revision=tuple(int(x) for x in  
> match.group(1).split('.')),
>                     branches=[], parent=None,
>                     synthetic=False)
>             state = 6
> @@ -343,7 +343,7 @@
>             # or store the commit log message otherwise
>             m = re_70.match(line)
>             if m:
> -                e.branches = [tuple([int(y) for y in  
> x.strip().split('.')])
> +                e.branches = [tuple(int(y) for y in  
> x.strip().split('.'))
>                                 for x in m.group(1).split(';')]
>                 state = 8
>             elif re_31.match(line) and re_50.match(peek):
> @@ -385,7 +385,7 @@
>         if store:
>             # clean up the results and save in the log.
>             store = False
> -            e.tags = sorted([scache(x) for x in  
> tags.get(e.revision, [])])
> +            e.tags = sorted(scache(x) for x in tags.get(e.revision,  
> []))
>             e.comment = scache('\n'.join(e.comment))
>
>             revn = len(e.revision)
> @@ -397,7 +397,7 @@
>             # find the branches starting from this revision
>             branchpoints = set()
>             for branch, revision in branchmap.iteritems():
> -                revparts = tuple([int(i) for i in  
> revision.split('.')])
> +                revparts = tuple(int(i) for i in revision.split('.'))
>                 if revparts[-2] == 0 and revparts[-1] % 2 == 0:
>                     # normal branch
>                     if revparts[:-2] == e.revision:
> @@ -794,7 +794,7 @@
>                 ui.write('Branchpoints: %s \n' % ',  
> '.join(branchpoints))
>             if opts["parents"] and cs.parents:
>                 if len(cs.parents)>1:
> -                    ui.write('Parents: %s\n' % (','.join([str(p.id)  
> for p in cs.parents])))
> +                    ui.write('Parents: %s\n' % (','.join(str(p.id)  
> for p in cs.parents)))
>                 else:
>                     ui.write('Parent: %d\n' % cs.parents[0].id)
>
> @@ -814,8 +814,8 @@
>                 fn = f.file
>                 if fn.startswith(opts["prefix"]):
>                     fn = fn[len(opts["prefix"]):]
> -                ui.write('\t%s:%s->%s%s \n' % (fn, '.'.join([str(x)  
> for x in f.parent]) or 'INITIAL',
> -                                          '.'.join([str(x) for x in  
> f.revision]), ['', '(DEAD)'][f.dead]))
> +                ui.write('\t%s:%s->%s%s \n' % (fn, '.'.join(str(x)  
> for x in f.parent) or 'INITIAL',
> +                                          '.'.join(str(x) for x in  
> f.revision), ['', '(DEAD)'][f.dead]))
>             ui.write('\n')
>
>         # have we seen the start tag?
> diff --git a/hgext/convert/hg.py b/hgext/convert/hg.py
> --- a/hgext/convert/hg.py
> +++ b/hgext/convert/hg.py
> @@ -189,7 +189,7 @@
>         except:
>             oldlines = []
>
> -        newlines = sorted([("%s %s\n" % (tags[tag], tag)) for tag  
> in tags])
> +        newlines = sorted(("%s %s\n" % (tags[tag], tag)) for tag in  
> tags)
>         if newlines == oldlines:
>             return None, None
>         data = "".join(newlines)
> @@ -330,8 +330,8 @@
>
>     def gettags(self):
>         tags = [t for t in self.repo.tagslist() if t[0] != 'tip']
> -        return dict([(name, hex(node)) for name, node in tags
> -                     if self.keep(node)])
> +        return dict((name, hex(node)) for name, node in tags
> +                     if self.keep(node))
>
>     def getchangedfiles(self, rev, i):
>         ctx = self.changectx(rev)
> diff --git a/hgext/convert/p4.py b/hgext/convert/p4.py
> --- a/hgext/convert/p4.py
> +++ b/hgext/convert/p4.py
> @@ -202,4 +202,4 @@
>         return self.tags
>
>     def getchangedfiles(self, rev, i):
> -        return sorted([x[0] for x in self.files[rev]])
> +        return sorted(x[0] for x in self.files[rev])
> diff --git a/hgext/gpg.py b/hgext/gpg.py
> --- a/hgext/gpg.py
> +++ b/hgext/gpg.py
> @@ -252,9 +252,9 @@
>     message = opts['message']
>     if not message:
>         # we don't translate commit messages
> -        message = "\n".join(["Added signature for changeset %s"
> +        message = "\n".join("Added signature for changeset %s"
>                              % hgnode.short(n)
> -                             for n in nodes])
> +                             for n in nodes)
>     try:
>         m = match.exact(repo.root, '', ['.hgsigs'])
>         repo.commit(message, opts['user'], opts['date'], match=m)
> diff --git a/hgext/hgk.py b/hgext/hgk.py
> --- a/hgext/hgk.py
> +++ b/hgext/hgk.py
> @@ -306,7 +306,7 @@
> def view(ui, repo, *etc, **opts):
>     "start interactive history viewer"
>     os.chdir(repo.root)
> -    optstr = ' '.join(['--%s %s' % (k, v) for k, v in  
> opts.iteritems() if v])
> +    optstr = ' '.join('--%s %s' % (k, v) for k, v in  
> opts.iteritems() if v)
>     cmd = ui.config("hgk", "path", "hgk") + " %s %s" % (optstr, "  
> ".join(etc))
>     ui.debug("running %s\n" % cmd)
>     util.system(cmd)
> diff --git a/hgext/inotify/server.py b/hgext/inotify/server.py
> --- a/hgext/inotify/server.py
> +++ b/hgext/inotify/server.py
> @@ -177,7 +177,7 @@
>
>         self.tree = directory()
>         self.statcache = {}
> -        self.statustrees = dict([(s, directory()) for s in  
> self.statuskeys])
> +        self.statustrees = dict((s, directory()) for s in  
> self.statuskeys)
>
>         self.ds_info = self.dirstate_info()
>
> diff --git a/hgext/mq.py b/hgext/mq.py
> --- a/hgext/mq.py
> +++ b/hgext/mq.py
> @@ -352,7 +352,7 @@
>             if bad:
>                 raise util.Abort(bad)
>         drop = self.guard_re.sub('', self.full_series[idx])
> -        self.full_series[idx] = drop + ''.join([' #' + g for g in  
> guards])
> +        self.full_series[idx] = drop + ''.join(' #' + g for g in  
> guards)
>         self.parse_series()
>         self.series_dirty = True
>
> @@ -661,7 +661,7 @@
>             del self.applied[:numrevs]
>             self.applied_dirty = 1
>
> -        for i in sorted([self.find_series(p) for p in patches],  
> reverse=True):
> +        for i in sorted((self.find_series(p) for p in patches),  
> reverse=True):
>             del self.full_series[i]
>         self.parse_series()
>         self.series_dirty = 1
> @@ -1396,7 +1396,7 @@
>                 msg = pfx + patchname
>             self.ui.write(msg + '\n')
>
> -        applied = set([p.name for p in self.applied])
> +        applied = set(p.name for p in self.applied)
>         if length is None:
>             length = len(self.series) - start
>         if not missing:
> @@ -1513,7 +1513,7 @@
>             pp = r.dirstate.parents()
>             msg += "\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
>         msg += "\n\nPatch Data:\n"
> -        text = msg + "\n".join([str(x) for x in self.applied]) +  
> '\n' + (ar and
> +        text = msg + "\n".join(str(x) for x in self.applied) + '\n'  
> + (ar and
>                    "\n".join(ar) + '\n' or "")
>         n = repo.commit(text, force=True)
>         if not n:
> @@ -2240,7 +2240,7 @@
>         ui.write('renaming %s to %s\n' % (patch, name))
>     i = q.find_series(patch)
>     guards = q.guard_re.findall(q.full_series[i])
> -    q.full_series[i] = name + ''.join([' #' + g for g in guards])
> +    q.full_series[i] = name + ''.join(' #' + g for g in guards)
>     q.parse_series()
>     q.series_dirty = 1
>
> diff --git a/hgext/record.py b/hgext/record.py
> --- a/hgext/record.py
> +++ b/hgext/record.py
> @@ -97,7 +97,7 @@
>             if h.startswith('---'):
>                 fp.write(_('%d hunks, %d lines changed\n') %
>                          (len(self.hunks),
> -                          sum([h.added + h.removed for h in  
> self.hunks])))
> +                          sum(h.added + h.removed for h in  
> self.hunks)))
>                 break
>             fp.write(h)
>
> diff --git a/mercurial/ancestor.py b/mercurial/ancestor.py
> --- a/mercurial/ancestor.py
> +++ b/mercurial/ancestor.py
> @@ -37,7 +37,7 @@
>                 if p not in depth:
>                     visit.append(p)
>             if visit[-1] == vertex:
> -                depth[vertex] = min([depth[p] for p in pl]) - 1
> +                depth[vertex] = min(depth[p] for p in pl) - 1
>                 visit.pop()
>
>     # traverse ancestors in order of decreasing distance from root
> diff --git a/mercurial/changelog.py b/mercurial/changelog.py
> --- a/mercurial/changelog.py
> +++ b/mercurial/changelog.py
> @@ -210,7 +210,7 @@
>                                     % repr(user))
>
>         # strip trailing whitespace and leading and trailing empty  
> lines
> -        desc = '\n'.join([l.rstrip() for l in  
> desc.splitlines()]).strip('\n')
> +        desc = '\n'.join(l.rstrip() for l in  
> desc.splitlines()).strip('\n')
>
>         user, desc = encoding.fromlocal(user),  
> encoding.fromlocal(desc)
>
> diff --git a/mercurial/cmdutil.py b/mercurial/cmdutil.py
> --- a/mercurial/cmdutil.py
> +++ b/mercurial/cmdutil.py
> @@ -1136,10 +1136,10 @@
>     if ctx.branch():
>         edittext.append(_("HG: branch '%s'")
>                         % encoding.tolocal(ctx.branch()))
> -    edittext.extend([_("HG: subrepo %s") % s for s in subs])
> -    edittext.extend([_("HG: added %s") % f for f in added])
> -    edittext.extend([_("HG: changed %s") % f for f in modified])
> -    edittext.extend([_("HG: removed %s") % f for f in removed])
> +    edittext.extend(_("HG: subrepo %s") % s for s in subs)
> +    edittext.extend(_("HG: added %s") % f for f in added)
> +    edittext.extend(_("HG: changed %s") % f for f in modified)
> +    edittext.extend(_("HG: removed %s") % f for f in removed)
>     if not added and not modified and not removed:
>         edittext.append(_("HG: no files changed"))
>     edittext.append("")
> diff --git a/mercurial/commands.py b/mercurial/commands.py
> --- a/mercurial/commands.py
> +++ b/mercurial/commands.py
> @@ -454,8 +454,8 @@
>         realhead = tag in activebranches
>         open = node in repo.branchheads(tag, closed=False)
>         return realhead and open
> -    branches = sorted([(testactive(tag, node),  
> repo.changelog.rev(node), tag)
> -                          for tag, node in  
> repo.branchtags().items()],
> +    branches = sorted(((testactive(tag, node),  
> repo.changelog.rev(node), tag)
> +                          for tag, node in  
> repo.branchtags().items()),
>                       reverse=True)
>
>     for isactive, node, tag in branches:
> @@ -738,7 +738,7 @@
> def debugcommands(ui, cmd='', *args):
>     for cmd, vals in sorted(table.iteritems()):
>         cmd = cmd.split('|')[0].strip('^')
> -        opts = ', '.join([i[1] for i in vals[1]])
> +        opts = ', '.join(i[1] for i in vals[1])
>         ui.write('%s: %s\n' % (cmd, opts))
>
> def debugcomplete(ui, cmd='', **opts):
> @@ -1065,8 +1065,8 @@
>     if not items:
>         return
>     fmt = 'f  %%-%ds  %%-%ds  %%s' % (
> -        max([len(abs) for abs in items]),
> -        max([len(m.rel(abs)) for abs in items]))
> +        max(len(abs) for abs in items),
> +        max(len(m.rel(abs)) for abs in items))
>     for abs in items:
>         line = fmt % (abs, m.rel(abs), m.exact(abs) and 'exact' or '')
>         ui.write("%s\n" % line.rstrip())
> @@ -1597,7 +1597,7 @@
>         except AttributeError:
>             ct = {}
>
> -        modcmds = set([c.split('|', 1)[0] for c in ct])
> +        modcmds = set(c.split('|', 1)[0] for c in ct)
>         helplist(_('list of commands:\n\n'), modcmds.__contains__)
>
>     if name and name != 'shortlist':
> @@ -1651,7 +1651,7 @@
>         topics = []
>         for names, header, doc in help.helptable:
>             topics.append((sorted(names, key=len, reverse=True)[0],  
> header))
> -        topics_len = max([len(s[0]) for s in topics])
> +        topics_len = max(len(s[0]) for s in topics)
>         for t, desc in topics:
>             ui.write(" %-*s  %s\n" % (topics_len, t, desc))
>
> @@ -1709,10 +1709,10 @@
>         if default or id or num:
>             changed = ctx.files() + ctx.deleted()
>         if default or id:
> -            output = ["%s%s" % ('+'.join([hexfunc(p.node()) for p  
> in parents]),
> +            output = ["%s%s" % ('+'.join(hexfunc(p.node()) for p in  
> parents),
>                                 (changed) and "+" or "")]
>         if num:
> -            output.append("%s%s" % ('+'.join([str(p.rev()) for p in  
> parents]),
> +            output.append("%s%s" % ('+'.join(str(p.rev()) for p in  
> parents),
>                                     (changed) and "+" or ""))
>     else:
>         ctx = repo[rev]
> @@ -2907,7 +2907,7 @@
>     tags = repo.tags()
>
>     for p in parents:
> -        t = ' '.join([t for t in tags if tags[t] == p.node()])
> +        t = ' '.join(t for t in tags if tags[t] == p.node())
>         if p.rev() == -1:
>             if not len(repo):
>                 t += _(' (empty repository)')
> diff --git a/mercurial/copies.py b/mercurial/copies.py
> --- a/mercurial/copies.py
> +++ b/mercurial/copies.py
> @@ -11,7 +11,7 @@
>
> def _nonoverlap(d1, d2, d3):
>     "Return list of elements in d1 not in d2 or d3"
> -    return sorted([d for d in d1 if d not in d3 and d not in d2])
> +    return sorted(d for d in d1 if d not in d3 and d not in d2)
>
> def _dirname(f):
>     s = f.rfind("/")
> diff --git a/mercurial/dirstate.py b/mercurial/dirstate.py
> --- a/mercurial/dirstate.py
> +++ b/mercurial/dirstate.py
> @@ -556,8 +556,8 @@
>
>         # step 3: report unseen items in the dmap hash
>         if not skipstep3 and not exact:
> -            visit = sorted([f for f in dmap if f not in results and  
> matchfn(f)])
> -            for nf, st in zip(visit, util.statfiles([join(i) for i  
> in visit])):
> +            visit = sorted(f for f in dmap if f not in results and  
> matchfn(f))
> +            for nf, st in zip(visit, util.statfiles(join(i) for i  
> in visit)):
>                 if not st is None and not getkind(st.st_mode) in  
> (regkind, lnkkind):
>                     st = None
>                 results[nf] = st
> diff --git a/mercurial/dispatch.py b/mercurial/dispatch.py
> --- a/mercurial/dispatch.py
> +++ b/mercurial/dispatch.py
> @@ -151,7 +151,7 @@
>         ui.warn(_("** Mercurial Distributed SCM (version %s)\n")
>                % util.version())
>         ui.warn(_("** Extensions loaded: %s\n")
> -               % ", ".join([x[0] for x in extensions.extensions()]))
> +               % ", ".join(x[0] for x in extensions.extensions()))
>         raise
>
>     return -1
> diff --git a/mercurial/encoding.py b/mercurial/encoding.py
> --- a/mercurial/encoding.py
> +++ b/mercurial/encoding.py
> @@ -72,6 +72,6 @@
>     d = s.decode(encoding, 'replace')
>     if hasattr(unicodedata, 'east_asian_width'):
>         w = unicodedata.east_asian_width
> -        return sum([w(c) in 'WF' and 2 or 1 for c in d])
> +        return sum(w(c) in 'WF' and 2 or 1 for c in d)
>     return len(d)
>
> diff --git a/mercurial/filemerge.py b/mercurial/filemerge.py
> --- a/mercurial/filemerge.py
> +++ b/mercurial/filemerge.py
> @@ -70,7 +70,7 @@
>         if t not in tools:
>             tools[t] = int(_toolstr(ui, t, "priority", "0"))
>     names = tools.keys()
> -    tools = sorted([(-p,t) for t,p in tools.items()])
> +    tools = sorted((-p,t) for t,p in tools.items())
>     uimerge = ui.config("ui", "merge")
>     if uimerge:
>         if uimerge not in names:
> diff --git a/mercurial/hbisect.py b/mercurial/hbisect.py
> --- a/mercurial/hbisect.py
> +++ b/mercurial/hbisect.py
> @@ -25,11 +25,11 @@
>     """
>
>     clparents = changelog.parentrevs
> -    skip = set([changelog.rev(n) for n in state['skip']])
> +    skip = set(changelog.rev(n) for n in state['skip'])
>
>     def buildancestors(bad, good):
>         # only the earliest bad revision matters
> -        badrev = min([changelog.rev(n) for n in bad])
> +        badrev = min(changelog.rev(n) for n in bad)
>         goodrevs = [changelog.rev(n) for n in good]
>         goodrev = min(goodrevs)
>         # build visit array
> diff --git a/mercurial/httprepo.py b/mercurial/httprepo.py
> --- a/mercurial/httprepo.py
> +++ b/mercurial/httprepo.py
> @@ -114,7 +114,7 @@
>         if proto.startswith('application/mercurial-'):
>             try:
>                 version = proto.split('-', 1)[1]
> -                version_info = tuple([int(n) for n in  
> version.split('.')])
> +                version_info = tuple(int(n) for n in  
> version.split('.'))
>             except ValueError:
>                 raise error.RepoError(_("'%s' sent a broken Content- 
> Type "
>                                         "header (%s)") % (safeurl,  
> proto))
> @@ -180,7 +180,7 @@
>         batch = 8 # avoid giant requests
>         r = []
>         for i in xrange(0, len(pairs), batch):
> -            n = " ".join(["-".join(map(hex, p)) for p in pairs[i:i  
> + batch]])
> +            n = " ".join("-".join(map(hex, p)) for p in pairs[i:i +  
> batch])
>             d = self.do_read("between", pairs=n)
>             try:
>                 r += [ l and map(bin, l.split(" ")) or [] for l in  
> d.splitlines() ]
> @@ -195,8 +195,8 @@
>
>     def changegroupsubset(self, bases, heads, source):
>         self.requirecap('changegroupsubset', _('look up remote  
> changes'))
> -        baselst = " ".join([hex(n) for n in bases])
> -        headlst = " ".join([hex(n) for n in heads])
> +        baselst = " ".join(hex(n) for n in bases)
> +        headlst = " ".join(hex(n) for n in heads)
>         f = self.do_cmd("changegroupsubset", bases=baselst,  
> heads=headlst)
>         return util.chunkbuffer(zgenerator(f))
>
> diff --git a/mercurial/localrepo.py b/mercurial/localrepo.py
> --- a/mercurial/localrepo.py
> +++ b/mercurial/localrepo.py
> @@ -279,8 +279,8 @@
>             if node != nullid:
>                 tags[encoding.tolocal(name)] = node
>         tags['tip'] = self.changelog.tip()
> -        tagtypes = dict([(encoding.tolocal(name), value)
> -                         for (name, value) in tagtypes.iteritems()])
> +        tagtypes = dict((encoding.tolocal(name), value)
> +                         for (name, value) in tagtypes.iteritems())
>         return (tags, tagtypes)
>
>     def tagtype(self, tagname):
> @@ -419,7 +419,7 @@
>                 latest = newnodes.pop()
>                 if latest not in bheads:
>                     continue
> -                minbhrev = self[min([self[bh].rev() for bh in  
> bheads])].node()
> +                minbhrev = self[min(self[bh].rev() for bh in  
> bheads)].node()
>                 reachable = self.changelog.reachable(latest, minbhrev)
>                 bheads = [b for b in bheads if b not in reachable]
>                 newbheads.insert(0, latest)
> @@ -1379,7 +1379,7 @@
>                 raise util.Abort(_("repository is unrelated"))
>
>         self.ui.debug("found new changesets starting at " +
> -                     " ".join([short(f) for f in fetch]) + "\n")
> +                     " ".join(short(f) for f in fetch) + "\n")
>
>         self.ui.debug("%d total queries\n" % reqcnt)
>
> @@ -1919,7 +1919,7 @@
>         self.hook('preoutgoing', throw=True, source=source)
>
>         cl = self.changelog
> -        revset = set([cl.rev(n) for n in nodes])
> +        revset = set(cl.rev(n) for n in nodes)
>         self.changegroupinfo(nodes, source)
>
>         def identity(x):
> diff --git a/mercurial/match.py b/mercurial/match.py
> --- a/mercurial/match.py
> +++ b/mercurial/match.py
> @@ -195,7 +195,7 @@
> def _buildmatch(pats, tail):
>     """build a matching function from a set of patterns"""
>     try:
> -        pat = '(?:%s)' % '|'.join([_regex(k, p, tail) for (k, p) in  
> pats])
> +        pat = '(?:%s)' % '|'.join(_regex(k, p, tail) for (k, p) in  
> pats)
>         if len(pat) > 20000:
>             raise OverflowError()
>         return re.compile(pat).match
> diff --git a/mercurial/mdiff.py b/mercurial/mdiff.py
> --- a/mercurial/mdiff.py
> +++ b/mercurial/mdiff.py
> @@ -72,7 +72,7 @@
>     if opts.git:
>         parts.append('--git')
>     if revs and not opts.git:
> -        parts.append(' '.join(["-r %s" % rev for rev in revs]))
> +        parts.append(' '.join("-r %s" % rev for rev in revs))
>     if opts.git:
>         parts.append('a/%s' % a)
>         parts.append('b/%s' % b)
> diff --git a/mercurial/patch.py b/mercurial/patch.py
> --- a/mercurial/patch.py
> +++ b/mercurial/patch.py
> @@ -1057,7 +1057,7 @@
>                 util.set_flags(dst, islink, isexec)
>     cmdutil.addremove(repo, cfiles, similarity=similarity)
>     files = patches.keys()
> -    files.extend([r for r in removes if r not in files])
> +    files.extend(r for r in removes if r not in files)
>     return sorted(files)
>
> def externalpatch(patcher, args, patchname, ui, strip, cwd, files):
> @@ -1325,7 +1325,7 @@
>     '''export changesets as hg patches.'''
>
>     total = len(revs)
> -    revwidth = max([len(str(rev)) for rev in revs])
> +    revwidth = max(len(str(rev)) for rev in revs)
>
>     def single(rev, seqno, fp):
>         ctx = repo[rev]
> diff --git a/mercurial/posix.py b/mercurial/posix.py
> --- a/mercurial/posix.py
> +++ b/mercurial/posix.py
> @@ -27,9 +27,9 @@
>     rcs = [os.path.join(path, 'hgrc')]
>     rcdir = os.path.join(path, 'hgrc.d')
>     try:
> -        rcs.extend([os.path.join(rcdir, f)
> +        rcs.extend(os.path.join(rcdir, f)
>                     for f, kind in osutil.listdir(rcdir)
> -                    if f.endswith(".rc")])
> +                    if f.endswith(".rc"))
>     except OSError:
>         pass
>     return rcs
> diff --git a/mercurial/revlog.py b/mercurial/revlog.py
> --- a/mercurial/revlog.py
> +++ b/mercurial/revlog.py
> @@ -680,7 +680,7 @@
>             roots = list(roots)
>             if not roots:
>                 return nonodes
> -            lowestrev = min([self.rev(n) for n in roots])
> +            lowestrev = min(self.rev(n) for n in roots)
>         else:
>             roots = [nullid] # Everybody's a descendent of nullid
>             lowestrev = nullrev
> @@ -707,7 +707,7 @@
>             # Start at the top and keep marking parents until we're  
> done.
>             nodestotag = set(heads)
>             # Remember where the top was so we can use it as a limit  
> later.
> -            highestrev = max([self.rev(n) for n in nodestotag])
> +            highestrev = max(self.rev(n) for n in nodestotag)
>             while nodestotag:
>                 # grab a node to tag
>                 n = nodestotag.pop()
> @@ -723,8 +723,8 @@
>                         # and we haven't already been marked as an  
> ancestor
>                         ancestors.add(n) # Mark as ancestor
>                         # Add non-nullid parents to list of nodes to  
> tag.
> -                        nodestotag.update([p for p in  
> self.parents(n) if
> -                                           p != nullid])
> +                        nodestotag.update(p for p in  
> self.parents(n) if
> +                                           p != nullid)
>                     elif n in heads: # We've seen it before, is it a  
> fake head?
>                         # So it is, real heads should not be the  
> ancestors of
>                         # any other heads.
> @@ -743,7 +743,7 @@
>                 roots = [n for n in roots if n in ancestors]
>                 # Recompute the lowest revision
>                 if roots:
> -                    lowestrev = min([self.rev(n) for n in roots])
> +                    lowestrev = min(self.rev(n) for n in roots)
>                 else:
>                     # No more roots?  Return empty list
>                     return nonodes
> @@ -832,7 +832,7 @@
>             start = nullid
>         if stop is None:
>             stop = []
> -        stoprevs = set([self.rev(n) for n in stop])
> +        stoprevs = set(self.rev(n) for n in stop)
>         startrev = self.rev(start)
>         reachable = set((startrev,))
>         heads = set((startrev,))
> diff --git a/mercurial/sshrepo.py b/mercurial/sshrepo.py
> --- a/mercurial/sshrepo.py
> +++ b/mercurial/sshrepo.py
> @@ -196,7 +196,7 @@
>             self.abort(error.ResponseError(_("unexpected  
> response:"), d))
>
>     def between(self, pairs):
> -        n = " ".join(["-".join(map(hex, p)) for p in pairs])
> +        n = " ".join("-".join(map(hex, p)) for p in pairs)
>         d = self.call("between", pairs=n)
>         try:
>             p = [ l and map(bin, l.split(" ")) or [] for l in  
> d.splitlines() ]
> diff --git a/mercurial/store.py b/mercurial/store.py
> --- a/mercurial/store.py
> +++ b/mercurial/store.py
> @@ -32,7 +32,7 @@
> def _buildencodefun():
>     e = '_'
>     win_reserved = [ord(x) for x in '\\:*?"<>|']
> -    cmap = dict([ (chr(x), chr(x)) for x in xrange(127) ])
> +    cmap = dict((chr(x), chr(x)) for x in xrange(127))
>     for x in (range(32) + range(126, 256) + win_reserved):
>         cmap[chr(x)] = "~%02x" % x
>     for x in range(ord("A"), ord("Z")+1) + [ord(e)]:
> @@ -52,19 +52,19 @@
>                     pass
>             else:
>                 raise KeyError
> -    return (lambda s: "".join([cmap[c] for c in encodedir(s)]),
> +    return (lambda s: "".join(cmap[c] for c in encodedir(s)),
>             lambda s: decodedir("".join(list(decode(s)))))
>
> encodefilename, decodefilename = _buildencodefun()
>
> def _build_lower_encodefun():
>     win_reserved = [ord(x) for x in '\\:*?"<>|']
> -    cmap = dict([ (chr(x), chr(x)) for x in xrange(127) ])
> +    cmap = dict((chr(x), chr(x)) for x in xrange(127))
>     for x in (range(32) + range(126, 256) + win_reserved):
>         cmap[chr(x)] = "~%02x" % x
>     for x in range(ord("A"), ord("Z")+1):
>         cmap[chr(x)] = chr(x).lower()
> -    return lambda s: "".join([cmap[c] for c in s])
> +    return lambda s: "".join(cmap[c] for c in s)
>
> lowerencode = _build_lower_encodefun()
>
> diff --git a/mercurial/subrepo.py b/mercurial/subrepo.py
> --- a/mercurial/subrepo.py
> +++ b/mercurial/subrepo.py
> @@ -41,8 +41,8 @@
>
> def writestate(repo, state):
>     repo.wwrite('.hgsubstate',
> -                ''.join(['%s %s\n' % (state[s][1], s)
> -                         for s in sorted(state)]), '')
> +                ''.join('%s %s\n' % (state[s][1], s)
> +                         for s in sorted(state)), '')
>
> def submerge(repo, wctx, mctx, actx):
>     if mctx == actx: # backwards?
> diff --git a/mercurial/tags.py b/mercurial/tags.py
> --- a/mercurial/tags.py
> +++ b/mercurial/tags.py
> @@ -173,7 +173,7 @@
>         if (bnode != anode and anode in bhist and
>             (bnode not in ahist or len(bhist) > len(ahist))):
>             anode = bnode
> -        ahist.extend([n for n in bhist if n not in ahist])
> +        ahist.extend(n for n in bhist if n not in ahist)
>         alltags[name] = anode, ahist
>         tagtypes[name] = tagtype
>
> diff --git a/mercurial/templatefilters.py b/mercurial/ 
> templatefilters.py
> --- a/mercurial/templatefilters.py
> +++ b/mercurial/templatefilters.py
> @@ -11,7 +11,7 @@
> def stringify(thing):
>     '''turn nested template iterator into string.'''
>     if hasattr(thing, '__iter__') and not isinstance(thing, str):
> -        return "".join([stringify(t) for t in thing if t is not  
> None])
> +        return "".join(stringify(t) for t in thing if t is not None)
>     return str(thing)
>
> agescales = [("second", 1),
> @@ -70,8 +70,8 @@
>             yield text[start:m.start(0)], m.group(1)
>             start = m.end(1)
>
> -    return "".join([space_re.sub(' ', textwrap.fill(para, width)) +  
> rest
> -                    for para, rest in findparas()])
> +    return "".join(space_re.sub(' ', textwrap.fill(para, width)) +  
> rest
> +                    for para, rest in findparas())
>
> def firstline(text):
>     '''return the first line of text'''
> @@ -86,7 +86,7 @@
>
> def obfuscate(text):
>     text = unicode(text, encoding.encoding, 'replace')
> -    return ''.join(['&#%d;' % ord(c) for c in text])
> +    return ''.join('&#%d;' % ord(c) for c in text)
>
> def domain(author):
>     '''get domain of author, or empty string if none.'''
> diff --git a/mercurial/transaction.py b/mercurial/transaction.py
> --- a/mercurial/transaction.py
> +++ b/mercurial/transaction.py
> @@ -68,7 +68,7 @@
>     @active
>     def endgroup(self):
>         q = self._queue.pop()
> -        d = ''.join(['%s\0%d\n' % (x[0], x[1]) for x in q])
> +        d = ''.join('%s\0%d\n' % (x[0], x[1]) for x in q)
>         self.entries.extend(q)
>         self.file.write(d)
>         self.file.flush()
> diff --git a/mercurial/ui.py b/mercurial/ui.py
> --- a/mercurial/ui.py
> +++ b/mercurial/ui.py
> @@ -227,7 +227,7 @@
>
>     def write(self, *args):
>         if self._buffers:
> -            self._buffers[-1].extend([str(a) for a in args])
> +            self._buffers[-1].extend(str(a) for a in args)
>         else:
>             for a in args:
>                 sys.stdout.write(str(a))
> diff --git a/mercurial/url.py b/mercurial/url.py
> --- a/mercurial/url.py
> +++ b/mercurial/url.py
> @@ -181,11 +181,11 @@
>
>             # see if we should use a proxy for this url
>             no_list = [ "localhost", "127.0.0.1" ]
> -            no_list.extend([p.lower() for
> -                            p in ui.configlist("http_proxy", "no")])
> -            no_list.extend([p.strip().lower() for
> +            no_list.extend(p.lower() for
> +                            p in ui.configlist("http_proxy", "no"))
> +            no_list.extend(p.strip().lower() for
>                             p in os.getenv("no_proxy", '').split(',')
> -                            if p.strip()])
> +                            if p.strip())
>             # "http_proxy.always" config is for running tests on  
> localhost
>             if ui.configbool("http_proxy", "always"):
>                 self.no_list = []
> @@ -540,7 +540,7 @@
>
>     handlers.extend((urllib2.HTTPBasicAuthHandler(passmgr),
>                      httpdigestauthhandler(passmgr)))
> -    handlers.extend([h(ui, passmgr) for h in handlerfuncs])
> +    handlers.extend(h(ui, passmgr) for h in handlerfuncs)
>     opener = urllib2.build_opener(*handlers)
>
>     # 1.0 here is the _protocol_ version
> diff --git a/mercurial/verify.py b/mercurial/verify.py
> --- a/mercurial/verify.py
> +++ b/mercurial/verify.py
> @@ -155,7 +155,7 @@
>     ui.status(_("crosschecking files in changesets and manifests\n"))
>
>     if havemf:
> -        for c,m in sorted([(c, m) for m in mflinkrevs for c in  
> mflinkrevs[m]]):
> +        for c,m in sorted((c, m) for m in mflinkrevs for c in  
> mflinkrevs[m]):
>             err(c, _("changeset refers to unknown manifest %s") %  
> short(m))
>         mflinkrevs = None # del is bad here due to scope issues
>
> @@ -169,7 +169,7 @@
>             if f not in filelinkrevs:
>                 try:
>                     fl = repo.file(f)
> -                    lr = min([fl.linkrev(fl.rev(n)) for n in  
> filenodes[f]])
> +                    lr = min(fl.linkrev(fl.rev(n)) for n in  
> filenodes[f])
>                 except:
>                     lr = None
>                 err(lr, _("in manifest but not in changeset"), f)
> diff --git a/mercurial/windows.py b/mercurial/windows.py
> --- a/mercurial/windows.py
> +++ b/mercurial/windows.py
> @@ -225,8 +225,8 @@
>         cache = dircache.get(dir, None)
>         if cache is None:
>             try:
> -                dmap = dict([(ncase(n), s)
> -                    for n, k, s in osutil.listdir(dir, True)])
> +                dmap = dict((ncase(n), s)
> +                    for n, k, s in osutil.listdir(dir, True))
>             except OSError, err:
>                 # handle directory not found in Python version prior  
> to 2.5
>                 # Python <= 2.4 returns native Windows code 3 in errno
> diff --git a/tests/test-convert-git b/tests/test-convert-git
> --- a/tests/test-convert-git
> +++ b/tests/test-convert-git
> @@ -137,7 +137,7 @@
> mkdir git-repo3
> cd git-repo3
> git init-db >/dev/null 2>/dev/null
> -python -c 'file("b", "wb").write("".join([chr(i) for i in  
> range(256)])*16)'
> +python -c 'file("b", "wb").write("".join(chr(i) for i in  
> range(256))*16)'
> git add b
> commit -a -m addbinary
> cd ..
> diff --git a/tests/test-convert-svn-encoding b/tests/test-convert- 
> svn-encoding
> --- a/tests/test-convert-svn-encoding
> +++ b/tests/test-convert-svn-encoding
> @@ -13,5 +13,5 @@
> cd A-hg
> hg up
> echo '% check tags are in UTF-8'
> -python -c "print '\n'.join([('%r' % l) for l in file('.hgtags',  
> 'rb').readlines()])"
> +python -c "print '\n'.join(('%r' % l) for l in file('.hgtags',  
> 'rb').readlines())"
> cd ..
> diff --git a/tests/test-extension b/tests/test-extension
> --- a/tests/test-extension
> +++ b/tests/test-extension
> @@ -141,7 +141,7 @@
>
> def debugextensions(ui):
>     "yet another debug command"
> -    ui.write("%s\n" % '\n'.join([x for x, y in  
> extensions.extensions()]))
> +    ui.write("%s\n" % '\n'.join(x for x, y in  
> extensions.extensions()))
>
> cmdtable = {"debugextensions": (debugextensions, (), "hg  
> debugextensions")}
> commands.norepo += " debugextensions"
> diff --git a/tests/test-hgweb-auth.py b/tests/test-hgweb-auth.py
> --- a/tests/test-hgweb-auth.py
> +++ b/tests/test-hgweb-auth.py
> @@ -16,7 +16,7 @@
>     return ui
>
> def dumpdict(dict):
> -    return '{' + ', '.join(['%s: %s' % (k, dict[k]) for k in  
> sorted(dict.iterkeys())]) + '}'
> +    return '{' + ', '.join('%s: %s' % (k, dict[k]) for k in  
> sorted(dict.iterkeys())) + '}'
>
> def test(auth):
>     print 'CFG:', dumpdict(auth)
> diff --git a/tests/test-non-interactive-wsgi b/tests/test-non- 
> interactive-wsgi
> --- a/tests/test-non-interactive-wsgi
> +++ b/tests/test-non-interactive-wsgi
> @@ -65,9 +65,9 @@
> print '---- ERRORS'
> print errors.getvalue()
> print '---- OS.ENVIRON wsgi variables'
> -print sorted([x for x in os.environ if x.startswith('wsgi')])
> +print sorted(x for x in os.environ if x.startswith('wsgi'))
> print '---- request.ENVIRON wsgi variables'
> -print sorted([x for x in i.repo.ui.environ if x.startswith('wsgi')])
> +print sorted(x for x in i.repo.ui.environ if x.startswith('wsgi'))
> EOF
>
> python request.py
> _______________________________________________
> Mercurial-devel mailing list
> Mercurial-devel at selenic.com
> http://selenic.com/mailman/listinfo/mercurial-devel



More information about the Mercurial-devel mailing list