From d1f4212acdc01b5ceda8edc03fe70b273c3a02da Mon Sep 17 00:00:00 2001 From: WMOkiishi Date: Fri, 17 Mar 2023 17:33:45 -0600 Subject: [PATCH] direct: Utilize the built-in `sorted` function Closes #1479 --- direct/src/actor/Actor.py | 23 ++++++------------- direct/src/cluster/ClusterClient.py | 9 +++----- direct/src/cluster/ClusterServer.py | 10 +++----- direct/src/directtools/DirectLights.py | 4 +--- direct/src/dist/FreezeTool.py | 5 +--- direct/src/dist/commands.py | 8 ++----- direct/src/distributed/DoCollectionManager.py | 10 ++------ direct/src/distributed/DoInterestManager.py | 3 +-- direct/src/gui/DirectGuiBase.py | 4 +--- direct/src/leveleditor/HotKeyUI.py | 4 +--- direct/src/showbase/BulletinBoard.py | 4 +--- direct/src/showbase/ContainerReport.py | 10 +++----- direct/src/showbase/ExceptionVarDump.py | 17 ++++---------- direct/src/showbase/GarbageReport.py | 3 +-- direct/src/showbase/JobManager.py | 4 +--- direct/src/showbase/Messenger.py | 16 ++++--------- direct/src/showbase/ObjectPool.py | 14 +++-------- direct/src/showbase/OnScreenDebug.py | 4 +--- direct/src/showutil/TexMemWatcher.py | 4 ++-- direct/src/tkpanels/FSMInspector.py | 3 +-- direct/src/tkpanels/Inspector.py | 8 ++----- direct/src/tkpanels/ParticlePanel.py | 8 ++----- direct/src/tkpanels/TaskManagerPanel.py | 4 +--- .../src/tkwidgets/WidgetPropertiesDialog.py | 3 +-- 24 files changed, 49 insertions(+), 133 deletions(-) diff --git a/direct/src/actor/Actor.py b/direct/src/actor/Actor.py index c9e8b8b8b3..263ac8803a 100644 --- a/direct/src/actor/Actor.py +++ b/direct/src/actor/Actor.py @@ -280,9 +280,7 @@ class Actor(DirectObject, NodePath): self.setLODNode(node = lodNode) # preserve numerical order for lod's # this will make it easier to set ranges - sortedKeys = list(models.keys()) - sortedKeys.sort() - for lodName in sortedKeys: + for lodName in sorted(models): # make a node under the LOD switch # for each lod (just because!) self.addLOD(str(lodName)) @@ -302,9 +300,7 @@ class Actor(DirectObject, NodePath): # it is a single part actor w/LOD self.setLODNode(node = lodNode) # preserve order of LOD's - sortedKeys = list(models.keys()) - sortedKeys.sort() - for lodName in sortedKeys: + for lodName in sorted(models): self.addLOD(str(lodName)) # pass in dictionary of parts self.loadModel(models[lodName], lodName=lodName, @@ -323,9 +319,7 @@ class Actor(DirectObject, NodePath): if isinstance(models, dict): if isinstance(models[next(iter(models))], dict): # then we have a multi-part w/ LOD - sortedKeys = list(models.keys()) - sortedKeys.sort() - for lodName in sortedKeys: + for lodName in sorted(models): # iterate over both dicts for partName in anims: self.loadAnims( @@ -336,9 +330,7 @@ class Actor(DirectObject, NodePath): self.loadAnims(anims[partName], partName) elif isinstance(models, dict): # then we have single-part w/ LOD - sortedKeys = list(models.keys()) - sortedKeys.sort() - for lodName in sortedKeys: + for lodName in sorted(models): self.loadAnims(anims, lodName=lodName) else: # else it is single-part w/o LOD @@ -603,9 +595,6 @@ class Actor(DirectObject, NodePath): return bundles def __updateSortedLODNames(self): - # Cache the sorted LOD names so we don't have to grab them - # and sort them every time somebody asks for the list - self.__sortedLODNames = list(self.__partBundleDict.keys()) # Reverse sort the doing a string->int def sortKey(x): if not str(x).isdigit(): @@ -622,7 +611,9 @@ class Actor(DirectObject, NodePath): else: return int(x) - self.__sortedLODNames.sort(key=sortKey, reverse=True) + # Cache the sorted LOD names so we don't have to grab them + # and sort them every time somebody asks for the list + self.__sortedLODNames = sorted(self.__partBundleDict, key=sortKey, reverse=True) def getLODNames(self): """ diff --git a/direct/src/cluster/ClusterClient.py b/direct/src/cluster/ClusterClient.py index fac896f1e4..e5c0b7ba6a 100644 --- a/direct/src/cluster/ClusterClient.py +++ b/direct/src/cluster/ClusterClient.py @@ -169,12 +169,9 @@ class ClusterClient(DirectObject.DirectObject): self.serverList[server].sendNamedMovementDone() def redoSortedPriorities(self): - self.sortedControlMappings = [] - for key in self.controlMappings: - self.sortedControlMappings.append([self.controlPriorities[key], - key]) - - self.sortedControlMappings.sort() + self.sortedControlMappings = sorted( + [self.controlPriorities[key], key] for key in self.controlMappings + ) def moveObject(self, nodePath, object, serverList, offset, hasColor = True): self.notify.debug('moving object '+object) diff --git a/direct/src/cluster/ClusterServer.py b/direct/src/cluster/ClusterServer.py index ba707f17dd..5d62146cc1 100644 --- a/direct/src/cluster/ClusterServer.py +++ b/direct/src/cluster/ClusterServer.py @@ -137,13 +137,9 @@ class ClusterServer(DirectObject.DirectObject): self.objectMappings.pop(name) def redoSortedPriorities(self): - - self.sortedControlMappings = [] - for key in self.objectMappings: - self.sortedControlMappings.append([self.controlPriorities[key], - key]) - - self.sortedControlMappings.sort() + self.sortedControlMappings = sorted( + [self.controlPriorities[key], key] for key in self.objectMappings + ) def addControlMapping(self, objectName, controlledName, offset = None, priority = 0): diff --git a/direct/src/directtools/DirectLights.py b/direct/src/directtools/DirectLights.py index 5fe757d688..a96e3d971e 100644 --- a/direct/src/directtools/DirectLights.py +++ b/direct/src/directtools/DirectLights.py @@ -66,9 +66,7 @@ class DirectLights(NodePath): def getNameList(self): # Return a sorted list of all lights in the light dict - nameList = [x.getName() for x in self.lightDict.values()] - nameList.sort() - return nameList + return sorted(x.getName() for x in self.lightDict.values()) def create(self, ltype): ltype = ltype.lower() diff --git a/direct/src/dist/FreezeTool.py b/direct/src/dist/FreezeTool.py index 4bf6dca3ac..84189ac77c 100644 --- a/direct/src/dist/FreezeTool.py +++ b/direct/src/dist/FreezeTool.py @@ -1146,15 +1146,12 @@ class Freezer: # Walk through the list in sorted order, so we reach parents # before children. - names = list(self.modules.items()) - names.sort() - excludeDict = {} implicitParentDict = {} includes = [] autoIncludes = [] origToNewName = {} - for newName, mdef in names: + for newName, mdef in sorted(self.modules.items()): moduleName = mdef.moduleName origToNewName[moduleName] = newName if mdef.implicit and '.' in newName: diff --git a/direct/src/dist/commands.py b/direct/src/dist/commands.py index 6036c6abcc..5410199307 100644 --- a/direct/src/dist/commands.py +++ b/direct/src/dist/commands.py @@ -859,16 +859,12 @@ class build_apps(setuptools.Command): libdir = os.path.dirname(dtool_fn.to_os_specific()) etcdir = os.path.join(libdir, '..', 'etc') - etcfiles = os.listdir(etcdir) - etcfiles.sort(reverse=True) - for fn in etcfiles: + for fn in sorted(os.listdir(etcdir), reverse=True): if fn.lower().endswith('.prc'): with open(os.path.join(etcdir, fn)) as f: prcstring += f.read() else: - etcfiles = [i for i in p3dwhl.namelist() if i.endswith('.prc')] - etcfiles.sort(reverse=True) - for fn in etcfiles: + for fn in sorted((i for i in p3dwhl.namelist() if i.endswith('.prc')), reverse=True): with p3dwhl.open(fn) as f: prcstring += f.read().decode('utf8') diff --git a/direct/src/distributed/DoCollectionManager.py b/direct/src/distributed/DoCollectionManager.py index 21eeb10751..cd022015bf 100755 --- a/direct/src/distributed/DoCollectionManager.py +++ b/direct/src/distributed/DoCollectionManager.py @@ -149,10 +149,7 @@ class DoCollectionManager: class2count.setdefault(className, 0) class2count[className] += 1 count2classes = invertDictLossless(class2count) - counts = list(count2classes.keys()) - counts.sort() - counts.reverse() - for count in counts: + for count in sorted(count2classes, reverse=True): count2classes[count].sort() for name in count2classes[count]: print('%s %s' % (count, name)) @@ -166,10 +163,7 @@ class DoCollectionManager: class2count.setdefault(className, 0) class2count[className] += 1 count2classes = invertDictLossless(class2count) - counts = list(count2classes.keys()) - counts.sort() - counts.reverse() - for count in counts: + for count in sorted(count2classes, reverse=True): count2classes[count].sort() for name in count2classes[count]: # print '%s %s' % (count, name) diff --git a/direct/src/distributed/DoInterestManager.py b/direct/src/distributed/DoInterestManager.py index 0297847966..251e0b91a1 100755 --- a/direct/src/distributed/DoInterestManager.py +++ b/direct/src/distributed/DoInterestManager.py @@ -512,8 +512,7 @@ class DoInterestManager(DirectObject.DirectObject): datagram = PyDatagram() # Add message type if isinstance(zoneIdList, list): - vzl = list(zoneIdList) - vzl.sort() + vzl = sorted(zoneIdList) uniqueElements(vzl) datagram.addUint16(CLIENT_ADD_INTEREST_MULTIPLE) datagram.addUint32(contextId) diff --git a/direct/src/gui/DirectGuiBase.py b/direct/src/gui/DirectGuiBase.py index fa2721f688..24424855d0 100644 --- a/direct/src/gui/DirectGuiBase.py +++ b/direct/src/gui/DirectGuiBase.py @@ -616,9 +616,7 @@ class DirectGuiBase(DirectObject.DirectObject): def components(self): # Return a list of all components. - names = list(self.__componentInfo.keys()) - names.sort() - return names + return sorted(self.__componentInfo) def hascomponent(self, component): return component in self.__componentInfo diff --git a/direct/src/leveleditor/HotKeyUI.py b/direct/src/leveleditor/HotKeyUI.py index 8cde68b0eb..2c56a065aa 100755 --- a/direct/src/leveleditor/HotKeyUI.py +++ b/direct/src/leveleditor/HotKeyUI.py @@ -116,9 +116,7 @@ class HotKeyPanel(ScrolledPanel): def updateUI(self): vbox = wx.BoxSizer(wx.VERTICAL) - keys = list(base.direct.hotKeyMap.keys()) - keys.sort() - for key in keys: + for key in sorted(base.direct.hotKeyMap): keyDesc = base.direct.hotKeyMap[key] itemPanel = wx.Panel(self) sizer = wx.BoxSizer(wx.HORIZONTAL) diff --git a/direct/src/showbase/BulletinBoard.py b/direct/src/showbase/BulletinBoard.py index 9478b68bfa..96b809157c 100755 --- a/direct/src/showbase/BulletinBoard.py +++ b/direct/src/showbase/BulletinBoard.py @@ -55,8 +55,6 @@ class BulletinBoard: def __repr__(self): str = 'Bulletin Board Contents\n' str += '=======================' - keys = list(self._dict.keys()) - keys.sort() - for postName in keys: + for postName in sorted(self._dict): str += '\n%s: %s' % (postName, self._dict[postName]) return str diff --git a/direct/src/showbase/ContainerReport.py b/direct/src/showbase/ContainerReport.py index 6075d55062..6ceca73d07 100755 --- a/direct/src/showbase/ContainerReport.py +++ b/direct/src/showbase/ContainerReport.py @@ -228,14 +228,11 @@ class ContainerReport(Job): if type not in self._type2id2len: return len2ids = invertDictLossless(self._type2id2len[type]) - lengths = list(len2ids.keys()) - lengths.sort() - lengths.reverse() print('=====') print('===== %s' % type) count = 0 stop = False - for l in lengths: + for l in sorted(len2ids, reverse=True): #len2ids[l].sort() pathStrList = list() for id in len2ids[l]: @@ -257,9 +254,8 @@ class ContainerReport(Job): for type in initialTypes: for i in self._outputType(type, **kArgs): yield None - otherTypes = list(set(self._type2id2len.keys()).difference(set(initialTypes))) - otherTypes.sort(key=lambda obj: obj.__name__) - for type in otherTypes: + otherTypes = set(self._type2id2len).difference(initialTypes) + for type in sorted(otherTypes, key=lambda obj: obj.__name__): for i in self._outputType(type, **kArgs): yield None diff --git a/direct/src/showbase/ExceptionVarDump.py b/direct/src/showbase/ExceptionVarDump.py index b1ccf266a8..b2cc73f68a 100755 --- a/direct/src/showbase/ExceptionVarDump.py +++ b/direct/src/showbase/ExceptionVarDump.py @@ -116,15 +116,10 @@ def _excepthookDumpVars(eType, eValue, tb): for name, obj in frame.f_locals.items(): if name in codeNames: name2obj[name] = obj - # show them in alphabetical order - names = list(name2obj.keys()) - names.sort() - # push them in reverse order so they'll be popped in the correct order - names.reverse() traversedIds = set() - - for name in names: + # push them in reverse alphabetical order so they'll be popped in the correct order + for name in sorted(name2obj, reverse=True): stateStack.push([name, name2obj[name], traversedIds]) while len(stateStack) > 0: @@ -150,14 +145,10 @@ def _excepthookDumpVars(eType, eValue, tb): continue attrName2obj[attrName] = attr if len(attrName2obj) > 0: - # show them in alphabetical order - attrNames = list(attrName2obj.keys()) - attrNames.sort() - # push them in reverse order so they'll be popped in the correct order - attrNames.reverse() ids = set(traversedIds) ids.add(id(obj)) - for attrName in attrNames: + # push them in reverse alphabetical order so they'll be popped in the correct order + for attrName in sorted(attrName2obj, reverse=True): obj = attrName2obj[attrName] stateStack.push(['%s.%s' % (name, attrName), obj, ids]) diff --git a/direct/src/showbase/GarbageReport.py b/direct/src/showbase/GarbageReport.py index fd101bc6c2..ca3d02b36a 100644 --- a/direct/src/showbase/GarbageReport.py +++ b/direct/src/showbase/GarbageReport.py @@ -294,8 +294,7 @@ class GarbageReport(Job): if self._args.fullReport: garbageIndices = range(self.numGarbage) else: - garbageIndices = list(self.cycleIds) - garbageIndices.sort() + garbageIndices = sorted(self.cycleIds) numGarbage = len(garbageIndices) # log each individual item with a number in front of it diff --git a/direct/src/showbase/JobManager.py b/direct/src/showbase/JobManager.py index 68bcbd0e32..e6f034f08c 100755 --- a/direct/src/showbase/JobManager.py +++ b/direct/src/showbase/JobManager.py @@ -141,9 +141,7 @@ class JobManager: def _getSortedPriorities(self): # returns all job priorities in ascending order - priorities = list(self._pri2jobId2job.keys()) - priorities.sort() - return priorities + return sorted(self._pri2jobId2job) def _process(self, task=None): if self._useOverflowTime is None: diff --git a/direct/src/showbase/Messenger.py b/direct/src/showbase/Messenger.py index 0a7e38e82b..e6ef2153c2 100644 --- a/direct/src/showbase/Messenger.py +++ b/direct/src/showbase/Messenger.py @@ -540,9 +540,7 @@ class Messenger: return a matching event (needle) if found (in haystack). This is primarily a debugging tool. """ - keys = list(self.__callbacks.keys()) - keys.sort() - for event in keys: + for event in sorted(self.__callbacks): if repr(event).find(needle) >= 0: return {event: self.__callbacks[event]} @@ -553,9 +551,7 @@ class Messenger: This is primarily a debugging tool. """ matches = {} - keys = list(self.__callbacks.keys()) - keys.sort() - for event in keys: + for event in sorted(self.__callbacks): if repr(event).find(needle) >= 0: matches[event] = self.__callbacks[event] # if the limit is not None, decrement and @@ -596,9 +592,7 @@ class Messenger: Compact version of event, acceptor pairs """ str = "The messenger is currently handling:\n" + "="*64 + "\n" - keys = list(self.__callbacks.keys()) - keys.sort() - for event in keys: + for event in sorted(self.__callbacks): str += self.__eventRepr(event) # Print out the object: event dictionary too str += "="*64 + "\n" @@ -617,9 +611,7 @@ class Messenger: """ str = 'Messenger\n' str = str + '='*50 + '\n' - keys = list(self.__callbacks.keys()) - keys.sort() - for event in keys: + for event in sorted(self.__callbacks): acceptorDict = self.__callbacks[event] str = str + 'Event: ' + event + '\n' for key in list(acceptorDict.keys()): diff --git a/direct/src/showbase/ObjectPool.py b/direct/src/showbase/ObjectPool.py index 125fb7f326..e895d0f8a5 100755 --- a/direct/src/showbase/ObjectPool.py +++ b/direct/src/showbase/ObjectPool.py @@ -90,10 +90,7 @@ class ObjectPool: def typeFreqStr(self): s = 'Object Pool: Type Frequencies' s += '\n=============================' - counts = list(set(self._count2types.keys())) - counts.sort() - counts.reverse() - for count in counts: + for count in sorted(self._count2types, reverse=True): types = makeList(self._count2types[count]) for typ in types: s += '\n%s\t%s' % (count, typ) @@ -102,12 +99,10 @@ class ObjectPool: def printObjsByType(self): print('Object Pool: Objects By Type') print('\n============================') - counts = list(set(self._count2types.keys())) - counts.sort() # print types with the smallest number of instances first, in case # there's a large group that waits a long time before printing #counts.reverse() - for count in counts: + for count in sorted(self._count2types): types = makeList(self._count2types[count]) for typ in types: print('TYPE: %s, %s objects' % (repr(typ), len(self._type2objs[typ]))) @@ -115,10 +110,7 @@ class ObjectPool: def printReferrers(self, numEach=3): """referrers of the first few of each type of object""" - counts = list(set(self._count2types.keys())) - counts.sort() - counts.reverse() - for count in counts: + for count in sorted(self._count2types, reverse=True): types = makeList(self._count2types[count]) for typ in types: print('\n\nTYPE: %s' % repr(typ)) diff --git a/direct/src/showbase/OnScreenDebug.py b/direct/src/showbase/OnScreenDebug.py index 7483d3c9f1..0d690e3806 100755 --- a/direct/src/showbase/OnScreenDebug.py +++ b/direct/src/showbase/OnScreenDebug.py @@ -57,9 +57,7 @@ class OnScreenDebug: if not self.onScreenText: self.load() self.onScreenText.clearText() - entries = list(self.data.items()) - entries.sort() - for k, v in entries: + for k, v in sorted(self.data.items()): if v[0] == self.frame: # It was updated this frame (key equals value): #isNew = " is" diff --git a/direct/src/showutil/TexMemWatcher.py b/direct/src/showutil/TexMemWatcher.py index 5418f1c6ba..3135c76b05 100644 --- a/direct/src/showutil/TexMemWatcher.py +++ b/direct/src/showutil/TexMemWatcher.py @@ -756,8 +756,8 @@ class TexMemWatcher(DirectObject): # Sort the regions from largest to smallest to maximize # packing effectiveness. - texRecords = list(self.texRecordsByTex.values()) - texRecords.sort(key = lambda tr: (tr.tw, tr.th), reverse = True) + texRecords = sorted(self.texRecordsByTex.values(), + key=lambda tr: (tr.tw, tr.th), reverse=True) for tr in texRecords: self.placeTexture(tr) diff --git a/direct/src/tkpanels/FSMInspector.py b/direct/src/tkpanels/FSMInspector.py index 12049542fa..f3b20aa258 100644 --- a/direct/src/tkpanels/FSMInspector.py +++ b/direct/src/tkpanels/FSMInspector.py @@ -358,8 +358,7 @@ class FSMInspector(AppShell): def printLayout(self): dict = self.stateInspectorDict - keys = list(dict.keys()) - keys.sort() + keys = sorted(dict) print("ClassicFSM.ClassicFSM('%s', [" % self.name) for key in keys[:-1]: si = dict[key] diff --git a/direct/src/tkpanels/Inspector.py b/direct/src/tkpanels/Inspector.py index 592e670cea..15cc04dc46 100644 --- a/direct/src/tkpanels/Inspector.py +++ b/direct/src/tkpanels/Inspector.py @@ -95,9 +95,7 @@ class Inspector: def initializePartsList(self): self._partsList = [] - keys = self.namedParts() - keys.sort() - for each in keys: + for each in sorted(self.namedParts()): self._partsList.append(each) #if not callable(getattr(self.object, each)): # self._partsList.append(each) @@ -202,9 +200,7 @@ class DictionaryInspector(Inspector): def initializePartsList(self): Inspector.initializePartsList(self) - keys = list(self.object.keys()) - keys.sort() - for each in keys: + for each in sorted(self.object): self._partsList.append(each) def partNumber(self, partNumber): diff --git a/direct/src/tkpanels/ParticlePanel.py b/direct/src/tkpanels/ParticlePanel.py index aeebb9cd25..7408497ac2 100644 --- a/direct/src/tkpanels/ParticlePanel.py +++ b/direct/src/tkpanels/ParticlePanel.py @@ -1174,9 +1174,7 @@ class ParticlePanel(AppShell): self.particlesLabelMenu.add_separator() # Add in a checkbutton for each effect (to toggle on/off) particles = self.particleEffect.getParticlesList() - names = [x.getName() for x in particles] - names.sort() - for name in names: + for name in sorted(x.getName() for x in particles): particle = self.particleEffect.getParticlesNamed(name) self.particlesLabelMenu.add_command( label = name, @@ -1199,9 +1197,7 @@ class ParticlePanel(AppShell): self.forceGroupLabelMenu.add_separator() # Add in a checkbutton for each effect (to toggle on/off) forceGroupList = self.particleEffect.getForceGroupList() - names = [x.getName() for x in forceGroupList] - names.sort() - for name in names: + for name in sorted(x.getName() for x in forceGroupList): force = self.particleEffect.getForceGroupNamed(name) self.forceGroupLabelMenu.add_command( label = name, diff --git a/direct/src/tkpanels/TaskManagerPanel.py b/direct/src/tkpanels/TaskManagerPanel.py index 3f974c1fb2..ce1da584d6 100644 --- a/direct/src/tkpanels/TaskManagerPanel.py +++ b/direct/src/tkpanels/TaskManagerPanel.py @@ -151,10 +151,8 @@ class TaskManagerWidget(DirectObject): # Get a list of task names taskNames = [] self.__taskDict = {} - tasks = self.taskMgr.getTasks() - tasks.sort(key = lambda t: t.getName()) count = 0 - for task in tasks: + for task in sorted(self.taskMgr.getTasks(), key=lambda t: t.getName()): taskNames.append(task.getName()) self.__taskDict[count] = task count += 1 diff --git a/direct/src/tkwidgets/WidgetPropertiesDialog.py b/direct/src/tkwidgets/WidgetPropertiesDialog.py index 92d48b4d9f..31fa2a9038 100644 --- a/direct/src/tkwidgets/WidgetPropertiesDialog.py +++ b/direct/src/tkwidgets/WidgetPropertiesDialog.py @@ -21,8 +21,7 @@ class WidgetPropertiesDialog(tk.Toplevel): self.propertyDict = propertyDict self.propertyList = propertyList if self.propertyList is None: - self.propertyList = list(self.propertyDict.keys()) - self.propertyList.sort() + self.propertyList = sorted(self.propertyDict) # Use default parent if none specified if not parent: parent = tk._default_root