changeset 1866:0194beaf511e

reduce reduce, filter and map usage
author Thomas Waldmann <tw AT waldmann-edv DOT de>
date Sat, 10 Mar 2007 19:20:19 +0100
parents 05158c12c271
children 8166b37db555
files MoinMoin/PageEditor.py MoinMoin/action/AttachFile.py MoinMoin/action/SpellCheck.py MoinMoin/action/edit.py MoinMoin/formatter/text_html.py MoinMoin/i18n/__init__.py MoinMoin/macro/MonthCalendar.py MoinMoin/macro/RecentChanges.py MoinMoin/parser/text_moin_wiki.py MoinMoin/request/STANDALONE.py MoinMoin/script/migration/wikimarkup_converter.py MoinMoin/stats/chart.py MoinMoin/stats/hitcounts.py MoinMoin/stats/pagesize.py MoinMoin/stats/useragents.py MoinMoin/util/diff_html.py MoinMoin/util/diff_text.py MoinMoin/util/pysupport.py MoinMoin/util/web.py MoinMoin/wikiutil.py setup.py
diffstat 21 files changed, 38 insertions(+), 36 deletions(-) [+]
line wrap: on
line diff
--- a/MoinMoin/PageEditor.py	Fri Mar 09 00:56:44 2007 +0100
+++ b/MoinMoin/PageEditor.py	Sat Mar 10 19:20:19 2007 +0100
@@ -746,8 +746,8 @@
             # send email to all subscribers
             results = [_('Status of sending notification mails:')]
             for lang in subscribers.keys():
-                emails = map(lambda u: u.email, subscribers[lang])
-                names = map(lambda u: u.name, subscribers[lang])
+                emails = [u.email for u in subscribers[lang]]
+                names = [u.name for u in subscribers[lang]]
                 mailok, status = self._sendNotification(comment, emails, lang, revisions, trivial)
                 recipients = ", ".join(names)
                 results.append(_('[%(lang)s] %(recipients)s: %(status)s') % {
--- a/MoinMoin/action/AttachFile.py	Fri Mar 09 00:56:44 2007 +0100
+++ b/MoinMoin/action/AttachFile.py	Sat Mar 10 19:20:19 2007 +0100
@@ -356,7 +356,7 @@
 def _get_files(request, pagename):
     attach_dir = getAttachDir(request, pagename)
     if os.path.isdir(attach_dir):
-        files = map(lambda a: a.decode(config.charset), os.listdir(attach_dir))
+        files = [fn.decode(config.charset) for fn in os.listdir(attach_dir)]
         files.sort()
         return files
     return []
--- a/MoinMoin/action/SpellCheck.py	Fri Mar 09 00:56:44 2007 +0100
+++ b/MoinMoin/action/SpellCheck.py	Sat Mar 10 19:20:19 2007 +0100
@@ -33,8 +33,8 @@
     for basedir in (request.cfg.moinmoin_dir, request.cfg.data_dir):
         localdict = os.path.join(basedir, 'dict')
         if os.path.isdir(localdict):
-            candidates.extend(map(
-                lambda f, d=localdict: os.path.join(d, f), os.listdir(localdict)))
+            candidates.extend(
+                [os.path.join(localdict, fn) for fn in os.listdir(localdict)])
 
     # validate candidate list (leave out directories!)
     wordsfiles = []
@@ -171,7 +171,7 @@
 
         # build regex recognizing the bad words
         badwords_re = r'(^|(?<!\w))(%s)(?!\w)'
-        badwords_re = badwords_re % ("|".join(map(re.escape, badwords)),)
+        badwords_re = badwords_re % ("|".join([re.escape(bw) for bw in badwords]),)
         badwords_re = re.compile(badwords_re, re.UNICODE)
 
         lsw_msg = ''
@@ -194,7 +194,7 @@
 
         checkbox = '<input type="checkbox" name="newwords" value="%(word)s">%(word)s&nbsp;&nbsp;'
         msg = msg + (
-            " ".join(map(lambda w, cb=checkbox: cb % {'word': wikiutil.escape(w), }, badwords)) +
+            " ".join([checkbox % { 'word': wikiutil.escape(w), } for w in badwords]) +
             '<p><input type="submit" name="button_newwords" value="%s"></p>' %
                 _('Add checked words to dictionary')
         )
--- a/MoinMoin/action/edit.py	Fri Mar 09 00:56:44 2007 +0100
+++ b/MoinMoin/action/edit.py	Sat Mar 10 19:20:19 2007 +0100
@@ -118,7 +118,7 @@
 
         # Add category separator if last non-empty line contains
         # non-categories.
-        lines = filter(None, savetext.splitlines())
+        lines = [line for line in savetext.splitlines() if line]
         if lines:
 
             #TODO: this code is broken, will not work for extended links
--- a/MoinMoin/formatter/text_html.py	Fri Mar 09 00:56:44 2007 +0100
+++ b/MoinMoin/formatter/text_html.py	Sat Mar 10 19:20:19 2007 +0100
@@ -1199,7 +1199,7 @@
             while len(self.request._fmt_hd_counters) < count_depth:
                 self.request._fmt_hd_counters.append(0)
             self.request._fmt_hd_counters[-1] = self.request._fmt_hd_counters[-1] + 1
-            number = '.'.join(map(str, self.request._fmt_hd_counters[self._show_section_numbers-1:]))
+            number = '.'.join([str(x) for x in self.request._fmt_hd_counters[self._show_section_numbers-1:]])
             if number: number += ". "
 
         # Add space before heading, easier to check source code
--- a/MoinMoin/i18n/__init__.py	Fri Mar 09 00:56:44 2007 +0100
+++ b/MoinMoin/i18n/__init__.py	Sat Mar 10 19:20:19 2007 +0100
@@ -317,7 +317,7 @@
     if accepted:
         # Extract the languages names from the string
         accepted = accepted.split(',')
-        accepted = map(lambda x: x.split(';')[0], accepted)
+        accepted = [lang.split(';')[0] for lang in accepted]
         # Add base language for each sub language. If the user specified
         # a sub language like "en-us", we will try to to provide it or
         # a least the base language "en" in this case.
--- a/MoinMoin/macro/MonthCalendar.py	Fri Mar 09 00:56:44 2007 +0100
+++ b/MoinMoin/macro/MonthCalendar.py	Sat Mar 10 19:20:19 2007 +0100
@@ -309,7 +309,7 @@
 
     colorstep = 85
     p = Page(request, thispage)
-    qpagenames = '*'.join(map(wikiutil.quoteWikinameURL, parmpagename))
+    qpagenames = '*'.join([wikiutil.quoteWikinameURL(pn) for pn in parmpagename])
     qtemplate = wikiutil.quoteWikinameURL(parmtemplate)
     querystr = "calparms=%%s,%d,%d,%d,%%d,%%s" % (parmyear, parmmonth, parmoffset)
     prevlink = p.url(request, querystr % (qpagenames, parmoffset2 - 1, qtemplate))
--- a/MoinMoin/macro/RecentChanges.py	Fri Mar 09 00:56:44 2007 +0100
+++ b/MoinMoin/macro/RecentChanges.py	Sat Mar 10 19:20:19 2007 +0100
@@ -116,7 +116,7 @@
                 if not name in counters:
                     counters[name] = []
                 counters[name].append(idx+1)
-            poslist = map(None, counters.values(), counters.keys())
+            poslist = [(v, k) for k, v in counters.items()]
             poslist.sort()
             ##request.write(repr(counters.items()))
             d['editors'] = []
--- a/MoinMoin/parser/text_moin_wiki.py	Fri Mar 09 00:56:44 2007 +0100
+++ b/MoinMoin/parser/text_moin_wiki.py	Sat Mar 10 19:20:19 2007 +0100
@@ -109,7 +109,7 @@
         'dl_rule': dl_rule,
         'url_rule': url_rule,
         'word_rule': word_rule,
-        'smiley': u'|'.join(map(re.escape, config.smileys))}
+        'smiley': u'|'.join([re.escape(s) for s in config.smileys])}
 
     # Don't start p before these 
     no_new_p_before = ("heading rule table tableZ tr td "
@@ -341,7 +341,7 @@
         if word.startswith(wikiutil.PARENT_PREFIX):
             if not text:
                 text = word
-            word = '/'.join(filter(None, self.formatter.page.page_name.split('/')[:-1] + [word[wikiutil.PARENT_PREFIX_LEN:]]))
+            word = '/'.join([x for x in self.formatter.page.page_name.split('/')[:-1] + [word[wikiutil.PARENT_PREFIX_LEN:]] if x])
 
         if not text:
             # if a simple, self-referencing link, emit it as plain text
--- a/MoinMoin/request/STANDALONE.py	Fri Mar 09 00:56:44 2007 +0100
+++ b/MoinMoin/request/STANDALONE.py	Sat Mar 10 19:20:19 2007 +0100
@@ -30,7 +30,7 @@
             self.http_accept_language = (sa.headers.getheader('accept-language')
                                          or self.http_accept_language)
             self.http_user_agent = sa.headers.getheader('user-agent', '')
-            co = filter(None, sa.headers.getheaders('cookie'))
+            co = [c for c in sa.headers.getheaders('cookie') if c]
             self.saved_cookie = ', '.join(co) or ''
             self.if_modified_since = sa.headers.getheader('if-modified-since')
             self.if_none_match = sa.headers.getheader('if-none-match')
--- a/MoinMoin/script/migration/wikimarkup_converter.py	Fri Mar 09 00:56:44 2007 +0100
+++ b/MoinMoin/script/migration/wikimarkup_converter.py	Sat Mar 10 19:20:19 2007 +0100
@@ -81,7 +81,7 @@
         'dl_rule': dl_rule,
         'url_rule': url_rule,
         'word_rule': word_rule,
-        'smiley': u'|'.join(map(re.escape, config.smileys))}
+        'smiley': u'|'.join([re.escape(s) for s in config.smileys])}
 
     def __init__(self, pagename, raw, request, **kw):
         self.raw = raw
@@ -365,7 +365,7 @@
         if word.startswith(wikiutil.PARENT_PREFIX):
             if not text:
                 text = word
-            word = '/'.join(filter(None, self.page_name.split('/')[:-1] + [word[wikiutil.PARENT_PREFIX_LEN:]]))
+            word = '/'.join([x for x in self.page_name.split('/')[:-1] + [word[wikiutil.PARENT_PREFIX_LEN:]] if x])
 
         if not text:
             text = word
--- a/MoinMoin/stats/chart.py	Fri Mar 09 00:56:44 2007 +0100
+++ b/MoinMoin/stats/chart.py	Sat Mar 10 19:20:19 2007 +0100
@@ -71,10 +71,12 @@
                 colors.append('black')
 
         # Default for X axis labels (numbered 1..n)
-        if not labels: labels = map(str, range(1, len(args[0])+1))
+        if not labels:
+            labels = [str(i) for i in range(1, len(args[0])+1)]
 
         # set colors for the data sets
-        if colors: self.option(set_color=map(int, map(Color, colors)))
+        if colors:
+            self.option(set_color=[int(Color(c)) for c in colors])
 
         # pass options to gdchart and render the chart
         gdchart.option(**self.options)
--- a/MoinMoin/stats/hitcounts.py	Fri Mar 09 00:56:44 2007 +0100
+++ b/MoinMoin/stats/hitcounts.py	Sat Mar 10 19:20:19 2007 +0100
@@ -204,8 +204,8 @@
     else:
         scalefactor = int(10 ** math.floor(math.log10(scalefactor)))
 
-    #scale edits up
-    edits = map(lambda x: x*scalefactor, edits)
+    # scale edits up
+    edits = [x * scalefactor for x in edits]
 
     # create image
     image = cStringIO.StringIO()
--- a/MoinMoin/stats/pagesize.py	Fri Mar 09 00:56:44 2007 +0100
+++ b/MoinMoin/stats/pagesize.py	Sat Mar 10 19:20:19 2007 +0100
@@ -83,7 +83,7 @@
     # give us a chance to develop this
     if _debug:
         return "<p>data = %s</p>" % \
-            '<br>'.join(map(wikiutil.escape, map(repr, [labels, data])))
+            '<br>'.join([wikiutil.escape(repr(x)) for x in [labels, data]])
 
     # create image
     image = cStringIO.StringIO()
--- a/MoinMoin/stats/useragents.py	Fri Mar 09 00:56:44 2007 +0100
+++ b/MoinMoin/stats/useragents.py	Sat Mar 10 19:20:19 2007 +0100
@@ -134,7 +134,7 @@
     maxdata = len(colors) - 1
     if len(data) > maxdata:
         others = [x[0] for x in data[maxdata:]]
-        data = data[:maxdata] + [(reduce(operator.add, others, 0), _('Others').encode('iso-8859-1', 'replace'))] # gdchart can't do utf-8
+        data = data[:maxdata] + [(sum(others), _('Others').encode('iso-8859-1', 'replace'))] # gdchart can't do utf-8
 
     # shift front to end if others is very small
     if data[-1][0] * 10 < data[0][0]:
@@ -146,7 +146,7 @@
     # give us a chance to develop this
     if _debug:
         return "<p>data = %s</p>" % \
-            '<br>'.join(map(wikiutil.escape, map(repr, [labels, data])))
+            '<br>'.join([wikiutil.escape(repr(x)) for x in [labels, data]])
 
     # create image
     image = cStringIO.StringIO()
--- a/MoinMoin/util/diff_html.py	Fri Mar 09 00:56:44 2007 +0100
+++ b/MoinMoin/util/diff_html.py	Sat Mar 10 19:20:19 2007 +0100
@@ -121,8 +121,8 @@
                 rightresult += escape(rightpane[thismatch[1]:thismatch[1] + thismatch[2]])
                 charlast = (thismatch[0] + thismatch[2], thismatch[1] + thismatch[2])
 
-        leftpane = '<br>\n'.join(map(indent, leftresult.splitlines()))
-        rightpane = '<br>\n'.join(map(indent, rightresult.splitlines()))
+        leftpane = '<br>\n'.join([indent(x) for x in leftresult.splitlines()])
+        rightpane = '<br>\n'.join([indent(x) for x in rightresult.splitlines()])
 
         # removed width="50%%"
         result += """
--- a/MoinMoin/util/diff_text.py	Fri Mar 09 00:56:44 2007 +0100
+++ b/MoinMoin/util/diff_text.py	Sat Mar 10 19:20:19 2007 +0100
@@ -33,10 +33,10 @@
             break
     if not changed: return []
 
-    if not "we want the unchanged lines, too":
-        if "no questionmark lines":
-            lines = filter(lambda line: line[0] != '?', lines)
-        return lines
+#    if not "we want the unchanged lines, too":
+#        if "no questionmark lines":
+#            lines = [line for line in lines if line[0] != '?']
+#        return lines
 
 
     # calculate the hunks and remove the unchanged lines between them
--- a/MoinMoin/util/pysupport.py	Fri Mar 09 00:56:44 2007 +0100
+++ b/MoinMoin/util/pysupport.py	Sat Mar 10 19:20:19 2007 +0100
@@ -42,8 +42,8 @@
         pyre = re.compile(r"^([^_].*)\.py$")
         dirlist = os.listdir(packagedir)
 
-    pyfiles = filter(None, map(pyre.match, dirlist))
-    modules = map(lambda x: x.group(1), pyfiles)
+    matches = [pyre.match(fn) for fn in dirlist]
+    modules = [match.group(1) for match in matches if match]
 
     modules.sort()
     return modules
--- a/MoinMoin/util/web.py	Fri Mar 09 00:56:44 2007 +0100
+++ b/MoinMoin/util/web.py	Sat Mar 10 19:20:19 2007 +0100
@@ -222,7 +222,7 @@
             a Netscape color name or a HTML color ("#RRGGBB").
         """
         if isinstance(color, tuple) and len(color) == 3:
-            self.r, self.g, self.b = map(int, color)
+            self.r, self.g, self.b = int(color[0]), int(color[1]), int(color[2])
         elif isinstance(color, Color):
             self.r, self.g, self.b = color.r, color.g, color.b
         elif not isinstance(color, str):
--- a/MoinMoin/wikiutil.py	Fri Mar 09 00:56:44 2007 +0100
+++ b/MoinMoin/wikiutil.py	Sat Mar 10 19:20:19 2007 +0100
@@ -707,7 +707,7 @@
     @return: only the category pages of pagelist
     """
     func = request.cfg.cache.page_category_regex.search
-    return filter(func, pagelist)
+    return [pn for pn in pagelist if func(pn)]
 
 
 def getLocalizedPage(request, pagename): # was: getSysPage
@@ -824,7 +824,7 @@
     @return: the absolute page name
     """
     if pagename.startswith(PARENT_PREFIX):
-        pagename = '/'.join(filter(None, context.split('/')[:-1] + [pagename[PARENT_PREFIX_LEN:]]))
+        pagename = '/'.join([x for x in context.split('/')[:-1] + [pagename[PARENT_PREFIX_LEN:]] if x])
     elif pagename.startswith(CHILD_PREFIX):
         pagename = context + '/' + pagename[CHILD_PREFIX_LEN:]
     return pagename
--- a/setup.py	Fri Mar 09 00:56:44 2007 +0100
+++ b/setup.py	Sat Mar 10 19:20:19 2007 +0100
@@ -193,7 +193,7 @@
     return script
 
 # build list of scripts from their implementation modules
-moin_scripts = map(scriptname, glob.glob('MoinMoin/script/[!_]*.py'))
+moin_scripts = [scriptname(fn) for fn in glob.glob('MoinMoin/script/[!_]*.py')]
 
 
 #############################################################################