Skip to content

Commit f6f7ce4

Browse files
Daniel NunesInfernio
authored andcommitted
Prepare map(), filter() and range() for py3
The builtin functions above have different returns in py3 - they become "generators" instead of lists. Took the oportunity to get rid of all map() usages and most of filter(), they're generally less readable than list comprehensions or generator expressions. Changed most range() usages to xrange(). These are easily handled by 2to3. This commit needs triple-checking since a lot of expressions were modified. Infernio: Took the opportunity to bring all copyListToClipboard usages in line.
1 parent 5e65d79 commit f6f7ce4

28 files changed

Lines changed: 184 additions & 157 deletions

Mopy/bash/ScriptParser.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -770,7 +770,7 @@ def _emit(self, word=None, type_=None):
770770
# Try to figure out if it's multiple operators bunched together
771771
rightWord = None
772772
if type_ == UNKNOWN:
773-
for idex in range(len(word),0,-1):
773+
for idex in xrange(len(word),0,-1):
774774
newType = getType(word[0:idex], self)
775775
if newType != UNKNOWN:
776776
rightWord = word[idex:]

Mopy/bash/_games_lo.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1041,7 +1041,7 @@ def _fetch_load_order(self, cached_load_order, cached_active):
10411041
if to_drop:
10421042
# If we need to drop some mods, then make a backup first
10431043
self._backup_load_order()
1044-
msg = (u'Removed ' + u' ,'.join(map(unicode, to_drop)) +
1044+
msg = (u'Removed ' + u' ,'.join(unicode(s) for s in to_drop) +
10451045
u' from %s')
10461046
if not exists or to_drop:
10471047
# In either case, write out the LO and deprint it
@@ -1110,7 +1110,7 @@ def parse_ccc_file(cls):
11101110
_ccc_path = bass.dirs['app'].join(cls._ccc_filename)
11111111
try:
11121112
with open(_ccc_path.s, 'r') as ins:
1113-
lines = map(bolt.GPath, map(str.strip, ins.readlines()))
1113+
lines = (bolt.GPath(line.strip()) for line in ins.readlines())
11141114
cls.must_be_active_if_present += tuple(lines)
11151115
except (OSError, IOError) as e:
11161116
if e.errno != errno.ENOENT:

Mopy/bash/balt.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -337,7 +337,7 @@ def setCheckListItems(checkListBox, names, values):
337337
continue
338338
checkListBox.SetString(index, name)
339339
checkListBox.Check(index, value)
340-
for index in range(checkListBox.GetCount(), len(names), -1):
340+
for index in xrange(checkListBox.GetCount(), len(names), -1):
341341
checkListBox.Delete(index - 1)
342342

343343
# Elements --------------------------------------------------------------------
@@ -518,7 +518,7 @@ def askOpen(parent,title=u'',defaultDir=u'',defaultFile=u'',wildcard=u'',style=w
518518
if dialog.ShowModal() != wx.ID_OK:
519519
result = False
520520
elif style & wx.FD_MULTIPLE:
521-
result = map(GPath,dialog.GetPaths())
521+
result = [GPath(path) for path in dialog.GetPaths()]
522522
if mustExist:
523523
for returned_path in result:
524524
if not returned_path.exists():
@@ -1137,10 +1137,10 @@ def __OnDragging(self, event):
11371137
else:
11381138
left,right,step = oldPos+1,newPos+1,-1
11391139
insert = left+step
1140-
addPages = [(self.GetPage(x),self.GetPageText(x)) for x in range(left,right)]
1140+
addPages = [(self.GetPage(x),self.GetPageText(x)) for x in xrange(left,right)]
11411141
addPages.reverse()
11421142
num = right - left
1143-
for i in range(num):
1143+
for i in xrange(num):
11441144
self.RemovePage(left)
11451145
for page,title in addPages:
11461146
self.InsertPage(insert,page,title)
@@ -1385,7 +1385,7 @@ def OnBeginDrag(self, event):
13851385

13861386
indexes = []
13871387
start = stop = -1
1388-
for index in range(self.GetItemCount()):
1388+
for index in xrange(self.GetItemCount()):
13891389
if self.GetItemState(index, wx.LIST_STATE_SELECTED):
13901390
if stop >= 0 and self.dndOnlyCont:
13911391
# Only allow moving selections if they are in a
@@ -1670,7 +1670,7 @@ def PopulateItem(self, itemDex=-1, item=None):
16701670
else: # no way we're inserting with a None item
16711671
item = self.GetItem(itemDex)
16721672
cols = self.cols
1673-
for colDex in range(len(cols)):
1673+
for colDex in xrange(len(cols)):
16741674
col = cols[colDex]
16751675
labelTxt = self.labels[col](self, item)
16761676
if insert and colDex == 0:
@@ -2718,7 +2718,7 @@ def __init__(self, parent, title, message, lists, liststyle='check',
27182718
checksCtrl.Bind(wx.EVT_KEY_UP,self.OnKeyUp)
27192719
checksCtrl.Bind(wx.EVT_CONTEXT_MENU,self.OnContext)
27202720
# check all - for range and set see wx._controls.CheckListBox
2721-
checksCtrl.SetChecked(set(range(len(strings))))
2721+
checksCtrl.SetChecked(set(xrange(len(strings))))
27222722
elif liststyle == 'list':
27232723
checksCtrl = listBox(self, choices=strings, isHScroll=True)
27242724
else:

Mopy/bash/basher/__init__.py

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -580,7 +580,7 @@ def ListTweaks(self):
580580
@staticmethod
581581
def filterOutDefaultTweaks(ini_tweaks):
582582
"""Filter out default tweaks from tweaks iterable."""
583-
return filter(lambda x: not bosh.iniInfos[x].is_default_tweak, ini_tweaks)
583+
return [x for x in ini_tweaks if not bosh.iniInfos[x].is_default_tweak]
584584

585585
def _toDelete(self, items):
586586
items = super(INIList, self)._toDelete(items)
@@ -806,7 +806,7 @@ def dndAllow(self, event):
806806
pinned = load_order.filter_pinned(self.GetSelected())
807807
if pinned:
808808
msg = _(u"You can't reorder the following mods:\n" +
809-
u', '.join(map(unicode, pinned)))
809+
u', '.join(unicode(s) for s in pinned))
810810
continue_key = 'bash.mods.dnd.pinned.continue'
811811
if msg:
812812
balt.askContinue(self, msg, continue_key)
@@ -979,8 +979,8 @@ def OnKeyUp(self,event):
979979
self._toggle_active_state(*toggle_target)
980980
# Ctrl+C: Copy file(s) to clipboard
981981
elif event.CmdDown() and code == ord('C'):
982-
balt.copyListToClipboard([self.data_store[mod].getPath().s
983-
for mod in self.GetSelected()])
982+
balt.copyListToClipboard(self.data_store[mod].abs_path.s
983+
for mod in self.GetSelected())
984984
super(ModList, self).OnKeyUp(event)
985985

986986
def OnLeftDown(self,event):
@@ -1909,9 +1909,8 @@ def OnKeyUp(self,event):
19091909
code = event.GetKeyCode()
19101910
# Ctrl+C: Copy file(s) to clipboard
19111911
if event.CmdDown() and code == ord('C'):
1912-
sel = map(lambda save: self.data_store[save].getPath().s,
1913-
self.GetSelected())
1914-
balt.copyListToClipboard(sel)
1912+
balt.copyListToClipboard(self.data_store[save].abs_path.s
1913+
for save in self.GetSelected())
19151914
super(SaveList, self).OnKeyUp(event)
19161915

19171916
def OnLeftDown(self,event):
@@ -2486,9 +2485,8 @@ def OnKeyUp(self,event):
24862485
self.addMarker()
24872486
# Ctrl+C: Copy file(s) to clipboard
24882487
elif event.CmdDown() and code == ord('C'):
2489-
sel = map(lambda x: bass.dirs['installers'].join(x).s,
2490-
self.GetSelected())
2491-
balt.copyListToClipboard(sel)
2488+
balt.copyListToClipboard(bass.dirs['installers'].join(x).s
2489+
for x in self.GetSelected())
24922490
super(InstallersList, self).OnKeyUp(event)
24932491

24942492
# Installer specific ------------------------------------------------------
@@ -2836,7 +2834,7 @@ def OnCheckSubItem(self,event):
28362834
installer.extras_dict['fomod_active'] = self.gSubList.IsChecked(0)
28372835
self.gSubList.Delete(0)
28382836
has_fomod = True
2839-
for index in range(self.gSubList.GetCount()):
2837+
for index in xrange(self.gSubList.GetCount()):
28402838
installer.subActives[index+1] = self.gSubList.IsChecked(index)
28412839
if has_fomod:
28422840
self.gSubList.Insert("fomod", 0)
@@ -3138,9 +3136,8 @@ def OnKeyUp(self,event):
31383136
code = event.GetKeyCode()
31393137
# Ctrl+C: Copy file(s) to clipboard
31403138
if event.CmdDown() and code == ord('C'):
3141-
sel = map(lambda x: bosh.screen_infos.store_dir.join(x).s,
3142-
self.GetSelected())
3143-
balt.copyListToClipboard(sel)
3139+
balt.copyListToClipboard(self.data_store[screen].abs_path.s
3140+
for screen in self.GetSelected())
31443141
super(ScreensList, self).OnKeyUp(event)
31453142

31463143
#------------------------------------------------------------------------------
@@ -3412,7 +3409,7 @@ def Execute(self):
34123409
iMods = None
34133410
iInstallers = None
34143411
iDelete = None
3415-
for i in range(Link.Frame.notebook.GetPageCount()):
3412+
for i in xrange(Link.Frame.notebook.GetPageCount()):
34163413
pageTitle = Link.Frame.notebook.GetPageText(i)
34173414
if pageTitle == tabInfo['Mods'][1]:
34183415
iMods = i
@@ -3658,7 +3655,7 @@ def UnhideButton(self,link):
36583655
self._addButton(link)
36593656
button = self.buttons.pop()
36603657
thisIndex, insertBefore = order.index(link.uid), 0
3661-
for i in range(len(self.buttons)):
3658+
for i in xrange(len(self.buttons)):
36623659
otherlink = self.GetLink(index=i)
36633660
indexOther = order.index(otherlink.uid)
36643661
if indexOther > thisIndex:

Mopy/bash/basher/frames.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -475,7 +475,7 @@ def DoSave(self):
475475
maVersion = re.match(u'' r'(\d+)\.(\d+)',
476476
self.gVersion.text_content.strip(), flags=re.U)
477477
if maVersion:
478-
config.vMajor,config.vMinor = map(int,maVersion.groups())
478+
config.vMajor,config.vMinor = (int(g) for g in maVersion.groups())
479479
else:
480480
config.vMajor,config.vMinor = (0,0)
481481
#--Done

Mopy/bash/basher/gui_patchers.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@
2424
from __future__ import division
2525
import copy
2626
import re
27-
from operator import itemgetter
2827
import wx
2928
# Internal
3029
from .. import bass, bosh, bush, balt, load_order, bolt, exception
@@ -176,7 +175,7 @@ def OnEditAliases(self):
176175
aliases_text = self.gAliases.text_content
177176
self.aliases.clear()
178177
for line in aliases_text.split(u'\n'):
179-
fields = map(unicode.strip,line.split(u'>>'))
178+
fields = [s.strip() for s in line.split(u'>>')]
180179
if len(fields) != 2 or not fields[0] or not fields[1]: continue
181180
self.aliases[GPath(fields[0])] = GPath(fields[1])
182181
self.SetAliasText()
@@ -187,7 +186,7 @@ def getConfig(self, configs):
187186
config = super(_AliasesPatcherPanel, self).getConfig(configs)
188187
#--Update old configs to use Paths instead of strings.
189188
self.aliases = dict(# map(GPath, item) gives a list (item is a tuple)
190-
map(GPath, item) for item in
189+
[GPath(i) for i in item] for item in
191190
config.get('aliases', self.__class__.default_aliases).iteritems())
192191
return config
193192

@@ -815,7 +814,7 @@ def _get_set_choice(self, item):
815814

816815
def getItemLabel(self,item):
817816
"""Returns label for item to be used in list"""
818-
choice = map(itemgetter(0),self.configChoices.get(item,tuple()))
817+
choice = [i[0] for i in self.configChoices.get(item, tuple())]
819818
item = u'%s' % item # Path or basestring - YAK
820819
if choice:
821820
return u'%s [%s]' % (item,u''.join(sorted(choice)))

Mopy/bash/basher/installer_links.py

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -507,8 +507,10 @@ class Installer_Hide(_InstallerLink, UIList_Hide):
507507
u'selected.')
508508

509509
def _enable(self):
510-
return not any(map(lambda inf: isinstance(inf, bosh.InstallerMarker),
511-
self.iselected_infos()))
510+
for info in self.iselected_infos():
511+
if isinstance(info, bosh.InstallerMarker):
512+
return False
513+
return True
512514

513515
class Installer_Rename(UIList_Rename, _InstallerLink):
514516
"""Renames files by pattern."""
@@ -518,8 +520,10 @@ class Installer_Rename(UIList_Rename, _InstallerLink):
518520
def _enable(self):
519521
##Only enable if all selected items are of the same type
520522
firstItem = next(self.iselected_infos())
521-
return all(map(lambda inf: isinstance(inf, type(firstItem)),
522-
self.iselected_infos()))
523+
for info in self.iselected_infos():
524+
if not isinstance(info, type(firstItem)):
525+
return False
526+
return True
523527

524528
class Installer_HasExtraData(CheckLink, _RefreshingLink):
525529
"""Toggle hasExtraData flag on installer."""
@@ -906,7 +910,7 @@ class Installer_Espm_SelectAll(_Installer_Details_Link):
906910

907911
def Execute(self):
908912
self._installer.espmNots = set()
909-
for i in range(len(self.window.espms)):
913+
for i in xrange(len(self.window.espms)):
910914
self.window.gEspmList.Check(i, True)
911915
self.window.refreshCurrent(self._installer)
912916

@@ -917,7 +921,7 @@ class Installer_Espm_DeselectAll(_Installer_Details_Link):
917921

918922
def Execute(self):
919923
espmNots = self._installer.espmNots = set()
920-
for i in range(len(self.window.espms)):
924+
for i in xrange(len(self.window.espms)):
921925
self.window.gEspmList.Check(i, False)
922926
espm =GPath(self.window.gEspmList.GetString(i).replace(u'&&',u'&'))
923927
espmNots.add(espm)
@@ -981,7 +985,7 @@ def Execute(self):
981985
subs = (_(u'Plugin List for %s:') % self._installer.archive +
982986
u'\n[spoiler]\n')
983987
espm_list = self.window.gEspmList
984-
for index in range(espm_list.GetCount()):
988+
for index in xrange(espm_list.GetCount()):
985989
subs += [u' ',u'** '][espm_list.IsChecked(index)] + \
986990
espm_list.GetString(index) + '\n'
987991
subs += u'[/spoiler]'
@@ -1095,8 +1099,10 @@ class InstallerArchive_Unpack(AppendableLink, _InstallerLink):
10951099
def _append(self, window):
10961100
self.selected = window.GetSelected() # append runs before _initData
10971101
self.window = window # and the idata access is via self.window
1098-
return all(map(lambda inf: isinstance(inf, bosh.InstallerArchive),
1099-
self.iselected_infos()))
1102+
for info in self.iselected_infos():
1103+
if not isinstance(info, bosh.InstallerArchive):
1104+
return False
1105+
return True
11001106

11011107
@balt.conversation
11021108
def Execute(self):

Mopy/bash/basher/installers_links.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ def Execute(self):
8686
with load_order.Unlock():
8787
mods_changed = bosh.modInfos.refresh()
8888
inis_changed = bosh.iniInfos.refresh()
89-
ui_refresh = map(bool, [mods_changed, inis_changed])
89+
ui_refresh = (bool(mods_changed), bool(inis_changed))
9090
self.iPanel.ShowPanel(canCancel=False, scan_data_dir=True)
9191
# Determine changes
9292
curData = self.idata.data_sizeCrcDate

Mopy/bash/basher/links.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -701,7 +701,7 @@ def InitScreenLinks():
701701
#--JPEG Quality
702702
if True:
703703
qualityMenu = MenuLink(_(u'JPEG Quality'))
704-
for i in range(100, 80, -5):
704+
for i in xrange(100, 80, -5):
705705
qualityMenu.links.append(Screens_JpgQuality(i))
706706
qualityMenu.links.append(Screens_JpgQualityCustom())
707707
ScreensList.mainMenu.append(SeparatorLink())

Mopy/bash/bolt.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -531,7 +531,7 @@ def csbody(self):
531531
@property
532532
def headTail(self):
533533
"""For alpha\beta.gamma returns (alpha,beta.gamma)"""
534-
return map(GPath,(self.shead,self.stail))
534+
return [GPath(self.shead), GPath(self.stail)]
535535
@property
536536
def head(self):
537537
"""For alpha\beta.gamma, returns alpha."""
@@ -623,7 +623,7 @@ def size(self):
623623
join = os.path.join
624624
getSize = os.path.getsize
625625
try:
626-
return sum([sum(map(getSize,map(lambda z: join(x,z),files))) for x,y,files in _walk(self._s)])
626+
return sum(sum(getSize(join(x, f)) for f in files) for x, _, files in _walk(self._s))
627627
except ValueError:
628628
return 0
629629
else:
@@ -1196,8 +1196,8 @@ def __len__(self): return sum(self.mask)
11961196
def __iter__(self):
11971197
for i,elem in enumerate(self.items):
11981198
if self.mask[i]: yield self.items[i]
1199-
def __str__(self): return u'{%s}' % (','.join(map(repr,self._items())))
1200-
def __repr__(self): return u'MemorySet([%s])' % (','.join(map(repr,self._items())))
1199+
def __str__(self): return u'{%s}' % (','.join(repr(i) for i in self._items()))
1200+
def __repr__(self): return u'MemorySet([%s])' % (','.join(repr(i) for i in self._items()))
12011201
def forget(self, elem):
12021202
# Permanently remove an item from the list. Don't remember its order
12031203
if elem in self.items:
@@ -2082,7 +2082,7 @@ def genHtml(ins,out=None,*cssDirs):
20822082
# Setup
20832083
outWrite = out.write
20842084

2085-
cssDirs = map(GPath,cssDirs)
2085+
cssDirs = (GPath(d) for d in cssDirs)
20862086
# Setup ---------------------------------------------------------
20872087
#--Headers
20882088
reHead = re.compile(u'(=+) *(.+)',re.U)

0 commit comments

Comments
 (0)