direct: Utilize the built-in sorted function

Closes #1479
This commit is contained in:
WMOkiishi 2023-03-17 17:33:45 -06:00 committed by rdb
parent 70cdbae247
commit d1f4212acd
24 changed files with 49 additions and 133 deletions

View File

@ -280,9 +280,7 @@ class Actor(DirectObject, NodePath):
self.setLODNode(node = lodNode) self.setLODNode(node = lodNode)
# preserve numerical order for lod's # preserve numerical order for lod's
# this will make it easier to set ranges # this will make it easier to set ranges
sortedKeys = list(models.keys()) for lodName in sorted(models):
sortedKeys.sort()
for lodName in sortedKeys:
# make a node under the LOD switch # make a node under the LOD switch
# for each lod (just because!) # for each lod (just because!)
self.addLOD(str(lodName)) self.addLOD(str(lodName))
@ -302,9 +300,7 @@ class Actor(DirectObject, NodePath):
# it is a single part actor w/LOD # it is a single part actor w/LOD
self.setLODNode(node = lodNode) self.setLODNode(node = lodNode)
# preserve order of LOD's # preserve order of LOD's
sortedKeys = list(models.keys()) for lodName in sorted(models):
sortedKeys.sort()
for lodName in sortedKeys:
self.addLOD(str(lodName)) self.addLOD(str(lodName))
# pass in dictionary of parts # pass in dictionary of parts
self.loadModel(models[lodName], lodName=lodName, self.loadModel(models[lodName], lodName=lodName,
@ -323,9 +319,7 @@ class Actor(DirectObject, NodePath):
if isinstance(models, dict): if isinstance(models, dict):
if isinstance(models[next(iter(models))], dict): if isinstance(models[next(iter(models))], dict):
# then we have a multi-part w/ LOD # then we have a multi-part w/ LOD
sortedKeys = list(models.keys()) for lodName in sorted(models):
sortedKeys.sort()
for lodName in sortedKeys:
# iterate over both dicts # iterate over both dicts
for partName in anims: for partName in anims:
self.loadAnims( self.loadAnims(
@ -336,9 +330,7 @@ class Actor(DirectObject, NodePath):
self.loadAnims(anims[partName], partName) self.loadAnims(anims[partName], partName)
elif isinstance(models, dict): elif isinstance(models, dict):
# then we have single-part w/ LOD # then we have single-part w/ LOD
sortedKeys = list(models.keys()) for lodName in sorted(models):
sortedKeys.sort()
for lodName in sortedKeys:
self.loadAnims(anims, lodName=lodName) self.loadAnims(anims, lodName=lodName)
else: else:
# else it is single-part w/o LOD # else it is single-part w/o LOD
@ -603,9 +595,6 @@ class Actor(DirectObject, NodePath):
return bundles return bundles
def __updateSortedLODNames(self): 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 # Reverse sort the doing a string->int
def sortKey(x): def sortKey(x):
if not str(x).isdigit(): if not str(x).isdigit():
@ -622,7 +611,9 @@ class Actor(DirectObject, NodePath):
else: else:
return int(x) 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): def getLODNames(self):
""" """

View File

@ -169,12 +169,9 @@ class ClusterClient(DirectObject.DirectObject):
self.serverList[server].sendNamedMovementDone() self.serverList[server].sendNamedMovementDone()
def redoSortedPriorities(self): def redoSortedPriorities(self):
self.sortedControlMappings = [] self.sortedControlMappings = sorted(
for key in self.controlMappings: [self.controlPriorities[key], key] for key in self.controlMappings
self.sortedControlMappings.append([self.controlPriorities[key], )
key])
self.sortedControlMappings.sort()
def moveObject(self, nodePath, object, serverList, offset, hasColor = True): def moveObject(self, nodePath, object, serverList, offset, hasColor = True):
self.notify.debug('moving object '+object) self.notify.debug('moving object '+object)

View File

@ -137,13 +137,9 @@ class ClusterServer(DirectObject.DirectObject):
self.objectMappings.pop(name) self.objectMappings.pop(name)
def redoSortedPriorities(self): def redoSortedPriorities(self):
self.sortedControlMappings = sorted(
self.sortedControlMappings = [] [self.controlPriorities[key], key] for key in self.objectMappings
for key in self.objectMappings: )
self.sortedControlMappings.append([self.controlPriorities[key],
key])
self.sortedControlMappings.sort()
def addControlMapping(self, objectName, controlledName, offset = None, def addControlMapping(self, objectName, controlledName, offset = None,
priority = 0): priority = 0):

View File

@ -66,9 +66,7 @@ class DirectLights(NodePath):
def getNameList(self): def getNameList(self):
# Return a sorted list of all lights in the light dict # Return a sorted list of all lights in the light dict
nameList = [x.getName() for x in self.lightDict.values()] return sorted(x.getName() for x in self.lightDict.values())
nameList.sort()
return nameList
def create(self, ltype): def create(self, ltype):
ltype = ltype.lower() ltype = ltype.lower()

View File

@ -1146,15 +1146,12 @@ class Freezer:
# Walk through the list in sorted order, so we reach parents # Walk through the list in sorted order, so we reach parents
# before children. # before children.
names = list(self.modules.items())
names.sort()
excludeDict = {} excludeDict = {}
implicitParentDict = {} implicitParentDict = {}
includes = [] includes = []
autoIncludes = [] autoIncludes = []
origToNewName = {} origToNewName = {}
for newName, mdef in names: for newName, mdef in sorted(self.modules.items()):
moduleName = mdef.moduleName moduleName = mdef.moduleName
origToNewName[moduleName] = newName origToNewName[moduleName] = newName
if mdef.implicit and '.' in newName: if mdef.implicit and '.' in newName:

View File

@ -859,16 +859,12 @@ class build_apps(setuptools.Command):
libdir = os.path.dirname(dtool_fn.to_os_specific()) libdir = os.path.dirname(dtool_fn.to_os_specific())
etcdir = os.path.join(libdir, '..', 'etc') etcdir = os.path.join(libdir, '..', 'etc')
etcfiles = os.listdir(etcdir) for fn in sorted(os.listdir(etcdir), reverse=True):
etcfiles.sort(reverse=True)
for fn in etcfiles:
if fn.lower().endswith('.prc'): if fn.lower().endswith('.prc'):
with open(os.path.join(etcdir, fn)) as f: with open(os.path.join(etcdir, fn)) as f:
prcstring += f.read() prcstring += f.read()
else: else:
etcfiles = [i for i in p3dwhl.namelist() if i.endswith('.prc')] for fn in sorted((i for i in p3dwhl.namelist() if i.endswith('.prc')), reverse=True):
etcfiles.sort(reverse=True)
for fn in etcfiles:
with p3dwhl.open(fn) as f: with p3dwhl.open(fn) as f:
prcstring += f.read().decode('utf8') prcstring += f.read().decode('utf8')

View File

@ -149,10 +149,7 @@ class DoCollectionManager:
class2count.setdefault(className, 0) class2count.setdefault(className, 0)
class2count[className] += 1 class2count[className] += 1
count2classes = invertDictLossless(class2count) count2classes = invertDictLossless(class2count)
counts = list(count2classes.keys()) for count in sorted(count2classes, reverse=True):
counts.sort()
counts.reverse()
for count in counts:
count2classes[count].sort() count2classes[count].sort()
for name in count2classes[count]: for name in count2classes[count]:
print('%s %s' % (count, name)) print('%s %s' % (count, name))
@ -166,10 +163,7 @@ class DoCollectionManager:
class2count.setdefault(className, 0) class2count.setdefault(className, 0)
class2count[className] += 1 class2count[className] += 1
count2classes = invertDictLossless(class2count) count2classes = invertDictLossless(class2count)
counts = list(count2classes.keys()) for count in sorted(count2classes, reverse=True):
counts.sort()
counts.reverse()
for count in counts:
count2classes[count].sort() count2classes[count].sort()
for name in count2classes[count]: for name in count2classes[count]:
# print '%s %s' % (count, name) # print '%s %s' % (count, name)

View File

@ -512,8 +512,7 @@ class DoInterestManager(DirectObject.DirectObject):
datagram = PyDatagram() datagram = PyDatagram()
# Add message type # Add message type
if isinstance(zoneIdList, list): if isinstance(zoneIdList, list):
vzl = list(zoneIdList) vzl = sorted(zoneIdList)
vzl.sort()
uniqueElements(vzl) uniqueElements(vzl)
datagram.addUint16(CLIENT_ADD_INTEREST_MULTIPLE) datagram.addUint16(CLIENT_ADD_INTEREST_MULTIPLE)
datagram.addUint32(contextId) datagram.addUint32(contextId)

View File

@ -616,9 +616,7 @@ class DirectGuiBase(DirectObject.DirectObject):
def components(self): def components(self):
# Return a list of all components. # Return a list of all components.
names = list(self.__componentInfo.keys()) return sorted(self.__componentInfo)
names.sort()
return names
def hascomponent(self, component): def hascomponent(self, component):
return component in self.__componentInfo return component in self.__componentInfo

View File

@ -116,9 +116,7 @@ class HotKeyPanel(ScrolledPanel):
def updateUI(self): def updateUI(self):
vbox = wx.BoxSizer(wx.VERTICAL) vbox = wx.BoxSizer(wx.VERTICAL)
keys = list(base.direct.hotKeyMap.keys()) for key in sorted(base.direct.hotKeyMap):
keys.sort()
for key in keys:
keyDesc = base.direct.hotKeyMap[key] keyDesc = base.direct.hotKeyMap[key]
itemPanel = wx.Panel(self) itemPanel = wx.Panel(self)
sizer = wx.BoxSizer(wx.HORIZONTAL) sizer = wx.BoxSizer(wx.HORIZONTAL)

View File

@ -55,8 +55,6 @@ class BulletinBoard:
def __repr__(self): def __repr__(self):
str = 'Bulletin Board Contents\n' str = 'Bulletin Board Contents\n'
str += '=======================' str += '======================='
keys = list(self._dict.keys()) for postName in sorted(self._dict):
keys.sort()
for postName in keys:
str += '\n%s: %s' % (postName, self._dict[postName]) str += '\n%s: %s' % (postName, self._dict[postName])
return str return str

View File

@ -228,14 +228,11 @@ class ContainerReport(Job):
if type not in self._type2id2len: if type not in self._type2id2len:
return return
len2ids = invertDictLossless(self._type2id2len[type]) len2ids = invertDictLossless(self._type2id2len[type])
lengths = list(len2ids.keys())
lengths.sort()
lengths.reverse()
print('=====') print('=====')
print('===== %s' % type) print('===== %s' % type)
count = 0 count = 0
stop = False stop = False
for l in lengths: for l in sorted(len2ids, reverse=True):
#len2ids[l].sort() #len2ids[l].sort()
pathStrList = list() pathStrList = list()
for id in len2ids[l]: for id in len2ids[l]:
@ -257,9 +254,8 @@ class ContainerReport(Job):
for type in initialTypes: for type in initialTypes:
for i in self._outputType(type, **kArgs): for i in self._outputType(type, **kArgs):
yield None yield None
otherTypes = list(set(self._type2id2len.keys()).difference(set(initialTypes))) otherTypes = set(self._type2id2len).difference(initialTypes)
otherTypes.sort(key=lambda obj: obj.__name__) for type in sorted(otherTypes, key=lambda obj: obj.__name__):
for type in otherTypes:
for i in self._outputType(type, **kArgs): for i in self._outputType(type, **kArgs):
yield None yield None

View File

@ -116,15 +116,10 @@ def _excepthookDumpVars(eType, eValue, tb):
for name, obj in frame.f_locals.items(): for name, obj in frame.f_locals.items():
if name in codeNames: if name in codeNames:
name2obj[name] = obj 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() traversedIds = set()
# push them in reverse alphabetical order so they'll be popped in the correct order
for name in names: for name in sorted(name2obj, reverse=True):
stateStack.push([name, name2obj[name], traversedIds]) stateStack.push([name, name2obj[name], traversedIds])
while len(stateStack) > 0: while len(stateStack) > 0:
@ -150,14 +145,10 @@ def _excepthookDumpVars(eType, eValue, tb):
continue continue
attrName2obj[attrName] = attr attrName2obj[attrName] = attr
if len(attrName2obj) > 0: 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 = set(traversedIds)
ids.add(id(obj)) 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] obj = attrName2obj[attrName]
stateStack.push(['%s.%s' % (name, attrName), obj, ids]) stateStack.push(['%s.%s' % (name, attrName), obj, ids])

View File

@ -294,8 +294,7 @@ class GarbageReport(Job):
if self._args.fullReport: if self._args.fullReport:
garbageIndices = range(self.numGarbage) garbageIndices = range(self.numGarbage)
else: else:
garbageIndices = list(self.cycleIds) garbageIndices = sorted(self.cycleIds)
garbageIndices.sort()
numGarbage = len(garbageIndices) numGarbage = len(garbageIndices)
# log each individual item with a number in front of it # log each individual item with a number in front of it

View File

@ -141,9 +141,7 @@ class JobManager:
def _getSortedPriorities(self): def _getSortedPriorities(self):
# returns all job priorities in ascending order # returns all job priorities in ascending order
priorities = list(self._pri2jobId2job.keys()) return sorted(self._pri2jobId2job)
priorities.sort()
return priorities
def _process(self, task=None): def _process(self, task=None):
if self._useOverflowTime is None: if self._useOverflowTime is None:

View File

@ -540,9 +540,7 @@ class Messenger:
return a matching event (needle) if found (in haystack). return a matching event (needle) if found (in haystack).
This is primarily a debugging tool. This is primarily a debugging tool.
""" """
keys = list(self.__callbacks.keys()) for event in sorted(self.__callbacks):
keys.sort()
for event in keys:
if repr(event).find(needle) >= 0: if repr(event).find(needle) >= 0:
return {event: self.__callbacks[event]} return {event: self.__callbacks[event]}
@ -553,9 +551,7 @@ class Messenger:
This is primarily a debugging tool. This is primarily a debugging tool.
""" """
matches = {} matches = {}
keys = list(self.__callbacks.keys()) for event in sorted(self.__callbacks):
keys.sort()
for event in keys:
if repr(event).find(needle) >= 0: if repr(event).find(needle) >= 0:
matches[event] = self.__callbacks[event] matches[event] = self.__callbacks[event]
# if the limit is not None, decrement and # if the limit is not None, decrement and
@ -596,9 +592,7 @@ class Messenger:
Compact version of event, acceptor pairs Compact version of event, acceptor pairs
""" """
str = "The messenger is currently handling:\n" + "="*64 + "\n" str = "The messenger is currently handling:\n" + "="*64 + "\n"
keys = list(self.__callbacks.keys()) for event in sorted(self.__callbacks):
keys.sort()
for event in keys:
str += self.__eventRepr(event) str += self.__eventRepr(event)
# Print out the object: event dictionary too # Print out the object: event dictionary too
str += "="*64 + "\n" str += "="*64 + "\n"
@ -617,9 +611,7 @@ class Messenger:
""" """
str = 'Messenger\n' str = 'Messenger\n'
str = str + '='*50 + '\n' str = str + '='*50 + '\n'
keys = list(self.__callbacks.keys()) for event in sorted(self.__callbacks):
keys.sort()
for event in keys:
acceptorDict = self.__callbacks[event] acceptorDict = self.__callbacks[event]
str = str + 'Event: ' + event + '\n' str = str + 'Event: ' + event + '\n'
for key in list(acceptorDict.keys()): for key in list(acceptorDict.keys()):

View File

@ -90,10 +90,7 @@ class ObjectPool:
def typeFreqStr(self): def typeFreqStr(self):
s = 'Object Pool: Type Frequencies' s = 'Object Pool: Type Frequencies'
s += '\n=============================' s += '\n============================='
counts = list(set(self._count2types.keys())) for count in sorted(self._count2types, reverse=True):
counts.sort()
counts.reverse()
for count in counts:
types = makeList(self._count2types[count]) types = makeList(self._count2types[count])
for typ in types: for typ in types:
s += '\n%s\t%s' % (count, typ) s += '\n%s\t%s' % (count, typ)
@ -102,12 +99,10 @@ class ObjectPool:
def printObjsByType(self): def printObjsByType(self):
print('Object Pool: Objects By Type') print('Object Pool: Objects By Type')
print('\n============================') print('\n============================')
counts = list(set(self._count2types.keys()))
counts.sort()
# print types with the smallest number of instances first, in case # print types with the smallest number of instances first, in case
# there's a large group that waits a long time before printing # there's a large group that waits a long time before printing
#counts.reverse() #counts.reverse()
for count in counts: for count in sorted(self._count2types):
types = makeList(self._count2types[count]) types = makeList(self._count2types[count])
for typ in types: for typ in types:
print('TYPE: %s, %s objects' % (repr(typ), len(self._type2objs[typ]))) print('TYPE: %s, %s objects' % (repr(typ), len(self._type2objs[typ])))
@ -115,10 +110,7 @@ class ObjectPool:
def printReferrers(self, numEach=3): def printReferrers(self, numEach=3):
"""referrers of the first few of each type of object""" """referrers of the first few of each type of object"""
counts = list(set(self._count2types.keys())) for count in sorted(self._count2types, reverse=True):
counts.sort()
counts.reverse()
for count in counts:
types = makeList(self._count2types[count]) types = makeList(self._count2types[count])
for typ in types: for typ in types:
print('\n\nTYPE: %s' % repr(typ)) print('\n\nTYPE: %s' % repr(typ))

View File

@ -57,9 +57,7 @@ class OnScreenDebug:
if not self.onScreenText: if not self.onScreenText:
self.load() self.load()
self.onScreenText.clearText() self.onScreenText.clearText()
entries = list(self.data.items()) for k, v in sorted(self.data.items()):
entries.sort()
for k, v in entries:
if v[0] == self.frame: if v[0] == self.frame:
# It was updated this frame (key equals value): # It was updated this frame (key equals value):
#isNew = " is" #isNew = " is"

View File

@ -756,8 +756,8 @@ class TexMemWatcher(DirectObject):
# Sort the regions from largest to smallest to maximize # Sort the regions from largest to smallest to maximize
# packing effectiveness. # packing effectiveness.
texRecords = list(self.texRecordsByTex.values()) texRecords = sorted(self.texRecordsByTex.values(),
texRecords.sort(key = lambda tr: (tr.tw, tr.th), reverse = True) key=lambda tr: (tr.tw, tr.th), reverse=True)
for tr in texRecords: for tr in texRecords:
self.placeTexture(tr) self.placeTexture(tr)

View File

@ -358,8 +358,7 @@ class FSMInspector(AppShell):
def printLayout(self): def printLayout(self):
dict = self.stateInspectorDict dict = self.stateInspectorDict
keys = list(dict.keys()) keys = sorted(dict)
keys.sort()
print("ClassicFSM.ClassicFSM('%s', [" % self.name) print("ClassicFSM.ClassicFSM('%s', [" % self.name)
for key in keys[:-1]: for key in keys[:-1]:
si = dict[key] si = dict[key]

View File

@ -95,9 +95,7 @@ class Inspector:
def initializePartsList(self): def initializePartsList(self):
self._partsList = [] self._partsList = []
keys = self.namedParts() for each in sorted(self.namedParts()):
keys.sort()
for each in keys:
self._partsList.append(each) self._partsList.append(each)
#if not callable(getattr(self.object, each)): #if not callable(getattr(self.object, each)):
# self._partsList.append(each) # self._partsList.append(each)
@ -202,9 +200,7 @@ class DictionaryInspector(Inspector):
def initializePartsList(self): def initializePartsList(self):
Inspector.initializePartsList(self) Inspector.initializePartsList(self)
keys = list(self.object.keys()) for each in sorted(self.object):
keys.sort()
for each in keys:
self._partsList.append(each) self._partsList.append(each)
def partNumber(self, partNumber): def partNumber(self, partNumber):

View File

@ -1174,9 +1174,7 @@ class ParticlePanel(AppShell):
self.particlesLabelMenu.add_separator() self.particlesLabelMenu.add_separator()
# Add in a checkbutton for each effect (to toggle on/off) # Add in a checkbutton for each effect (to toggle on/off)
particles = self.particleEffect.getParticlesList() particles = self.particleEffect.getParticlesList()
names = [x.getName() for x in particles] for name in sorted(x.getName() for x in particles):
names.sort()
for name in names:
particle = self.particleEffect.getParticlesNamed(name) particle = self.particleEffect.getParticlesNamed(name)
self.particlesLabelMenu.add_command( self.particlesLabelMenu.add_command(
label = name, label = name,
@ -1199,9 +1197,7 @@ class ParticlePanel(AppShell):
self.forceGroupLabelMenu.add_separator() self.forceGroupLabelMenu.add_separator()
# Add in a checkbutton for each effect (to toggle on/off) # Add in a checkbutton for each effect (to toggle on/off)
forceGroupList = self.particleEffect.getForceGroupList() forceGroupList = self.particleEffect.getForceGroupList()
names = [x.getName() for x in forceGroupList] for name in sorted(x.getName() for x in forceGroupList):
names.sort()
for name in names:
force = self.particleEffect.getForceGroupNamed(name) force = self.particleEffect.getForceGroupNamed(name)
self.forceGroupLabelMenu.add_command( self.forceGroupLabelMenu.add_command(
label = name, label = name,

View File

@ -151,10 +151,8 @@ class TaskManagerWidget(DirectObject):
# Get a list of task names # Get a list of task names
taskNames = [] taskNames = []
self.__taskDict = {} self.__taskDict = {}
tasks = self.taskMgr.getTasks()
tasks.sort(key = lambda t: t.getName())
count = 0 count = 0
for task in tasks: for task in sorted(self.taskMgr.getTasks(), key=lambda t: t.getName()):
taskNames.append(task.getName()) taskNames.append(task.getName())
self.__taskDict[count] = task self.__taskDict[count] = task
count += 1 count += 1

View File

@ -21,8 +21,7 @@ class WidgetPropertiesDialog(tk.Toplevel):
self.propertyDict = propertyDict self.propertyDict = propertyDict
self.propertyList = propertyList self.propertyList = propertyList
if self.propertyList is None: if self.propertyList is None:
self.propertyList = list(self.propertyDict.keys()) self.propertyList = sorted(self.propertyDict)
self.propertyList.sort()
# Use default parent if none specified # Use default parent if none specified
if not parent: if not parent:
parent = tk._default_root parent = tk._default_root