From 033c18fd9fce2657c30961ab6f58b74da99fd5e0 Mon Sep 17 00:00:00 2001 From: "Per A. Brodtkorb" Date: Fri, 20 Mar 2020 18:51:19 +0100 Subject: [PATCH] Fixes issue #1556 Replaced XXX.keys() calls with idiomatic python 3 calls that are compatible with python 2 such as eg: * replaced "y = xxx.keys()" or "y = list(xxx.keys())" with just "y = list(xxx)" * replaced "sorted(xxx.keys())" or "sorted(list(xxx.keys()))" with just "sorted(xxx)" * replaced "if not A in B.keys():" with "if A not in B:" * replaced "for A in B.keys():" with "for A in B:" See also https://python-future.org/compatible_idioms.html https://python-future.org/compatible_idioms.html#dict-keys-values-items-as-a-list --- buildtools/build_wxwidgets.py | 3 +- demo/Cursor.py | 3 +- demo/DVC_IndexListModel.py | 3 +- demo/DrawXXXList.py | 4 +- demo/FloatCanvas.py | 4 +- demo/GLCanvas.py | 2 +- demo/Grid.py | 3 +- demo/Main.py | 11 +-- demo/TablePrint.py | 3 +- demo/Throbber.py | 8 +-- demo/agw/AGWInfoBar.py | 3 +- demo/agw/ShortcutEditor.py | 7 +- demo/agw/UltimateListCtrl.py | 3 +- demo/agw/UltimateListIconDemo.py | 3 +- demo/agw/UltimateListListDemo.py | 3 +- etgtools/sphinx_generator.py | 2 +- samples/doodle/doodle.py | 4 +- samples/floatcanvas/BB_HitTest.py | 2 +- samples/floatcanvas/GroupDeleteDemo.py | 2 +- samples/floatcanvas/GroupDemo.py | 2 +- samples/floatcanvas/MiniDemo.py | 2 +- samples/roses/wxroses.py | 4 +- sphinxtools/postprocess.py | 29 +++----- sphinxtools/utilities.py | 2 +- unittests/test_windowid.py | 3 +- unittests/wtc.py | 2 +- wx/lib/agw/artmanager.py | 2 +- wx/lib/agw/fmcustomizedlg.py | 4 +- wx/lib/agw/shortcuteditor.py | 4 +- wx/lib/agw/supertooltip.py | 3 +- wx/lib/calendar.py | 12 ++-- wx/lib/evtmgr.py | 2 +- wx/lib/filebrowsebutton.py | 3 +- wx/lib/inspection.py | 2 +- wx/lib/masked/maskededit.py | 38 ++++++----- wx/lib/masked/numctrl.py | 8 +-- wx/lib/masked/timectrl.py | 2 +- wx/lib/nvdlg.py | 4 +- wx/lib/plot/polyobjects.py | 2 +- wx/lib/pubsub/core/topicargspec.py | 10 +-- wx/lib/pubsub/core/topicdefnprovider.py | 90 ++++++++++++------------- wx/lib/pubsub/utils/misc.py | 4 +- wx/lib/pubsub/utils/topictreeprinter.py | 2 +- wx/py/PyCrust.py | 4 +- wx/py/PyShell.py | 4 +- wx/py/PySlices.py | 4 +- wx/py/PySlicesShell.py | 4 +- wx/py/PyWrap.py | 2 +- wx/py/buffer.py | 4 +- wx/py/dispatcher.py | 12 ++-- wx/py/filling.py | 2 +- wx/py/introspect.py | 8 +-- wx/py/magic.py | 2 +- wx/tools/dbg.py | 2 +- 54 files changed, 164 insertions(+), 193 deletions(-) diff --git a/buildtools/build_wxwidgets.py b/buildtools/build_wxwidgets.py index 4539d9a6..0cc32f77 100644 --- a/buildtools/build_wxwidgets.py +++ b/buildtools/build_wxwidgets.py @@ -231,8 +231,7 @@ def main(wxDir, args): parser = optparse.OptionParser(usage="usage: %prog [options]", version="%prog 1.0") - keys = option_dict.keys() - for opt in sorted(keys): + for opt in sorted(option_dict): default = option_dict[opt][0] action = "store" if type(default) == bool: diff --git a/demo/Cursor.py b/demo/Cursor.py index 44046f4e..9e18d55c 100644 --- a/demo/Cursor.py +++ b/demo/Cursor.py @@ -216,8 +216,7 @@ class TestPanel(wx.Panel): wx.Panel.__init__(self, parent, -1) # Create a list of choices from the dictionary above. - choices = cursors.keys() - choices = sorted(choices) + choices = sorted(cursors) # Create the controls. self.cb = wx.ComboBox(self, -1, "wx.CURSOR_DEFAULT", choices=choices, diff --git a/demo/DVC_IndexListModel.py b/demo/DVC_IndexListModel.py index 74a3f4ac..db40d044 100644 --- a/demo/DVC_IndexListModel.py +++ b/demo/DVC_IndexListModel.py @@ -80,9 +80,8 @@ class TestModel(dv.DataViewIndexListModel): def DeleteRows(self, rows): # make a copy since we'll be sorting(mutating) the list - rows = list(rows) # use reverse order so the indexes don't change as we remove items - rows.sort(reverse=True) + rows = sorted(rows, reverse=True) for row in rows: # remove it from our data structure diff --git a/demo/DrawXXXList.py b/demo/DrawXXXList.py index 582a37a8..97962de2 100644 --- a/demo/DrawXXXList.py +++ b/demo/DrawXXXList.py @@ -106,7 +106,7 @@ def makeRandomPens(num, cache): c = random.choice(colours) t = random.randint(1, 4) - if not (c, t) in cache.keys(): + if (c, t) not in cache: cache[(c, t)] = wx.Pen(c, t) pens.append( cache[(c, t)] ) @@ -120,7 +120,7 @@ def makeRandomBrushes(num, cache): for i in range(num): c = random.choice(colours) - if not c in cache.keys(): + if c not in cache: cache[c] = wx.Brush(c) brushes.append( cache[c] ) diff --git a/demo/FloatCanvas.py b/demo/FloatCanvas.py index 868947fd..25be050a 100644 --- a/demo/FloatCanvas.py +++ b/demo/FloatCanvas.py @@ -1514,11 +1514,11 @@ def BuildDrawFrame(): # this gets called when needed, rather than on import Object.SetFillColor(colors[random.randint(0,len(colors)-1)]) Object.SetLineColor(colors[random.randint(0,len(colors)-1)]) Object.SetLineWidth(random.randint(1,7)) - Object.SetLineStyle(list(FloatCanvas.DrawObject.LineStyleList.keys())[random.randint(0,5)]) + Object.SetLineStyle(list(FloatCanvas.DrawObject.LineStyleList)[random.randint(0,5)]) for Object in self.ColorObjectsLine: Object.SetLineColor(colors[random.randint(0,len(colors)-1)]) Object.SetLineWidth(random.randint(1,7)) - Object.SetLineStyle(list(FloatCanvas.DrawObject.LineStyleList.keys())[random.randint(0,5)]) + Object.SetLineStyle(list(FloatCanvas.DrawObject.LineStyleList)[random.randint(0,5)]) for Object in self.ColorObjectsColor: Object.SetColor(colors[random.randint(0,len(colors)-1)]) for Object in self.ColorObjectsText: diff --git a/demo/GLCanvas.py b/demo/GLCanvas.py index 7ea4d9e1..7c158b28 100644 --- a/demo/GLCanvas.py +++ b/demo/GLCanvas.py @@ -33,7 +33,7 @@ class ButtonPanel(wx.Panel): box = wx.BoxSizer(wx.VERTICAL) box.Add((20, 30)) - keys = sorted(buttonDefs.keys()) + keys = sorted(buttonDefs) for k in keys: text = buttonDefs[k][1] btn = wx.Button(self, k, text) diff --git a/demo/Grid.py b/demo/Grid.py index cbf793ff..0eb2a48d 100644 --- a/demo/Grid.py +++ b/demo/Grid.py @@ -23,9 +23,8 @@ class ButtonPanel(wx.Panel): box = wx.BoxSizer(wx.VERTICAL) box.Add((20, 20)) - keys = sorted(buttonDefs.keys()) - for k in keys: + for k in sorted(buttonDefs): text = buttonDefs[k][1] btn = wx.Button(self, k, text) box.Add(btn, 0, wx.ALIGN_CENTER|wx.ALL, 10) diff --git a/demo/Main.py b/demo/Main.py index d57ec6c1..8742c120 100644 --- a/demo/Main.py +++ b/demo/Main.py @@ -171,8 +171,7 @@ def RemoveHTMLTags(data): def FormatDocs(keyword, values, num): - names = list(values.keys()) - names.sort() + names = sorted(values) headers = (num == 2 and [_eventHeaders] or [_styleHeaders])[0] table = (num == 2 and [_eventTable] or [_styleTable])[0] @@ -1014,10 +1013,7 @@ def HuntExternalDemos(): # Sort and reverse the external demos keys so that they # come back in alphabetical order - keys = list(externalDemos.keys()) - keys.sort() - keys.reverse() - + keys = sorted(externalDemos, reverse=True) # Loop over all external packages for extern in keys: package = externalDemos[extern] @@ -1733,8 +1729,7 @@ class wxPythonDemo(wx.Frame): item.Check(self.allowAuiFloating) self.Bind(wx.EVT_MENU, self.OnAllowAuiFloating, item) - auiPerspectives = list(self.auiConfigurations.keys()) - auiPerspectives.sort() + auiPerspectives = sorted(self.auiConfigurations) perspectivesMenu = wx.Menu() item = wx.MenuItem(perspectivesMenu, -1, DEFAULT_PERSPECTIVE, "Load startup default perspective", wx.ITEM_RADIO) self.Bind(wx.EVT_MENU, self.OnAUIPerspectives, item) diff --git a/demo/TablePrint.py b/demo/TablePrint.py index f058962b..de8b45ef 100644 --- a/demo/TablePrint.py +++ b/demo/TablePrint.py @@ -24,8 +24,7 @@ class TablePanel(wx.Panel): box = wx.BoxSizer(wx.VERTICAL) box.Add((20, 30)) - keys = list(buttonDefs.keys()) - keys.sort() + keys = sorted(buttonDefs) for k in keys: text = buttonDefs[k][1] diff --git a/demo/Throbber.py b/demo/Throbber.py index 2f936f13..d4ad41fd 100644 --- a/demo/Throbber.py +++ b/demo/Throbber.py @@ -180,7 +180,7 @@ class TestPanel(wx.Panel): sizer.SetSizeHints(self) sizer.Fit(self) - for t in self.throbbers.keys(): + for t in self.throbbers: self.throbbers[t]['throbber'].Start() self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy) @@ -190,11 +190,11 @@ class TestPanel(wx.Panel): event.Skip() def OnStartAnimation(self, event): - for t in self.throbbers.keys(): + for t in self.throbbers: self.throbbers[t]['throbber'].Start() def OnStopAnimation(self, event): - for t in self.throbbers.keys(): + for t in self.throbbers: self.throbbers[t]['throbber'].Rest() def OnNext(self, event): @@ -222,7 +222,7 @@ class TestPanel(wx.Panel): self.customThrobber.Stop() def ShutdownDemo(self): - for t in self.throbbers.keys(): + for t in self.throbbers: self.throbbers[t]['throbber'].Rest() diff --git a/demo/agw/AGWInfoBar.py b/demo/agw/AGWInfoBar.py index 25c66d0f..4434b633 100644 --- a/demo/agw/AGWInfoBar.py +++ b/demo/agw/AGWInfoBar.py @@ -24,11 +24,10 @@ from images import catalog def GetValidImages(): - keys = catalog.keys() valid_images = [] counter = 0 - for key in keys: + for key in catalog: bmp = catalog[key].GetBitmap() if bmp.GetWidth() == 16 and bmp.GetHeight() == 16: valid_images.append(bmp) diff --git a/demo/agw/ShortcutEditor.py b/demo/agw/ShortcutEditor.py index 7ac2d183..df124e3b 100644 --- a/demo/agw/ShortcutEditor.py +++ b/demo/agw/ShortcutEditor.py @@ -136,11 +136,10 @@ _window = PyEmbeddedImage( def GetValidMenuImages(): - keys = catalog.keys() valid_images = [] counter = 0 - for key in keys: + for key in catalog: bmp = catalog[key].GetBitmap() if bmp.GetWidth() == 16 and bmp.GetHeight() == 16: valid_images.append(bmp) @@ -204,7 +203,7 @@ class ShortcutEditorDemo(wx.Frame): for i in range(6): name = 'Accelerator %d'%(i+1) - choice = random.choice(list(SE.ACCELERATORS.keys())) + choice = random.choice(list(SE.ACCELERATORS)) if choice == wx.ACCEL_ALT: letter = random.choice(COMBINATIONS) @@ -216,7 +215,7 @@ class ShortcutEditorDemo(wx.Frame): wxk = ord(letter) else: - wxk = random.choice(list(SE.KEYMAP.keys())) + wxk = random.choice(list(SE.KEYMAP)) accel = (choice, wxk, ACCEL_IDS[i]) saved_accel = (name, choice, wxk, ACCEL_IDS[i]) diff --git a/demo/agw/UltimateListCtrl.py b/demo/agw/UltimateListCtrl.py index 60e963a5..2f0e16ef 100644 --- a/demo/agw/UltimateListCtrl.py +++ b/demo/agw/UltimateListCtrl.py @@ -37,8 +37,7 @@ class ButtonPanel(wx.Panel): box = wx.BoxSizer(wx.VERTICAL) box.Add((20, 20)) - keys = list(buttonDefs.keys()) - keys.sort() + keys = sorted(buttonDefs) for k in keys: text = buttonDefs[k][1] diff --git a/demo/agw/UltimateListIconDemo.py b/demo/agw/UltimateListIconDemo.py index b5c51e9f..b93125b0 100644 --- a/demo/agw/UltimateListIconDemo.py +++ b/demo/agw/UltimateListIconDemo.py @@ -850,8 +850,7 @@ class TestFrame(wx.Frame): # load some images into an image list il = wx.ImageList(64, 64, True) - imgs = list(catalog.keys()) - imgs.sort() + imgs = sorted(catalog) for img in imgs: bmp = catalog[img].GetBitmap() diff --git a/demo/agw/UltimateListListDemo.py b/demo/agw/UltimateListListDemo.py index 3bb636fd..d55f4339 100644 --- a/demo/agw/UltimateListListDemo.py +++ b/demo/agw/UltimateListListDemo.py @@ -89,8 +89,7 @@ class TestFrame(wx.Frame): # load some images into an image list il = wx.ImageList(16, 16, True) - imgs = list(catalog.keys()) - imgs.sort() + imgs = sorted(catalog) for img in imgs: bmp = catalog[img].GetBitmap() diff --git a/etgtools/sphinx_generator.py b/etgtools/sphinx_generator.py index d7bebac5..ddc11dac 100644 --- a/etgtools/sphinx_generator.py +++ b/etgtools/sphinx_generator.py @@ -382,7 +382,7 @@ class Root(Node): text = Node.Join(self, with_tail) # Health check - existing_sections = list(self.sections.keys()) + existing_sections = list(self.sections) for section_name, dummy in SECTIONS: if section_name not in self.sections: diff --git a/samples/doodle/doodle.py b/samples/doodle/doodle.py index bd71276d..54fccf15 100644 --- a/samples/doodle/doodle.py +++ b/samples/doodle/doodle.py @@ -106,9 +106,7 @@ class DoodleWindow(wx.Window): def MakeMenu(self): """Make a menu that can be popped up later""" menu = wx.Menu() - keys = list(self.menuColours.keys()) - keys.sort() - for k in keys: + for k in sorted(self.menuColours): text = self.menuColours[k] menu.Append(k, text, kind=wx.ITEM_CHECK) self.Bind(wx.EVT_MENU_RANGE, self.OnMenuSetColour, id=100, id2=200) diff --git a/samples/floatcanvas/BB_HitTest.py b/samples/floatcanvas/BB_HitTest.py index ac99bed1..46cc52b7 100644 --- a/samples/floatcanvas/BB_HitTest.py +++ b/samples/floatcanvas/BB_HitTest.py @@ -27,7 +27,7 @@ def BB_HitTest(self, event, HitEvent): object_index_list = [] #Create list for holding the indexes xy_p = event.GetPosition() xy = self.PixelToWorld( xy_p ) #Convert to the correct coords - for key2 in self.HitDict[HitEvent].keys(): + for key2 in self.HitDict[HitEvent]: #Get Mouse Event Position bb = self.HitDict[HitEvent][key2].BoundingBox if bb.PointInside(xy): diff --git a/samples/floatcanvas/GroupDeleteDemo.py b/samples/floatcanvas/GroupDeleteDemo.py index 56f4aec1..52052e7a 100644 --- a/samples/floatcanvas/GroupDeleteDemo.py +++ b/samples/floatcanvas/GroupDeleteDemo.py @@ -71,7 +71,7 @@ class DrawFrame(wx.Frame): tb = NC.ToolBar # tb.AddSeparator() - for Group in self.Groups.keys(): + for Group in self.Groups: Button = wx.Button(tb, wx.ID_ANY, "Remove %s"%Group) tb.AddControl(Button) Button.Bind(wx.EVT_BUTTON, lambda evt, group=Group: self.RemoveGroup(evt, group)) diff --git a/samples/floatcanvas/GroupDemo.py b/samples/floatcanvas/GroupDemo.py index b6ce3f6d..9d2ede73 100644 --- a/samples/floatcanvas/GroupDemo.py +++ b/samples/floatcanvas/GroupDemo.py @@ -71,7 +71,7 @@ class DrawFrame(wx.Frame): tb = NC.ToolBar # tb.AddSeparator() - for Group in self.Groups.keys(): + for Group in self.Groups: Button = wx.Button(tb, wx.ID_ANY, "Hide/Show%s"%Group) tb.AddControl(Button) print(Group) diff --git a/samples/floatcanvas/MiniDemo.py b/samples/floatcanvas/MiniDemo.py index 48b6f007..3ac553d7 100644 --- a/samples/floatcanvas/MiniDemo.py +++ b/samples/floatcanvas/MiniDemo.py @@ -77,7 +77,7 @@ class DrawFrame(wx.Frame): wx.lib.colourdb.updateColourDB() self.colors = wx.lib.colourdb.getColourList() - self.LineStyles = FloatCanvas.DrawObject.LineStyleList.keys() + self.LineStyles = list(FloatCanvas.DrawObject.LineStyleList) return None diff --git a/samples/roses/wxroses.py b/samples/roses/wxroses.py index e56c1729..f18931aa 100644 --- a/samples/roses/wxroses.py +++ b/samples/roses/wxroses.py @@ -539,6 +539,6 @@ ctrl_buttons = {} # Button widgets for command (NE) panel app = wx.App(False) MyFrame() if verbose: - print_('spin_panels', spin_panels.keys()) - print_('ctrl_buttons', ctrl_buttons.keys()) + print_('spin_panels', list(spin_panels)) + print_('ctrl_buttons', list(ctrl_buttons)) app.MainLoop() diff --git a/sphinxtools/postprocess.py b/sphinxtools/postprocess.py index ed45f565..6dc849e8 100644 --- a/sphinxtools/postprocess.py +++ b/sphinxtools/postprocess.py @@ -207,8 +207,6 @@ def buildEnumsAndMethods(sphinxDir): 'the text file "unreferenced_classes.inc" together with the ReST file names where they\n' \ 'appear.\n\n' - keys = list(unreferenced_classes.keys()) - keys.sort() fid = textfile_open(os.path.join(SPHINXROOT, 'unreferenced_classes.inc'), 'wt') fid.write('\n') @@ -216,13 +214,13 @@ def buildEnumsAndMethods(sphinxDir): fid.write('%-50s %-50s\n'%('Reference', 'File Name(s)')) fid.write('='*50 + ' ' + '='*50 + '\n') - for key in keys: + for key in sorted(unreferenced_classes): fid.write('%-50s %-50s\n'%(key, ', '.join(unreferenced_classes[key]))) fid.write('='*50 + ' ' + '='*50 + '\n') fid.close() - print((warn%(len(keys)))) + print((warn%(len(unreferenced_classes)))) # ----------------------------------------------------------------------- # @@ -372,9 +370,7 @@ def reformatFunctions(file): else: label = '.'.join(local_file.split('.')[0:2]) - names = list(functions.keys()) - names = [name.lower() for name in names] - names.sort() + names = sorted([name.lower() for name in functions]) text = templates.TEMPLATE_FUNCTION_SUMMARY % (label, label) @@ -387,8 +383,7 @@ def reformatFunctions(file): text += ' | '.join([':ref:`%s <%s %s>`'%(letter, label, letter) for letter in letters]) text += '\n\n\n' - names = list(functions.keys()) - names = sorted(names, key=str.lower) + names = sorted(functions, key=str.lower) imm = ItemModuleMap() for letter in letters: @@ -443,13 +438,10 @@ def makeModuleIndex(sphinxDir, file): enum_base = [os.path.split(os.path.splitext(enum)[0])[1] for enum in enum_files] imm = ItemModuleMap() - names = list(classes.keys()) - names.sort(key=lambda n: imm.get_fullname(n)) + names = sorted(classes, key=lambda n: imm.get_fullname(n)) # Workaround to sort names in a case-insensitive way - lower_to_name = {} - for name in names: - lower_to_name[name.lower()] = name + lower_to_name = {name.lower(): name for name in names} text = '' if module: @@ -461,8 +453,7 @@ def makeModuleIndex(sphinxDir, file): text += '%-80s **Short Description**\n' % '**Class**' text += 80*'=' + ' ' + 80*'=' + '\n' - lower_names = list(lower_to_name.keys()) - lower_names.sort() + lower_names = sorted(lower_to_name) for lower in lower_names: cls = lower_to_name[lower] @@ -488,8 +479,7 @@ def makeModuleIndex(sphinxDir, file): functionsFile = os.path.join(sphinxDir, module + '.functions.pkl') if os.path.exists(functionsFile): pf = PickleFile(functionsFile) - functions = list(pf.read().keys()) - functions.sort(key=lambda n: imm.get_fullname(n)) + functions = sorted(pf.read(), key=lambda n: imm.get_fullname(n)) pf = PickleFile(os.path.join(SPHINXROOT, 'function_summary.pkl')) function_summaries = pf.read() @@ -555,8 +545,7 @@ def genGallery(): possible = simple.lower() html_files[possible + '.png'] = simple + '.html' - keys = list(html_files.keys()) - keys.sort() + keys = sorted(html_files) text = '' diff --git a/sphinxtools/utilities.py b/sphinxtools/utilities.py index aa7674ff..6177a10a 100644 --- a/sphinxtools/utilities.py +++ b/sphinxtools/utilities.py @@ -92,7 +92,7 @@ class ODict(UserDict): def update(self, dict): UserDict.update(self, dict) - for key in list(dict.keys()): + for key in dict: if key not in self._keys: self._keys.append(key) def values(self): diff --git a/unittests/test_windowid.py b/unittests/test_windowid.py index fc36c9eb..423a6b56 100644 --- a/unittests/test_windowid.py +++ b/unittests/test_windowid.py @@ -79,8 +79,7 @@ class IdManagerTest(wtc.WidgetTestCase): def test_WindowIDRef02(self): d = {wx.NewIdRef(): 'one', wx.NewIdRef(): 'two'} - keys = sorted(d.keys()) - for k in keys: + for k in sorted(d): val = d[k] diff --git a/unittests/wtc.py b/unittests/wtc.py index c9cfa41e..2ecb3d18 100644 --- a/unittests/wtc.py +++ b/unittests/wtc.py @@ -143,7 +143,7 @@ class PubsubTestCase(unittest.TestCase): pass del self.pub - if 'wx.lib.pubsub.pub' in sys.modules.keys(): + if 'wx.lib.pubsub.pub' in sys.modules: del sys.modules['wx.lib.pubsub.pub'] #skeys = sys.modules.keys() diff --git a/wx/lib/agw/artmanager.py b/wx/lib/agw/artmanager.py index 82d4500e..f61d4652 100644 --- a/wx/lib/agw/artmanager.py +++ b/wx/lib/agw/artmanager.py @@ -2076,7 +2076,7 @@ class ArtManager(wx.EvtHandler): :return: A list of strings representing the available colour schemes. """ - return list(self._colourSchemeMap.keys()) + return list(self._colourSchemeMap) def CreateGreyBitmap(self, bmp): diff --git a/wx/lib/agw/fmcustomizedlg.py b/wx/lib/agw/fmcustomizedlg.py index 920c38a9..c4078529 100644 --- a/wx/lib/agw/fmcustomizedlg.py +++ b/wx/lib/agw/fmcustomizedlg.py @@ -82,7 +82,7 @@ class OrderedDict(UserDict): def update(self, dict): UserDict.update(self, dict) - for key in list(dict.keys()): + for key in dict: if key not in self._keys: self._keys.append(key) def values(self): @@ -271,7 +271,7 @@ class FMCustomizeDlg(wx.Dialog): # Add all hidden menus to the menu bar - for key in list(self._hiddenMenus.keys()): + for key in self._hiddenMenus: choices.append(key) if self.created: diff --git a/wx/lib/agw/shortcuteditor.py b/wx/lib/agw/shortcuteditor.py index e09331bd..88def298 100644 --- a/wx/lib/agw/shortcuteditor.py +++ b/wx/lib/agw/shortcuteditor.py @@ -1612,8 +1612,8 @@ class Shortcut(object): split = accelerator.split('+') modifiers, keyCode = split[0:-1], split[-1] - inv_Accel = dict(list(zip(list(ACCELERATORS.values()), list(ACCELERATORS.keys())))) - inv_KeyMap = dict(list(zip(list(KEYMAP.values()), list(KEYMAP.keys())))) + inv_Accel = dict(zip(ACCELERATORS.values(), ACCELERATORS.keys())) + inv_KeyMap = dict(zip(KEYMAP.values(), KEYMAP.keys())) base = wx.ACCEL_NORMAL diff --git a/wx/lib/agw/supertooltip.py b/wx/lib/agw/supertooltip.py index ae3071ec..eace5325 100644 --- a/wx/lib/agw/supertooltip.py +++ b/wx/lib/agw/supertooltip.py @@ -202,8 +202,7 @@ _colourSchemes = {"Beige": (wx.Colour(255,255,255), wx.Colour(242,242,223), wx.C def GetStyleKeys(): """ Returns the predefined styles keywords. """ - schemes = list(_colourSchemes.keys()) - schemes.sort() + schemes = sorted(_colourSchemes) return schemes diff --git a/wx/lib/calendar.py b/wx/lib/calendar.py index 66dd2e71..fe1c4c17 100644 --- a/wx/lib/calendar.py +++ b/wx/lib/calendar.py @@ -731,7 +731,7 @@ class CalDraw: :param `DC`: the :class:`wx.DC` to use """ - for key in self.cal_sel.keys(): + for key in self.cal_sel: sel_color = self.cal_sel[key][1] brush = wx.Brush(MakeColor(sel_color), wx.BRUSHSTYLE_SOLID) DC.SetBrush(brush) @@ -1004,7 +1004,7 @@ class Calendar(wx.Control): self.GetParent().GetEventHandler().ProcessEvent(ne) event.Skip() return - + self.shiftkey = event.ShiftDown() self.ctrlkey = event.ControlDown() self.click = 'KEY' @@ -1086,14 +1086,14 @@ class Calendar(wx.Control): def SetDate(self, day, month, year): """ - Set a calendar date. + Set a calendar date. :param int `day`: the day :param int `month`: the month :param int `year`: the year :raises: `ValueError` when setting an invalid month/year :returns: the new date set. - + """ datetime.date(year, month, 1) # let the possible ValueError propagate try: @@ -1221,7 +1221,7 @@ class Calendar(wx.Control): :param `my`: the y positon """ - for key in self.rg.keys(): + for key in self.rg: val = self.rg[key] ms_rect = wx.Rect(mx, my, 1, 1) if wx.IntersectRect(ms_rect, val) is not None: @@ -1509,7 +1509,7 @@ class CalenDlg(wx.Dialog): monthlist = GetMonthList() # select the month - self.m_date = wx.ComboBox(self, pos=(20, 20), size=(90, -1), + self.m_date = wx.ComboBox(self, pos=(20, 20), size=(90, -1), style=wx.CB_DROPDOWN|wx.TE_READONLY) for n, month_name in enumerate(monthlist): self.m_date.Append(month_name, n+1) diff --git a/wx/lib/evtmgr.py b/wx/lib/evtmgr.py index 84446a53..222f303f 100644 --- a/wx/lib/evtmgr.py +++ b/wx/lib/evtmgr.py @@ -261,7 +261,7 @@ class EventManager: def __getTopics(self, win=None): if win is None: - return self.messageAdapterDict.keys() + return list(self.messageAdapterDict) if win is not None: try: diff --git a/wx/lib/filebrowsebutton.py b/wx/lib/filebrowsebutton.py index c4de5b8f..7d3c60bc 100644 --- a/wx/lib/filebrowsebutton.py +++ b/wx/lib/filebrowsebutton.py @@ -425,8 +425,7 @@ if __name__ == "__main__": self.history={"c:\\temp":1, "c:\\tmp":1, "r:\\temp":1,"z:\\temp":1} def historyCallBack(self): - keys=self.history.keys() - keys.sort() + keys=sorted(self.history) return keys def OnFileNameChangedHistory (self, event): diff --git a/wx/lib/inspection.py b/wx/lib/inspection.py index 752da60e..d435c946 100644 --- a/wx/lib/inspection.py +++ b/wx/lib/inspection.py @@ -762,7 +762,7 @@ class FlagsFormatter(object): def __str__(self): st = [] - for k in self.d.keys(): + for k in self.d: if self.val & k: st.append(self.d[k]) if st: diff --git a/wx/lib/masked/maskededit.py b/wx/lib/masked/maskededit.py index 80305362..648403bb 100644 --- a/wx/lib/masked/maskededit.py +++ b/wx/lib/masked/maskededit.py @@ -1337,8 +1337,8 @@ class Field: """ #### dbg('Field::Field', indent=1) # Validate legitimate set of parameters: - for key in kwargs.keys(): - if key not in Field.valid_params.keys(): + for key in kwargs: + if key not in Field.valid_params: #### dbg(indent=0) ae = AttributeError('invalid parameter "%s"' % (key)) ae.attribute = key @@ -1366,8 +1366,8 @@ class Field: ## dbg(suspend=1) ## dbg('maskededit.Field::_SetParameters', indent=1) # Validate keyword arguments: - for key in kwargs.keys(): - if key not in Field.valid_params.keys(): + for key in kwargs: + if key not in Field.valid_params: ## dbg(indent=0, suspend=0) ae = AttributeError('invalid keyword argument "%s"' % key) ae.attribute = key @@ -1384,7 +1384,7 @@ class Field: old_fillChar = self._fillChar # store so we can change choice lists accordingly if it changes # First, Assign all parameters specified: - for key in Field.valid_params.keys(): + for key in Field.valid_params: if key in kwargs: setattr(self, '_' + key, kwargs[key] ) @@ -1747,8 +1747,9 @@ class MaskedEditMixin: self._previous_mask = None # Validate legitimate set of parameters: - for key in kwargs.keys(): - if key.replace('Color', 'Colour') not in list(MaskedEditMixin.valid_ctrl_params.keys()) + list(Field.valid_params.keys()): + valid_parameters = list(MaskedEditMixin.valid_ctrl_params) + list(Field.valid_params) + for key in kwargs: + if key.replace('Color', 'Colour') not in valid_parameters: raise TypeError('%s: invalid parameter "%s"' % (name, key)) ## Set up dictionary that can be used by subclasses to override or add to default @@ -1857,14 +1858,15 @@ class MaskedEditMixin: # Validate keyword arguments: constraint_kwargs = {} ctrl_kwargs = {} + valid_parameters = list(MaskedEditMixin.valid_ctrl_params) + list(Field.valid_params) for key, value in kwargs.items(): key = key.replace('Color', 'Colour') # for b-c, and standard wxPython spelling - if key not in list(MaskedEditMixin.valid_ctrl_params.keys()) + list(Field.valid_params.keys()): + if key not in valid_parameters: ## dbg(indent=0, suspend=0) ae = AttributeError('Invalid keyword argument "%s" for control "%s"' % (key, self.name)) ae.attribute = key raise ae - elif key in Field.valid_params.keys(): + elif key in Field.valid_params: constraint_kwargs[key] = value else: ctrl_kwargs[key] = value @@ -1878,10 +1880,10 @@ class MaskedEditMixin: autoformat = None # handle "parochial name" backward compatibility: - if autoformat and autoformat.find('MILTIME') != -1 and autoformat not in masktags.keys(): + if autoformat and autoformat.find('MILTIME') != -1 and autoformat not in masktags: autoformat = autoformat.replace('MILTIME', '24HRTIME') - if autoformat != self._autoformat and autoformat in masktags.keys(): + if autoformat != self._autoformat and autoformat in masktags: ## dbg('autoformat:', autoformat) self._autoformat = autoformat mask = masktags[self._autoformat]['mask'] @@ -1890,7 +1892,7 @@ class MaskedEditMixin: if param == 'mask': continue # (must be present; already accounted for) constraint_kwargs[param] = value - elif autoformat and not autoformat in masktags.keys(): + elif autoformat and not autoformat in masktags: ae = AttributeError('invalid value for autoformat parameter: %s' % repr(autoformat)) ae.attribute = autoformat raise ae @@ -1942,7 +1944,7 @@ class MaskedEditMixin: #### dbg(indent=0) # determine if changing parameters that should affect the entire control: - for key in MaskedEditMixin.valid_ctrl_params.keys(): + for key in MaskedEditMixin.valid_ctrl_params: if key in ( 'mask', 'fields' ): continue # (processed separately) if key in ctrl_kwargs: setattr(self, '_' + key, ctrl_kwargs[key]) @@ -2431,8 +2433,8 @@ class MaskedEditMixin: field_index += 1 #### dbg('next field:', field_index) - indices = list(self._fields.keys()) - indices.sort() + indices = sorted(self._fields) + self._field_indices = indices[1:] #### dbg('lookupField map:', indent=1) ## for i in range(len(self._mask)): @@ -2440,7 +2442,7 @@ class MaskedEditMixin: #### dbg(indent=0) # Verify that all field indices specified are valid for mask: - for index in self._fields.keys(): + for index in self._fields: if index not in [-1] + list(self._lookupField.values()): ie = IndexError('field %d is not a valid field for mask "%s"' % (index, self._mask)) ie.index = index @@ -6387,7 +6389,7 @@ class MaskedEditAccessorsMixin: """ # Define the default set of attributes exposed by the most generic masked controls: - exposed_basectrl_params = list(MaskedEditMixin.valid_ctrl_params.keys()) + list(Field.valid_params.keys()) + exposed_basectrl_params = list(MaskedEditMixin.valid_ctrl_params) + list(Field.valid_params) exposed_basectrl_params.remove('index') exposed_basectrl_params.remove('extent') exposed_basectrl_params.remove('foregroundColour') # (base class already has this) @@ -6754,7 +6756,7 @@ To see a great example of validations in action, try entering a bad email addres self.Close() def onClickPrint(self, event): - for format in masktags.keys(): + for format in masktags: sep = "+------------------------+" print("%s\n%s \n Mask: %s \n RE Validation string: %s\n" % (sep,format, masktags[format]['mask'], masktags[format]['validRegex'])) diff --git a/wx/lib/masked/numctrl.py b/wx/lib/masked/numctrl.py index 658639e3..32d7e1d1 100644 --- a/wx/lib/masked/numctrl.py +++ b/wx/lib/masked/numctrl.py @@ -549,7 +549,7 @@ class NumCtrl(BaseMaskedTextCtrl, NumCtrlAccessorsMixin): ## dbg('kwargs:', kwargs) for key, param_value in kwargs.items(): key = key.replace('Color', 'Colour') - if key not in NumCtrl.valid_ctrl_params.keys(): + if key not in NumCtrl.valid_ctrl_params: raise AttributeError('invalid keyword argument "%s"' % key) else: init_args[key] = param_value @@ -739,9 +739,9 @@ class NumCtrl(BaseMaskedTextCtrl, NumCtrlAccessorsMixin): # for all other parameters, assign keyword args as appropriate: for key, param_value in kwargs.items(): key = key.replace('Color', 'Colour') - if key not in NumCtrl.valid_ctrl_params.keys(): + if key not in NumCtrl.valid_ctrl_params: raise AttributeError('invalid keyword argument "%s"' % key) - elif key not in MaskedEditMixin.valid_ctrl_params.keys(): + elif key not in MaskedEditMixin.valid_ctrl_params: setattr(self, '_' + key, param_value) elif key in ('mask', 'autoformat'): # disallow explicit setting of mask raise AttributeError('invalid keyword argument "%s"' % key) @@ -809,7 +809,7 @@ class NumCtrl(BaseMaskedTextCtrl, NumCtrlAccessorsMixin): maskededit_kwargs['stopFieldChangeIfInvalid'] = False ## dbg('maskededit_kwargs:', maskededit_kwargs) - if maskededit_kwargs.keys(): + if maskededit_kwargs: self.SetCtrlParameters(**maskededit_kwargs) # Go ensure all the format codes necessary are present: diff --git a/wx/lib/masked/timectrl.py b/wx/lib/masked/timectrl.py index 0ee316c4..3feb50b3 100644 --- a/wx/lib/masked/timectrl.py +++ b/wx/lib/masked/timectrl.py @@ -526,7 +526,7 @@ class TimeCtrl(BaseMaskedTextCtrl): # assign keyword args as appropriate: for key, param_value in kwargs.items(): - if key not in TimeCtrl.valid_ctrl_params.keys(): + if key not in TimeCtrl.valid_ctrl_params: raise AttributeError('invalid keyword argument "%s"' % key) if key == 'format': diff --git a/wx/lib/nvdlg.py b/wx/lib/nvdlg.py index 5583aa93..5e174378 100644 --- a/wx/lib/nvdlg.py +++ b/wx/lib/nvdlg.py @@ -94,11 +94,11 @@ class SimpleNameValueDialog(wx.Dialog): self.clearValues() if values: for name, value in values.items(): - if name in self._fields.keys(): + if name in self._fields: setattr(self, name, value) def clearValues(self): - for name in self._fields.keys(): + for name in self._fields: setattr(self, name, "") diff --git a/wx/lib/plot/polyobjects.py b/wx/lib/plot/polyobjects.py index 6a248f84..26a54f8f 100644 --- a/wx/lib/plot/polyobjects.py +++ b/wx/lib/plot/polyobjects.py @@ -61,7 +61,7 @@ class PolyPoints(object): self.attributes = {} self.attributes.update(self._attributes) for name, value in attr.items(): - if name not in self._attributes.keys(): + if name not in self._attributes: err_txt = "Style attribute incorrect. Should be one of {}" raise KeyError(err_txt.format(self._attributes.keys())) self.attributes[name] = value diff --git a/wx/lib/pubsub/core/topicargspec.py b/wx/lib/pubsub/core/topicargspec.py index 202c973d..63fb238c 100644 --- a/wx/lib/pubsub/core/topicargspec.py +++ b/wx/lib/pubsub/core/topicargspec.py @@ -10,8 +10,8 @@ Definitions related to message data specification. from .listener import getArgs as getListenerArgs from .validatedefnargs import MessageDataSpecError from .topicargspecimpl import ( - SenderMissingReqdMsgDataError, - SenderUnknownMsgDataError, + SenderMissingReqdMsgDataError, + SenderUnknownMsgDataError, ArgsInfo ) @@ -53,9 +53,9 @@ class ArgSpecGiven: self.argsDocs = argsDocs # check that all args marked as required are in argsDocs - missingArgs = set(self.reqdArgs).difference(self.argsDocs.keys()) # py3: iter keys ok + missingArgs = set(self.reqdArgs).difference(self.argsDocs) if missingArgs: - msg = 'Params [%s] missing inherited required args [%%s]' % ','.join(argsDocs.keys()) # iter keys ok + msg = 'Params [%s] missing inherited required args [%%s]' % ','.join(argsDocs) raise MessageDataSpecError(msg, missingArgs) def setAll(self, allArgsDocs, reqdArgs = None): @@ -68,7 +68,7 @@ class ArgSpecGiven: return self.argsSpecType == ArgSpecGiven.SPEC_GIVEN_ALL def getOptional(self): - return tuple( set( self.argsDocs.keys() ).difference( self.reqdArgs ) ) + return tuple( set( self.argsDocs ).difference( self.reqdArgs ) ) def __str__(self): return "%s, %s, %s" % \ diff --git a/wx/lib/pubsub/core/topicdefnprovider.py b/wx/lib/pubsub/core/topicdefnprovider.py index 8bce8ff0..a4ae504d 100644 --- a/wx/lib/pubsub/core/topicdefnprovider.py +++ b/wx/lib/pubsub/core/topicdefnprovider.py @@ -8,11 +8,11 @@ import os, re, inspect from textwrap import TextWrapper, dedent from .. import ( - policies, + policies, py2and3 ) from .topicargspec import ( - topicArgsFromCallable, + topicArgsFromCallable, ArgSpecGiven ) from .topictreetraverser import TopicTreeTraverser @@ -22,13 +22,13 @@ from .topicexc import UnrecognizedSourceFormatError class ITopicDefnProvider: """ All topic definition providers added via pub.addTopicDefnProvider() - must have this interface. Derived classes must override the getDefn(), - getTreeDoc() and topicNames() methods. + must have this interface. Derived classes must override the getDefn(), + getTreeDoc() and topicNames() methods. """ - + def getDefn(self, topicNameTuple): """Must return a pair (string, ArgSpecGiven) for given topic. - The first item is a description for topic, the second item + The first item is a description for topic, the second item contains the message data specification (MDS). Note topic name is in tuple format ('a', 'b', 'c') rather than 'a.b.c'. """ msg = 'Must return (string, ArgSpecGiven), or (None, None)' @@ -58,9 +58,9 @@ SPEC_METHOD_NAME = 'msgDataSpec' class ITopicDefnDeserializer: """ - Interface class for all topic definition de-serializers that can be - accepted by TopicDefnProvider. A deserializer - creates a topic tree from something such as file, module, or string. + Interface class for all topic definition de-serializers that can be + accepted by TopicDefnProvider. A deserializer + creates a topic tree from something such as file, module, or string. """ class TopicDefn: @@ -82,13 +82,13 @@ class ITopicDefnDeserializer: def getNextTopic(self): """Get the next topic definition available from the data. The return - must be an instance of TopicDefn. Must return None when no topics + must be an instance of TopicDefn. Must return None when no topics are left.""" raise NotImplementedError def doneIter(self): """Called automatically by TopicDefnProvider once - it considers the iteration completed. Override this only if + it considers the iteration completed. Override this only if deserializer needs to take action, such as closing a file.""" pass @@ -101,10 +101,10 @@ class ITopicDefnDeserializer: class TopicDefnDeserialClass(ITopicDefnDeserializer): """ - Convert a nested class tree as a topic definition tree. Format: the class - name is the topic name, its doc string is its description. The topic's - message data specification is determined by inspecting a class method called - the same as SPEC_METHOD_NAME. The doc string of that method is parsed to + Convert a nested class tree as a topic definition tree. Format: the class + name is the topic name, its doc string is its description. The topic's + message data specification is determined by inspecting a class method called + the same as SPEC_METHOD_NAME. The doc string of that method is parsed to extract the description for each message data. """ @@ -157,7 +157,7 @@ class TopicDefnDeserialClass(ITopicDefnDeserializer): def __addDefnFromClassObj(self, pyClassObj): """Extract a topic definition from a Python class: topic name, - docstring, and MDS, and docstring for each message data. + docstring, and MDS, and docstring for each message data. The class name is the topic name, assumed to be a root topic, and descends recursively into nested classes to define subtopic etc. """ if self.__iterStarted: @@ -197,7 +197,7 @@ class TopicDefnDeserialClass(ITopicDefnDeserializer): memberNames = dir(pyClassObj) topicClasses = [] for memberName in memberNames: - if memberName.startswith('_'): + if memberName.startswith('_'): continue # ignore special and non-public methods member = getattr(pyClassObj, memberName) if inspect.isclass( member ): @@ -246,7 +246,7 @@ class TopicDefnDeserialModule(ITopicDefnDeserializer): def getTreeDoc(self): return self.__classDeserial.getTreeDoc() - + def getNextTopic(self): return self.__classDeserial.getNextTopic() @@ -268,8 +268,8 @@ class TopicDefnDeserialString(ITopicDefnDeserializer): def __init__(self, source): """This just saves the string into a temporary file created in - os.getcwd(), and the rest is delegated to TopicDefnDeserialModule. - The temporary file (module -- as well as its byte-compiled + os.getcwd(), and the rest is delegated to TopicDefnDeserialModule. + The temporary file (module -- as well as its byte-compiled version) will be deleted when the doneIter() method is called.""" def createTmpModule(): @@ -317,14 +317,14 @@ TOPIC_TREE_FROM_CLASS = 'class' class TopicDefnProvider(ITopicDefnProvider): """ Default implementation of the ITopicDefnProvider API. This - implementation accepts several formats for the topic tree + implementation accepts several formats for the topic tree source data and delegates to a registered ITopicDefnDeserializer - that converts source data into topic definitions. - - This provider is instantiated automatically by + that converts source data into topic definitions. + + This provider is instantiated automatically by ``pub.addTopicDefnProvider(source, format)`` when source is *not* an ITopicDefnProvider. - + Additional de-serializers can be registered via registerTypeForImport(). """ @@ -332,7 +332,7 @@ class TopicDefnProvider(ITopicDefnProvider): def __init__(self, source, format, **providerKwargs): """Find the correct de-serializer class from registry for the given - format; instantiate it with given source and providerKwargs; get + format; instantiate it with given source and providerKwargs; get all available topic definitions.""" if format not in self._typeRegistry: raise UnrecognizedSourceFormatError() @@ -366,16 +366,16 @@ class TopicDefnProvider(ITopicDefnProvider): @classmethod def registerTypeForImport(cls, typeName, providerClassObj): """If a new type of importer is defined for topic definitions, it - can be registered with pubsub by providing a name for the new - importer (typeName), and the class to instantiate when - pub.addTopicDefnProvider(obj, typeName) is called. For instance, :: - + can be registered with pubsub by providing a name for the new + importer (typeName), and the class to instantiate when + pub.addTopicDefnProvider(obj, typeName) is called. For instance, :: + from pubsub.core.topicdefnprovider import ITopicDefnDeserializer - class SomeNewImporter(ITopicDefnDeserializer): + class SomeNewImporter(ITopicDefnDeserializer): ... TopicDefnProvider.registerTypeForImport('some name', SomeNewImporter) # will instantiate SomeNewImporter(source) - pub.addTopicDefnProvider(source, 'some name') + pub.addTopicDefnProvider(source, 'some name') """ assert issubclass(providerClassObj, ITopicDefnDeserializer) cls._typeRegistry[typeName] = providerClassObj @@ -412,16 +412,16 @@ defaultTopicTreeSpecFooter = \ def exportTopicTreeSpec(moduleName = None, rootTopic=None, bak='bak', moduleDoc=None): """Using TopicTreeSpecPrinter, exports the topic tree rooted at rootTopic to a - Python module (.py) file. This module will define module-level classes - representing root topics, nested classes for subtopics etc. Returns a string + Python module (.py) file. This module will define module-level classes + representing root topics, nested classes for subtopics etc. Returns a string representing the contents of the file. Parameters: - If moduleName is given, the topic tree is written to moduleName.py in - os.getcwd(). By default, it is first backed up, it it already exists, - using bak as the filename extension. If bak is None, existing module file - gets overwritten. - - If rootTopic is specified, the export only traverses tree from - corresponding topic. Otherwise, complete tree, using + os.getcwd(). By default, it is first backed up, it it already exists, + using bak as the filename extension. If bak is None, existing module file + gets overwritten. + - If rootTopic is specified, the export only traverses tree from + corresponding topic. Otherwise, complete tree, using pub.getDefaultTopicTreeRoot() as starting point. - The moduleDoc is the doc string for the module ie topic tree. """ @@ -456,15 +456,15 @@ class TopicTreeSpecPrinter: Helper class to print the topic tree using the Python class syntax. The "printout" can be sent to any file object (object that has a write() method). If printed to a module, the module can be imported and - given to pub.addTopicDefnProvider(module, 'module'). Importing the module - also provides code completion of topic names (rootTopic.subTopic can be + given to pub.addTopicDefnProvider(module, 'module'). Importing the module + also provides code completion of topic names (rootTopic.subTopic can be given to any pubsub function requiring a topic name). """ INDENT_CH = ' ' #INDENT_CH = '.' - def __init__(self, rootTopic=None, fileObj=None, width=70, indentStep=4, + def __init__(self, rootTopic=None, fileObj=None, width=70, indentStep=4, treeDoc = defaultTopicTreeSpecHeader, footer = defaultTopicTreeSpecFooter): """For formatting, can specify the width of output, the indent step, the header and footer to print to override defaults. The destination is fileObj; @@ -504,7 +504,7 @@ class TopicTreeSpecPrinter: ] self.__comment.extend(fmtArgs) self.__comment.extend(['']) # two empty line after comment - + if rootTopic is not None: self.writeAll(rootTopic) @@ -612,9 +612,9 @@ class TopicTreeSpecPrinter: # but ignore the arg keys that are in parent args docs: parentMsgKeys = () if topicObj.getParent() is not None: - parentMsgKeys = topicObj.getParent().getArgDescriptions().keys() # keys iter ok + parentMsgKeys = set(topicObj.getParent().getArgDescriptions()) argsDocs = topicObj.getArgDescriptions() - for key in sorted(py2and3.iterkeys(argsDocs)): + for key in sorted(argsDocs): if key not in parentMsgKeys: argDesc = argsDocs[key] msg = "- %s: %s" % (key, argDesc) diff --git a/wx/lib/pubsub/utils/misc.py b/wx/lib/pubsub/utils/misc.py index 51299eaa..7d772746 100644 --- a/wx/lib/pubsub/utils/misc.py +++ b/wx/lib/pubsub/utils/misc.py @@ -14,8 +14,8 @@ __all__ = ('printImported', 'StructMsg', 'Callback', 'Enum' ) def printImported(): """Output a list of pubsub modules imported so far""" - ll = [mod for mod in sys.modules.keys() if mod.find('pubsub') >= 0] # iter keys ok - ll.sort() + ll = sorted([mod for mod in sys.modules if mod.find('pubsub') >= 0]) + py2and3.print_('\n'.join(ll)) diff --git a/wx/lib/pubsub/utils/topictreeprinter.py b/wx/lib/pubsub/utils/topictreeprinter.py index 4bd52770..fe3b1450 100644 --- a/wx/lib/pubsub/utils/topictreeprinter.py +++ b/wx/lib/pubsub/utils/topictreeprinter.py @@ -56,7 +56,7 @@ class TopicTreePrinter(ITopicTreeVisitor): A = self.__printTopicArgsAll, a = self.__printTopicArgNames, L = self.__printTopicListeners) - assert self.allowedExtras == set(self.__contentMeth.keys()) + assert self.allowedExtras == set(self.__contentMeth) import sys self.__destination = fileObj or sys.stdout self.__output = [] diff --git a/wx/py/PyCrust.py b/wx/py/PyCrust.py index cd8ae25d..c3e045f4 100644 --- a/wx/py/PyCrust.py +++ b/wx/py/PyCrust.py @@ -6,7 +6,7 @@ # main namespace to look as much as possible like the regular Python # shell environment. import __main__ -original = list(__main__.__dict__.keys()) +original = list(__main__.__dict__) __author__ = "Patrick K. O'Brien " @@ -51,7 +51,7 @@ def main(): md = __main__.__dict__ keepers = original keepers.append('App') - for key in list(md.keys()): + for key in list(md): if key not in keepers: del md[key] # Create an application instance. diff --git a/wx/py/PyShell.py b/wx/py/PyShell.py index c42152a9..31c5a3b2 100644 --- a/wx/py/PyShell.py +++ b/wx/py/PyShell.py @@ -6,7 +6,7 @@ # main namespace to look as much as possible like the regular Python # shell environment. import __main__ -original = list(__main__.__dict__.keys()) +original = list(__main__.__dict__) __author__ = "Patrick K. O'Brien " @@ -51,7 +51,7 @@ def main(): md = __main__.__dict__ keepers = original keepers.append('App') - for key in list(md.keys()): + for key in list(md): if key not in keepers: del md[key] # Create an application instance. diff --git a/wx/py/PySlices.py b/wx/py/PySlices.py index b4de479e..1b5e4727 100644 --- a/wx/py/PySlices.py +++ b/wx/py/PySlices.py @@ -6,7 +6,7 @@ # main namespace to look as much as possible like the regular Python # shell environment. import __main__ -original = list(__main__.__dict__.keys()) +original = list(__main__.__dict__) __author__ = "Patrick K. O'Brien / " __author__ += "David N. Mashburn " @@ -69,7 +69,7 @@ def main(filename=None): keepers = original keepers.append('App') keepers.append('filename') - for key in list(md.keys()): + for key in list(md): if key not in keepers: del md[key] # Create an application instance. diff --git a/wx/py/PySlicesShell.py b/wx/py/PySlicesShell.py index 220c36b8..e0d574b7 100644 --- a/wx/py/PySlicesShell.py +++ b/wx/py/PySlicesShell.py @@ -6,7 +6,7 @@ # main namespace to look as much as possible like the regular Python # shell environment. import __main__ -original = list(__main__.__dict__.keys()) +original = list(__main__.__dict__) __author__ = "Patrick K. O'Brien " @@ -65,7 +65,7 @@ def main(filename=None): keepers = original keepers.append('App') keepers.append('filename') - for key in list(md.keys()): + for key in list(md): if key not in keepers: del md[key] # Create an application instance. diff --git a/wx/py/PyWrap.py b/wx/py/PyWrap.py index 5496266e..254e8c0b 100644 --- a/wx/py/PyWrap.py +++ b/wx/py/PyWrap.py @@ -36,7 +36,7 @@ def main(modulename=None): # Find the App class. App = None d = module.__dict__ - for item in d.keys(): + for item in d: try: if issubclass(d[item], wx.App): App = d[item] diff --git a/wx/py/buffer.py b/wx/py/buffer.py index fa37b759..87db6084 100644 --- a/wx/py/buffer.py +++ b/wx/py/buffer.py @@ -23,7 +23,7 @@ class Buffer: self.name = '' self.editors = {} self.editor = None - self.modules = sys.modules.keys() + self.modules = list(sys.modules) self.syspath = sys.path[:] while True: try: @@ -131,6 +131,6 @@ class Buffer: return True finally: sys.path = syspath - for m in sys.modules.keys(): + for m in sys.modules: if m not in self.modules: del sys.modules[m] diff --git a/wx/py/dispatcher.py b/wx/py/dispatcher.py index 22e0b143..33e09622 100644 --- a/wx/py/dispatcher.py +++ b/wx/py/dispatcher.py @@ -169,8 +169,8 @@ def _call(receiver, **kwds): if not (fc.co_flags & 8): # fc does not have a **kwds type parameter, therefore # remove unacceptable arguments. - keys = list(kwds.keys()) - for arg in keys: + + for arg in list(kwds): if arg not in acceptable: del kwds[arg] return receiver(**kwds) @@ -226,10 +226,10 @@ class BoundMethodWeakref: def _removeReceiver(receiver): """Remove receiver from connections.""" - list_keys = [] - for senderkey in connections.keys(): - for signal in connections[senderkey].keys(): - list_keys.append((senderkey, signal)) + list_keys = [(senderkey, signal) + for senderkey in connections + for signal in connections[senderkey]] + for senderkey, signal in list_keys: try: connections[senderkey][signal].remove(receiver) diff --git a/wx/py/filling.py b/wx/py/filling.py index 039afb3b..7ce8fbf3 100644 --- a/wx/py/filling.py +++ b/wx/py/filling.py @@ -140,7 +140,7 @@ class FillingTree(wx.TreeCtrl): children = self.objGetChildren(obj) if not children: return - keys = sorted(children.keys(), key=lambda x: six.text_type(x).lower()) + keys = sorted(children, key=lambda x: six.text_type(x).lower()) for key in keys: itemtext = six.text_type(key) # Show string dictionary items with single quotes, except diff --git a/wx/py/introspect.py b/wx/py/introspect.py index c911f6de..892f8474 100644 --- a/wx/py/introspect.py +++ b/wx/py/introspect.py @@ -48,7 +48,7 @@ def getAttributeNames(obj, includeMagic=1, includeSingle=1, # Special code to allow traits to be caught by autocomplete if hasattr(obj,'trait_get'): try: - for i in obj.trait_get().keys(): + for i in obj.trait_get(): if i not in attributes: if hasattr(obj, i): attributes += i @@ -75,10 +75,10 @@ def getAttributeNames(obj, includeMagic=1, includeSingle=1, # Remove duplicates from the attribute list. for item in attributes: dict[item] = None - attributes = dict.keys() + attributes = list(dict) # new-style swig wrappings can result in non-string attributes # e.g. ITK http://www.itk.org/ - attributes = [attribute for attribute in attributes \ + attributes = [attribute for attribute in attributes if type(attribute) == str] attributes.sort(key=lambda x: x.upper()) if not includeSingle: @@ -116,7 +116,7 @@ def getAllAttributeNames(obj): attrdict[(key, 'dir', len(attributes))] = attributes # Get attributes from the object's dictionary, if it has one. try: - attributes = sorted(obj.__dict__.keys()) + attributes = sorted(obj.__dict__) except Exception: # Must catch all because object might have __getattr__. pass else: diff --git a/wx/py/magic.py b/wx/py/magic.py index d87334ae..7cd658e2 100644 --- a/wx/py/magic.py +++ b/wx/py/magic.py @@ -47,7 +47,7 @@ def magicSingle(command): n,v = c[0],' '.join(c[1:]) aliasDict[n]=v command = '' - elif command.split(' ')[0] in aliasDict.keys(): + elif command.split(' ')[0] in aliasDict: c = command.split(' ') if len(c)<2: command = 'sx("'+aliasDict[c[0]]+'")' diff --git a/wx/tools/dbg.py b/wx/tools/dbg.py index 743e7ba9..be4c1a17 100644 --- a/wx/tools/dbg.py +++ b/wx/tools/dbg.py @@ -144,7 +144,7 @@ class Logger: optional debugging output that can be displayed at an arbitrary level of indentation. """ - if not self._dbg and not 'enable' in kwargs.keys(): + if not self._dbg and not 'enable' in kwargs: return if self._dbg and len(args) and not self._suspend: