diff --git a/source/IAccessibleHandler.py b/source/IAccessibleHandler.py index 0d8dc905785..52a1fd3d893 100644 --- a/source/IAccessibleHandler.py +++ b/source/IAccessibleHandler.py @@ -111,7 +111,7 @@ def flushEvents(self): g=self._genericEventCache self._genericEventCache={} threadCounters={} - for k,v in sorted(g.iteritems(),key=lambda item: item[1],reverse=True): + for k,v in sorted(g.items(),key=lambda item: item[1],reverse=True): threadCount=threadCounters.get(k[-1],0) if threadCount>MAX_WINEVENTS_PER_THREAD: continue @@ -119,7 +119,7 @@ def flushEvents(self): threadCounters[k[-1]]=threadCount+1 f=self._focusEventCache self._focusEventCache={} - for k,v in sorted(f.iteritems(),key=lambda item: item[1])[0-self.maxFocusItems:]: + for k,v in sorted(f.items(),key=lambda item: item[1])[0-self.maxFocusItems:]: heapq.heappush(self._eventHeap,(v,)+k) e=self._eventHeap self._eventHeap=[] @@ -832,7 +832,9 @@ def initialize(): accPropServices=comtypes.client.CreateObject(CAccPropServices) except (WindowsError,COMError) as e: log.debugWarning("AccPropServices is not available: %s"%e) - for eventType in winEventIDsToNVDAEventNames.keys(): + # #9067 (Py3 review required): originally, this calls dict.keys, which in Python 2 returns a list and Python 3 assumes iterators. + # Therefore wrap this around a list call. + for eventType in list(winEventIDsToNVDAEventNames.keys()): hookID=winUser.setWinEventHook(eventType,eventType,0,cWinEventCallback,0,0,0) if hookID: winEventHookIDs.append(hookID) diff --git a/source/NVDAObjects/IAccessible/__init__.py b/source/NVDAObjects/IAccessible/__init__.py index bbfa0375ce7..7430386b1be 100644 --- a/source/NVDAObjects/IAccessible/__init__.py +++ b/source/NVDAObjects/IAccessible/__init__.py @@ -1366,7 +1366,9 @@ def _get_positionInfo(self): del info['indexInGroup'] del info['similarItemsInGroup'] # 0 means not applicable, so remove it. - for key, val in info.items(): + # #9067 (Py3 review required): originally this called dict.items, which returns iterators in Python 3. + # Therefore wrap this inside a list call. + for key, val in list(info.items()): if not val: del info[key] return info @@ -1376,7 +1378,7 @@ def _get_positionInfo(self): d=self.decodedAccDescription if d and not isinstance(d,basestring): groupdict=d.groupdict() - return {x:int(y) for x,y in groupdict.iteritems() if y is not None} + return {x:int(y) for x,y in groupdict.items() if y is not None} if self.allowIAccessibleChildIDAndChildCountForPositionInfo and self.IAccessibleChildID>0: indexInGroup=self.IAccessibleChildID parent=self.parent @@ -1503,7 +1505,7 @@ def _get_devInfo(self): info.append("IAccessible accName: %s" % ret) try: ret = iaObj.accRole(childID) - for name, const in oleacc.__dict__.iteritems(): + for name, const in oleacc.__dict__.items(): if not name.startswith("ROLE_"): continue if ret == const: @@ -1517,7 +1519,7 @@ def _get_devInfo(self): try: temp = iaObj.accState(childID) ret = ", ".join( - name for name, const in oleacc.__dict__.iteritems() + name for name, const in oleacc.__dict__.items() if name.startswith("STATE_") and temp & const ) + " (%d)" % temp except Exception as e: @@ -1546,7 +1548,7 @@ def _get_devInfo(self): info.append("IAccessible2 uniqueID: %s" % ret) try: ret = iaObj.role() - for name, const in itertools.chain(oleacc.__dict__.iteritems(), IAccessibleHandler.__dict__.iteritems()): + for name, const in itertools.chain(oleacc.__dict__.items(), IAccessibleHandler.__dict__.items()): if not name.startswith("ROLE_") and not name.startswith("IA2_ROLE_"): continue if ret == const: @@ -1560,7 +1562,7 @@ def _get_devInfo(self): try: temp = iaObj.states ret = ", ".join( - name for name, const in IAccessibleHandler.__dict__.iteritems() + name for name, const in IAccessibleHandler.__dict__.items() if name.startswith("IA2_STATE_") and temp & const ) + " (%d)" % temp except Exception as e: diff --git a/source/NVDAObjects/UIA/__init__.py b/source/NVDAObjects/UIA/__init__.py index 9073e402ca7..64c7982e197 100644 --- a/source/NVDAObjects/UIA/__init__.py +++ b/source/NVDAObjects/UIA/__init__.py @@ -1039,11 +1039,11 @@ def _get_devInfo(self): info.append("UIA className: %s"%ret) patternsAvailable = [] patternAvailableConsts = dict( - (const, name) for name, const in UIAHandler.__dict__.iteritems() + (const, name) for name, const in UIAHandler.__dict__.items() if name.startswith("UIA_Is") and name.endswith("PatternAvailablePropertyId") ) self._prefetchUIACacheForPropertyIDs(list(patternAvailableConsts)) - for const, name in patternAvailableConsts.iteritems(): + for const, name in patternAvailableConsts.items(): try: res = self._getUIACacheablePropertyValue(const) except COMError: diff --git a/source/NVDAObjects/__init__.py b/source/NVDAObjects/__init__.py index 74422175da8..10bd22334d0 100644 --- a/source/NVDAObjects/__init__.py +++ b/source/NVDAObjects/__init__.py @@ -1144,7 +1144,7 @@ def _get_devInfo(self): info.append("name: %s" % ret) try: ret = self.role - for name, const in controlTypes.__dict__.iteritems(): + for name, const in controlTypes.__dict__.items(): if name.startswith("ROLE_") and ret == const: ret = name break @@ -1152,7 +1152,7 @@ def _get_devInfo(self): ret = "exception: %s" % e info.append("role: %s" % ret) try: - stateConsts = dict((const, name) for name, const in controlTypes.__dict__.iteritems() if name.startswith("STATE_")) + stateConsts = dict((const, name) for name, const in controlTypes.__dict__.items() if name.startswith("STATE_")) ret = ", ".join( stateConsts.get(state) or str(state) for state in self.states) diff --git a/source/NVDAObjects/window/excel.py b/source/NVDAObjects/window/excel.py index f8d91ac828a..7b8ab4dc0bc 100755 --- a/source/NVDAObjects/window/excel.py +++ b/source/NVDAObjects/window/excel.py @@ -1335,7 +1335,7 @@ def _get_states(self): if not cellInfo: return states stateBits=cellInfo.states - for k,v in vars(controlTypes).iteritems(): + for k,v in vars(controlTypes).items(): if k.startswith('STATE_') and stateBits&v: states.add(v) return states diff --git a/source/NVDAObjects/window/excelCellBorder.py b/source/NVDAObjects/window/excelCellBorder.py index 4765e8b24ec..275c42308d4 100644 --- a/source/NVDAObjects/window/excelCellBorder.py +++ b/source/NVDAObjects/window/excelCellBorder.py @@ -107,7 +107,9 @@ def getCellBorderStyleDescription(bordersObj,reportBorderColor=False): d=OrderedDict() - for pos in bordersIndexLabels.keys(): + # #9067 (Py3 review required): originally called dict.keys. + # Therefore wrap this inside list call. + for pos in list(bordersIndexLabels.keys()): border=bordersObj[pos] if border.lineStyle != xlLineStyleNone: style=border.lineStyle @@ -150,7 +152,9 @@ def getCellBorderStyleDescription(bordersObj,reportBorderColor=False): s.append(_("{desc} up-right and down-right diagonal lines").format(desc=d.get(xlDiagonalUp))) del d[xlDiagonalUp] del d[xlDiagonalDown] - for pos,desc in d.items(): + # #9067 (Py3 review required): Originally called dict.items. + # Therefore wrap this inside a list call. + for pos,desc in list(d.items()): # Translators: border styles in Microsoft Excel. s.append(_("{desc} {position}").format( desc=desc, diff --git a/source/NVDAObjects/window/winword.py b/source/NVDAObjects/window/winword.py index 1293125ea24..baeebc47267 100755 --- a/source/NVDAObjects/window/winword.py +++ b/source/NVDAObjects/window/winword.py @@ -701,7 +701,8 @@ def getTextWithFields(self,formatConfig=None): startOffset=self._rangeObj.start endOffset=self._rangeObj.end text=BSTR() - formatConfigFlags=sum(y for x,y in formatConfigFlagsMap.iteritems() if formatConfig.get(x,False)) + # #9067: format config flags map is a dictionary. + formatConfigFlags=sum(y for x,y in formatConfigFlagsMap.items() if formatConfig.get(x,False)) if self.shouldIncludeLayoutTables: formatConfigFlags+=formatConfigFlag_includeLayoutTables if self.obj.ignoreEditorRevisions: diff --git a/source/UIAUtils.py b/source/UIAUtils.py index 7704b12aa2d..3aa5e7ddd28 100644 --- a/source/UIAUtils.py +++ b/source/UIAUtils.py @@ -19,7 +19,7 @@ def createUIAMultiPropertyCondition(*dicts): outerOrList=[] for dict in dicts: andList=[] - for key,values in dict.iteritems(): + for key,values in dict.items(): innerOrList=[] if not isinstance(values,(list,set)): values=[values] diff --git a/source/_UIAHandler.py b/source/_UIAHandler.py index 090fbeaf68e..f3aacc74d22 100644 --- a/source/_UIAHandler.py +++ b/source/_UIAHandler.py @@ -156,7 +156,7 @@ ignoreWinEventsMap = { UIA_AutomationPropertyChangedEventId: list(UIAPropertyIdsToNVDAEventNames.keys()), } -for id in UIAEventIdsToNVDAEventNames.iterkeys(): +for id in UIAEventIdsToNVDAEventNames.keys(): ignoreWinEventsMap[id] = [0] class UIAHandler(COMObject): @@ -198,7 +198,7 @@ def MTAThreadFunc(self): for index in xrange(pfm.count): e=pfm.getEntry(index) entryChanged = False - for eventId, propertyIds in ignoreWinEventsMap.iteritems(): + for eventId, propertyIds in ignoreWinEventsMap.items(): for propertyId in propertyIds: # Check if this proxy has mapped any winEvents to the UIA propertyChange event for this property ID try: @@ -246,8 +246,10 @@ def MTAThreadFunc(self): self.reservedNotSupportedValue=self.clientObject.ReservedNotSupportedValue self.ReservedMixedAttributeValue=self.clientObject.ReservedMixedAttributeValue self.clientObject.AddFocusChangedEventHandler(self.baseCacheRequest,self) - self.clientObject.AddPropertyChangedEventHandler(self.rootElement,TreeScope_Subtree,self.baseCacheRequest,self,UIAPropertyIdsToNVDAEventNames.keys()) - for x in UIAEventIdsToNVDAEventNames.iterkeys(): + # #9067 (Py3 review required): originally called dict.keys. + # Therefore wrap this inside a list call. + self.clientObject.AddPropertyChangedEventHandler(self.rootElement,TreeScope_Subtree,self.baseCacheRequest,self,list(UIAPropertyIdsToNVDAEventNames.keys())) + for x in UIAEventIdsToNVDAEventNames.keys(): self.clientObject.addAutomationEventHandler(x,self.rootElement,TreeScope_Subtree,self.baseCacheRequest,self) # #7984: add support for notification event (IUIAutomation5, part of Windows 10 build 16299 and later). if isinstance(self.clientObject, IUIAutomation5): diff --git a/source/addonHandler/__init__.py b/source/addonHandler/__init__.py index 7dd532acd0c..836275810bf 100644 --- a/source/addonHandler/__init__.py +++ b/source/addonHandler/__init__.py @@ -223,7 +223,7 @@ def getAvailableAddons(refresh=False, filterFunc=None): generators = [_getAvailableAddonsFromPath(path) for path in _getDefaultAddonPaths()] for addon in itertools.chain(*generators): _availableAddons[addon.path] = addon - return (addon for addon in _availableAddons.itervalues() if not filterFunc or filterFunc(addon)) + return (addon for addon in _availableAddons.values() if not filterFunc or filterFunc(addon)) def installAddonBundle(bundle): """Extracts an Addon bundle in to a unique subdirectory of the user addons directory, marking the addon as needing install completion on NVDA restart.""" @@ -513,7 +513,9 @@ def getCodeAddon(obj=None, frameDist=1): raise AddonError("Code does not belong to an addon package.") curdir = dir while curdir not in _getDefaultAddonPaths(): - if curdir in _availableAddons.keys(): + # #9067 (Py3 review required): originally called dict.keys. + # Therefore wrap this inside a list call. + if curdir in list(_availableAddons.keys()): return _availableAddons[curdir] curdir = os.path.abspath(os.path.join(curdir, "..")) # Not found! diff --git a/source/appModuleHandler.py b/source/appModuleHandler.py index 52e1afdb7d3..7a973e565a9 100644 --- a/source/appModuleHandler.py +++ b/source/appModuleHandler.py @@ -140,7 +140,7 @@ def update(processID,helperLocalBindingHandle=None,inprocRegistrationHandle=None def cleanup(): """Removes any appModules from the cache whose process has died. """ - for deadMod in [mod for mod in runningTable.itervalues() if not mod.isAlive]: + for deadMod in [mod for mod in runningTable.values() if not mod.isAlive]: log.debug("application %s closed"%deadMod.appName) del runningTable[deadMod.processID] if deadMod in set(o.appModule for o in api.getFocusAncestors()+[api.getFocusObject()] if o and o.appModule): @@ -189,7 +189,7 @@ def reloadAppModules(): """ global appModules state = [] - for mod in runningTable.itervalues(): + for mod in runningTable.values(): state.append({key: getattr(mod, key) for key in ("processID", # #2892: We must save nvdaHelperRemote handles, as we can't reinitialize without a foreground/focus event. # Also, if there is an active context handle such as a loaded buffer, @@ -203,7 +203,7 @@ def reloadAppModules(): mod._helperPreventDisconnect = True terminate() del appModules - mods=[k for k,v in sys.modules.iteritems() if k.startswith("appModules") and v is not None] + mods=[k for k,v in sys.modules.items() if k.startswith("appModules") and v is not None] for mod in mods: del sys.modules[mod] import appModules @@ -232,7 +232,7 @@ def initialize(): _importers=list(pkgutil.iter_importers("appModules.__init__")) def terminate(): - for processID, app in runningTable.iteritems(): + for processID, app in runningTable.items(): try: app.terminate() except: diff --git a/source/baseObject.py b/source/baseObject.py index 3f04cdc93e0..3b338f73742 100755 --- a/source/baseObject.py +++ b/source/baseObject.py @@ -157,7 +157,8 @@ def invalidateCaches(cls): """ # We use keys() here instead of iterkeys(), as invalidating the cache on an object may cause instances to disappear, # which would in turn cause an exception due to the dictionary changing size during iteration. - for instance in cls.__instances.keys(): + # #9067 (Py3 review required): because of this, wrap this in a list, as dict.keys() in Python 3 returns iterators. + for instance in list(cls.__instances.keys()): instance.invalidateCache() class ScriptableType(AutoPropertyType): @@ -173,8 +174,7 @@ def __new__(meta, name, bases, dict): # This class currently has no gestures dictionary, # because no custom __gestures dictionary has been defined. gestures = {} - # Python 3 incompatible. - for name, script in dict.iteritems(): + for name, script in dict.items(): if not name.startswith('script_'): continue scriptName = name[len("script_"):] @@ -261,7 +261,7 @@ def bindGestures(self, gestureMap): @param gestureMap: A mapping of gesture identifiers to script names. @type gestureMap: dict of str to str """ - for gestureIdentifier, scriptName in gestureMap.iteritems(): + for gestureIdentifier, scriptName in gestureMap.items(): if scriptName: try: self.bindGesture(gestureIdentifier, scriptName) diff --git a/source/bdDetect.py b/source/bdDetect.py index 42b09a6e128..9247383f4d9 100644 --- a/source/bdDetect.py +++ b/source/bdDetect.py @@ -118,8 +118,8 @@ def getDriversForConnectedUsbDevices(): for port in deviceInfoFetcher.comPorts if "usbID" in port) ) for match in usbDevs: - for driver, devs in _driverDevices.iteritems(): - for type, ids in devs.iteritems(): + for driver, devs in _driverDevices.items(): + for type, ids in devs.items(): if match.type==type and match.id in ids: yield driver, match @@ -136,7 +136,7 @@ def getDriversForPossibleBluetoothDevices(): for port in deviceInfoFetcher.hidDevices if port["provider"]=="bluetooth"), ) for match in btDevs: - for driver, devs in _driverDevices.iteritems(): + for driver, devs in _driverDevices.items(): matchFunc = devs[KEY_BLUETOOTH] if not callable(matchFunc): continue @@ -334,7 +334,7 @@ def getConnectedUsbDevicesForDriver(driver): for port in deviceInfoFetcher.comPorts if "usbID" in port) ) for match in usbDevs: - for type, ids in devs.iteritems(): + for type, ids in devs.items(): if match.type==type and match.id in ids: yield match diff --git a/source/brailleDisplayDrivers/baum.py b/source/brailleDisplayDrivers/baum.py index 6b2a332cf7c..53c10e05899 100644 --- a/source/brailleDisplayDrivers/baum.py +++ b/source/brailleDisplayDrivers/baum.py @@ -231,7 +231,7 @@ def __init__(self, model, keysDown): self.keysDown = dict(keysDown) self.keyNames = names = [] - for group, groupKeysDown in keysDown.iteritems(): + for group, groupKeysDown in keysDown.items(): if group == BAUM_BRAILLE_KEYS and len(keysDown) == 1 and not groupKeysDown & 0xfc: # This is braille input. # 0xfc covers command keys. The space bars are covered by 0x3. diff --git a/source/brailleDisplayDrivers/brltty.py b/source/brailleDisplayDrivers/brltty.py index 777cf2737f1..2e54fd8c137 100644 --- a/source/brailleDisplayDrivers/brltty.py +++ b/source/brailleDisplayDrivers/brltty.py @@ -12,7 +12,7 @@ try: import brlapi BRLAPI_CMD_KEYS = dict((code, name[8:].lower()) - for name, code in brlapi.__dict__.iteritems() if name.startswith("KEY_CMD_")) + for name, code in brlapi.__dict__.items() if name.startswith("KEY_CMD_")) except ImportError: pass diff --git a/source/brailleDisplayDrivers/eurobraille.py b/source/brailleDisplayDrivers/eurobraille.py index 1081da47e4a..c8488daa07f 100644 --- a/source/brailleDisplayDrivers/eurobraille.py +++ b/source/brailleDisplayDrivers/eurobraille.py @@ -549,9 +549,9 @@ def __init__(self, display): self.model = display.deviceType.lower().split(" ")[0] keysDown = dict(display.keysDown) self.keyNames = names = [] - for group, groupKeysDown in keysDown.iteritems(): + for group, groupKeysDown in keysDown.items(): if group == EB_KEY_BRAILLE: - if sum(keysDown.itervalues())==groupKeysDown and not groupKeysDown & 0x100: + if sum(keysDown.values())==groupKeysDown and not groupKeysDown & 0x100: # This is braille input. # 0x1000 is backspace, 0x2000 is space self.dots = groupKeysDown & 0xff @@ -565,7 +565,7 @@ def __init__(self, display): self.routingIndex = (groupKeysDown & 0xff)-1 names.append("doubleRouting" if groupKeysDown>>8 ==ord(EB_KEY_INTERACTIVE_DOUBLE_CLICK) else "routing") if group == EB_KEY_COMMAND: - for key, keyName in display.keys.iteritems(): + for key, keyName in display.keys.items(): if groupKeysDown & key: # This key is pressed names.append(keyName) diff --git a/source/brailleTables.py b/source/brailleTables.py index 560e4b270ad..51fbc79ecb5 100644 --- a/source/brailleTables.py +++ b/source/brailleTables.py @@ -56,7 +56,9 @@ def listTables(): @return: A list of braille tables. @rtype: list of L{BrailleTable} """ - tables = _tables.values() + # #9067 (Py3 review required): originally called dict.values. + # Therefore wrap this inside a list call. + tables = list(_tables.values()) tables.sort(key=lambda table: table.displayName) return tables diff --git a/source/characterProcessing.py b/source/characterProcessing.py index d8c830a1b85..b10d21d2572 100644 --- a/source/characterProcessing.py +++ b/source/characterProcessing.py @@ -252,7 +252,7 @@ def _loadSymbolField(self, input, inputMap=None): "#": "#", "\\": "\\", } - IDENTIFIER_ESCAPES_OUTPUT = {v: k for k, v in IDENTIFIER_ESCAPES_INPUT.iteritems()} + IDENTIFIER_ESCAPES_OUTPUT = {v: k for k, v in IDENTIFIER_ESCAPES_INPUT.items()} LEVEL_INPUT = { "none": SYMLVL_NONE, "some": SYMLVL_SOME, @@ -260,13 +260,13 @@ def _loadSymbolField(self, input, inputMap=None): "all": SYMLVL_ALL, "char": SYMLVL_CHAR, } - LEVEL_OUTPUT = {v:k for k, v in LEVEL_INPUT.iteritems()} + LEVEL_OUTPUT = {v:k for k, v in LEVEL_INPUT.items()} PRESERVE_INPUT = { "never": SYMPRES_NEVER, "always": SYMPRES_ALWAYS, "norep": SYMPRES_NOREP, } - PRESERVE_OUTPUT = {v: k for k, v in PRESERVE_INPUT.iteritems()} + PRESERVE_OUTPUT = {v: k for k, v in PRESERVE_INPUT.items()} def _loadSymbol(self, line): line = line.split("\t") @@ -315,13 +315,13 @@ def save(self, fileName=None): with codecs.open(fileName, "w", "utf_8_sig", errors="replace") as f: if self.complexSymbols: f.write(u"complexSymbols:\r\n") - for identifier, pattern in self.complexSymbols.iteritems(): + for identifier, pattern in self.complexSymbols.items(): f.write(u"%s\t%s\r\n" % (identifier, pattern)) f.write(u"\r\n") if self.symbols: f.write(u"symbols:\r\n") - for symbol in self.symbols.itervalues(): + for symbol in self.symbols.values(): f.write(u"%s\r\n" % self._saveSymbol(symbol)) def _saveSymbolField(self, output, outputMap=None): @@ -429,7 +429,7 @@ def __init__(self, locale): # Add all complex symbols first, as they take priority. for source in sources: - for identifier, pattern in source.complexSymbols.iteritems(): + for identifier, pattern in source.complexSymbols.items(): if identifier in symbols: # Already defined. continue @@ -439,7 +439,7 @@ def __init__(self, locale): # Supplement the data for complex symbols and add all simple symbols. for source in sources: - for identifier, sourceSymbol in source.symbols.iteritems(): + for identifier, sourceSymbol in source.symbols.items(): try: symbol = symbols[identifier] # We're updating an already existing symbol. @@ -462,7 +462,9 @@ def __init__(self, locale): symbol.displayName = sourceSymbol.displayName # Set defaults for any fields not explicitly set. - for symbol in symbols.values(): + # #9067 (Py3 review required): originally called dict.values. + # Therefore wrap this inside a list call. + for symbol in list(symbols.values()): if symbol.replacement is None: # Symbols without a replacement specified are useless. log.warning(u"Replacement not defined in locale {locale} for symbol: {symbol}".format( diff --git a/source/config/__init__.py b/source/config/__init__.py index e3ee3dd6441..2b285567605 100644 --- a/source/config/__init__.py +++ b/source/config/__init__.py @@ -617,7 +617,7 @@ def deleteProfile(self, name): # Remove any triggers associated with this profile. allTriggers = self.triggersToProfiles # You can't delete from a dict while iterating through it. - delTrigs = [trigSpec for trigSpec, trigProfile in allTriggers.iteritems() + delTrigs = [trigSpec for trigSpec, trigProfile in allTriggers.items() if trigProfile == name] if delTrigs: for trigSpec in delTrigs: @@ -636,7 +636,9 @@ def deleteProfile(self, name): self._handleProfileSwitch() if self._suspendedTriggers: # Remove any suspended triggers referring to this profile. - for trigger in self._suspendedTriggers.keys(): + # #9067 (Py3 review required): originally called dict.keys (note that triggers is a dictionary). + # Therefore wrap this inside a list call unless it can be simplified further. + for trigger in list(self._suspendedTriggers.keys()): if trigger._profile == delProfile: del self._suspendedTriggers[trigger] @@ -666,7 +668,7 @@ def renameProfile(self, oldName, newName): # Update any associated triggers. allTriggers = self.triggersToProfiles saveTrigs = False - for trigSpec, trigProfile in allTriggers.iteritems(): + for trigSpec, trigProfile in allTriggers.items(): if trigProfile == oldName: allTriggers[trigSpec] = newName saveTrigs = True @@ -780,7 +782,7 @@ def resumeProfileTriggers(self): triggers = self._suspendedTriggers self._suspendedTriggers = None with self.atomicProfileSwitch(): - for trigger, action in triggers.iteritems(): + for trigger, action in triggers.items(): trigger.enter() if action == "enter" else trigger.exit() def disableProfileTriggers(self): @@ -989,7 +991,7 @@ def _cacheLeaf(self, key, spec, val): def __iter__(self): keys = set() # Start with the cached items. - for key, val in self._cache.iteritems(): + for key, val in self._cache.items(): keys.add(key) if val is not KeyError: yield key diff --git a/source/config/profileUpgrader.py b/source/config/profileUpgrader.py index e138fdabfec..f53c8abca1c 100644 --- a/source/config/profileUpgrader.py +++ b/source/config/profileUpgrader.py @@ -66,7 +66,9 @@ def _doValidation(profile, validator): raise ValueError(errorString) def _ensureVersionProperty(profile): - isEmptyProfile = 1 > len(profile.keys()) + # #9067 (Py3 review required): profile is a subclass of dictionary. + # Therefore wrap this inside a list call. + isEmptyProfile = 1 > len(list(profile.keys())) if isEmptyProfile: log.debug("Empty profile, triggering default schema version") profile[SCHEMA_VERSION_KEY] = latestSchemaVersion diff --git a/source/extensionPoints/util.py b/source/extensionPoints/util.py index 684036192d0..b3bfda11287 100644 --- a/source/extensionPoints/util.py +++ b/source/extensionPoints/util.py @@ -109,7 +109,9 @@ def handlers(self): """Generator of registered handler functions. This should be used when you want to call the handlers. """ - for weak in self._handlers.values(): + # #9067 (py3 review required): handlers is an ordered dictionary. + # Therefore wrap this inside a list call. + for weak in list(self._handlers.values()): handler = weak() if not handler: continue # Died. @@ -166,6 +168,7 @@ def callWithSupportedKwargs(func, *args, **kwargs): if not spec.defaults or numExpectedArgsWithDefaults != numExpectedArgs: # get the names of the args without defaults, skipping the N positional args given to `callWithSupportedKwargs` # positionals are required for the Filter extension point. + # #9067 (Py3 review required): Set construction will work with iterators, too. givenKwargsKeys = set(kwargs.keys()) firstArgWithDefault = numExpectedArgs - numExpectedArgsWithDefaults specArgs = set(spec.args[numGivenPositionalArgs:firstArgWithDefault]) @@ -179,7 +182,9 @@ def callWithSupportedKwargs(func, *args, **kwargs): return func(*args, **kwargs) supportedKwargs = set(spec.args) - for kwarg in kwargs.keys(): + # #9067 (Py3 review required): originally called dict.keys. + # Therefore wrap this inside a list call. + for kwarg in list(kwargs.keys()): if kwarg not in supportedKwargs: del kwargs[kwarg] return func(*args, **kwargs) \ No newline at end of file diff --git a/source/globalPluginHandler.py b/source/globalPluginHandler.py index a50cdb76bcc..7c6d7df48f0 100644 --- a/source/globalPluginHandler.py +++ b/source/globalPluginHandler.py @@ -47,7 +47,7 @@ def reloadGlobalPlugins(): global globalPlugins terminate() del globalPlugins - mods=[k for k,v in sys.modules.iteritems() if k.startswith("globalPlugins") and v is not None] + mods=[k for k,v in sys.modules.items() if k.startswith("globalPlugins") and v is not None] for mod in mods: del sys.modules[mod] import globalPlugins diff --git a/source/gui/__init__.py b/source/gui/__init__.py index fed017ddd62..e7fe38950ab 100644 --- a/source/gui/__init__.py +++ b/source/gui/__init__.py @@ -553,7 +553,7 @@ def initialize(): wx.GetApp().SetTopWindow(mainFrame) def terminate(): - for instance, state in gui.SettingsDialog._instances.iteritems(): + for instance, state in gui.SettingsDialog._instances.items(): if state is gui.SettingsDialog._DIALOG_DESTROYED_STATE: log.error( "Destroyed but not deleted instance of settings dialog exists: {!r}".format(instance) diff --git a/source/gui/configProfiles.py b/source/gui/configProfiles.py index 7a6a40c93bd..dc395283e04 100644 --- a/source/gui/configProfiles.py +++ b/source/gui/configProfiles.py @@ -300,7 +300,7 @@ def __init__(self, parent): triggers.append(TriggerInfo(spec, disp, profile)) processed.add(spec) # Handle all other triggers. - for spec, profile in confTrigs.iteritems(): + for spec, profile in confTrigs.items(): if spec in processed: continue if spec.startswith("app:"): diff --git a/source/gui/settingsDialogs.py b/source/gui/settingsDialogs.py index 15eda0f7d4e..b69aaedd6e7 100644 --- a/source/gui/settingsDialogs.py +++ b/source/gui/settingsDialogs.py @@ -76,7 +76,9 @@ class MultiInstanceError(RuntimeError): pass shouldSuspendConfigProfileTriggers = True def __new__(cls, *args, **kwargs): - instanceItems = SettingsDialog._instances.items() + # #9067 (Py3 review required): originally calls WeakKeyDictionary.items. + # Therefore wrap this inside a list call. + instanceItems = list(SettingsDialog._instances.items()) instancesOfSameClass = ( (dlg, state) for dlg, state in instanceItems if isinstance(dlg, cls) ) @@ -589,12 +591,13 @@ def onCategoryChange(self, evt): evt.Skip() def _doSave(self): - for panel in self.catIdToInstanceMap.itervalues(): + # #9067 (Py3 review required): category instance map is a dictionary. + for panel in self.catIdToInstanceMap.values(): if panel.isValid() is False: raise ValueError("Validation for %s blocked saving settings" % panel.__class__.__name__) - for panel in self.catIdToInstanceMap.itervalues(): + for panel in self.catIdToInstanceMap.values(): panel.onSave() - for panel in self.catIdToInstanceMap.itervalues(): + for panel in self.catIdToInstanceMap.values(): panel.postSave() def onOk(self,evt): @@ -603,12 +606,12 @@ def onOk(self,evt): except ValueError: log.debugWarning("", exc_info=True) return - for panel in self.catIdToInstanceMap.itervalues(): + for panel in self.catIdToInstanceMap.values(): panel.Destroy() super(MultiCategorySettingsDialog,self).onOk(evt) def onCancel(self,evt): - for panel in self.catIdToInstanceMap.itervalues(): + for panel in self.catIdToInstanceMap.values(): panel.onDiscard() panel.Destroy() super(MultiCategorySettingsDialog,self).onCancel(evt) @@ -1071,7 +1074,9 @@ def makeStringSettingControl(self,setting): setattr( self, "_%ss"%setting.id, - getattr(self.driver,"available%ss"%setting.id.capitalize()).values() + # #9067 (Py3 review required): settings are stored as an ordered dict. + # Therefore wrap this inside a list call. + list(getattr(self.driver,"available%ss"%setting.id.capitalize()).values()) ) l=getattr(self,"_%ss"%setting.id) labeledControl=guiHelper.LabeledControlHelper( @@ -1109,7 +1114,8 @@ def makeBooleanSettingControl(self,setting): def updateDriverSettings(self, changedSetting=None): """Creates, hides or updates existing GUI controls for all of supported settings.""" #firstly check already created options - for name,sizer in self.sizerDict.iteritems(): + # #9067 (Py3 review required): sizerDict is a dictionary. + for name,sizer in self.sizerDict.items(): if name == changedSetting: # Changing a setting shouldn't cause that setting itself to disappear. continue @@ -2324,7 +2330,8 @@ def setType(self, type): self.typeRadioBox.SetSelection(DictionaryEntryDialog.TYPE_LABELS_ORDERING.index(type)) class DictionaryDialog(SettingsDialog): - TYPE_LABELS = {t: l.replace("&", "") for t, l in DictionaryEntryDialog.TYPE_LABELS.iteritems()} + # #9067 (py3 review required): type_labels is a dictionary of type/labels map. + TYPE_LABELS = {t: l.replace("&", "") for t, l in DictionaryEntryDialog.TYPE_LABELS.items()} def __init__(self,parent,title,speechDict): self.title = title @@ -2559,7 +2566,8 @@ def updatePossiblePorts(self): if displayName != "auto": displayCls = braille._getDisplayDriver(displayName) try: - self.possiblePorts.extend(displayCls.getPossiblePorts().iteritems()) + # #9067 (Py3 review required): getPossiblePorts returns an ordered dictionary. + self.possiblePorts.extend(displayCls.getPossiblePorts().items()) except NotImplementedError: pass if self.possiblePorts: @@ -2886,7 +2894,8 @@ def __init__(self,parent): def makeSettings(self, settingsSizer): self.filteredSymbols = self.symbols = [ - copy.copy(symbol) for symbol in self.symbolProcessor.computedSymbols.itervalues() + # #9067 (Py3 review required): locale data factory/data map is a dictionary. + copy.copy(symbol) for symbol in self.symbolProcessor.computedSymbols.values() ] self.pendingRemovals = {} @@ -3132,7 +3141,8 @@ def OnRemoveClick(self, evt): def onOk(self, evt): self.onSymbolEdited() self.editingItem = None - for symbol in self.pendingRemovals.itervalues(): + # #9067 (Py3 review required): pending removals is a dictionary. + for symbol in self.pendingRemovals.values(): self.symbolProcessor.deleteSymbol(symbol) for symbol in self.symbols: if not symbol.replacement: diff --git a/source/inputCore.py b/source/inputCore.py index b6cd974fdb3..602da3ef970 100644 --- a/source/inputCore.py +++ b/source/inputCore.py @@ -268,14 +268,14 @@ def update(self, entries): @type entries: mapping of str to mapping """ self.lastUpdateContainedError = False - for locationName, location in entries.iteritems(): + for locationName, location in entries.items(): try: module, className = locationName.rsplit(".", 1) except: log.error("Invalid module/class specification: %s" % locationName) self.lastUpdateContainedError = True continue - for script, gestures in location.iteritems(): + for script, gestures in location.items(): if script == "None": script = None if gestures == "": @@ -353,7 +353,7 @@ def save(self): out = configobj.ConfigObj(encoding="UTF-8") out.filename = self.fileName - for gesture, scripts in self._map.iteritems(): + for gesture, scripts in self._map.items(): for module, className, script in scripts: key = "%s.%s" % (module, className) try: @@ -661,7 +661,7 @@ def getScriptCategory(self, cls, script): def addObj(self, obj, isAncestor=False): scripts = {} for cls in obj.__class__.__mro__: - for scriptName, script in cls.__dict__.iteritems(): + for scriptName, script in cls.__dict__.items(): if not scriptName.startswith("script_"): continue if isAncestor and not getattr(script, "canPropagate", False): @@ -675,7 +675,7 @@ def addObj(self, obj, isAncestor=False): continue self.addResult(scriptInfo) scripts[script] = scriptInfo - for gesture, script in obj._gestureMap.iteritems(): + for gesture, script in obj._gestureMap.items(): try: scriptInfo = scripts[script.__func__] except KeyError: diff --git a/source/installer.py b/source/installer.py index 9662e9daa98..517bcd657db 100644 --- a/source/installer.py +++ b/source/installer.py @@ -216,7 +216,7 @@ def removeOldProgramFiles(destPath): def registerInstallation(installDir,startMenuFolder,shouldCreateDesktopShortcut,startOnLogonScreen,configInLocalAppData=False): with winreg.CreateKeyEx(winreg.HKEY_LOCAL_MACHINE,"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\NVDA",0,winreg.KEY_WRITE) as k: - for name,value in uninstallerRegInfo.iteritems(): + for name,value in uninstallerRegInfo.items(): winreg.SetValueEx(k,name,None,winreg.REG_SZ,value.format(installDir=installDir)) with winreg.CreateKeyEx(winreg.HKEY_LOCAL_MACHINE,"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\nvda.exe",0,winreg.KEY_WRITE) as k: winreg.SetValueEx(k,"",None,winreg.REG_SZ,os.path.join(installDir,"nvda.exe")) diff --git a/source/oleacc.py b/source/oleacc.py index 959d5e649f5..d97ec999dbf 100644 --- a/source/oleacc.py +++ b/source/oleacc.py @@ -8,7 +8,7 @@ import winUser # Include functions from oleacc.dll in the module namespace. m=comtypes.client.GetModule('oleacc.dll') -globals().update((key, val) for key, val in m.__dict__.iteritems() if not key.startswith("_")) +globals().update((key, val) for key, val in m.__dict__.items() if not key.startswith("_")) NAVDIR_MIN=0 NAVDIR_UP=1 diff --git a/source/queueHandler.py b/source/queueHandler.py index b8a9533b000..28616bb802c 100644 --- a/source/queueHandler.py +++ b/source/queueHandler.py @@ -63,7 +63,8 @@ def isPendingItems(queue): def pumpAll(): # This dict can mutate during iteration, so use keys(). - for ID in generators.keys(): + # #9067 (Py3 review required): due to this, wrap this with a list call. + for ID in list(generators.keys()): # KeyError could occur within the generator itself, so retrieve the generator first. try: gen = generators[ID] diff --git a/source/speech/__init__.py b/source/speech/__init__.py index 393ed64a5af..a3b17a38b03 100755 --- a/source/speech/__init__.py +++ b/source/speech/__init__.py @@ -230,7 +230,8 @@ def speakObjectProperties(obj, reason=controlTypes.REASON_QUERY, priority=None, #Fetch the values for all wanted properties newPropertyValues={} positionInfo=None - for name,value in allowedProperties.iteritems(): + # #9067 (Py3 review required): allowed properties is a keyword dictionary. + for name,value in allowedProperties.items(): if name=="includeTableCellCoords": # This is verbosity info. newPropertyValues[name]=value @@ -1634,7 +1635,8 @@ def getFormatFieldSpeech(attrs,attrsCache=None,formatConfig=None,reason=None,uni _("no first line indent"), ), } - for attr,(label,noVal) in indentLabels.iteritems(): + # #9067 (Py3 review required): see above for definition of indent labels. + for attr,(label,noVal) in indentLabels.items(): newVal=attrs.get(attr) oldVal=attrsCache.get(attr) if attrsCache else None if (newVal or oldVal is not None) and newVal!=oldVal: diff --git a/source/speech/manager.py b/source/speech/manager.py index 685117ab1f0..0612a4be06c 100644 --- a/source/speech/manager.py +++ b/source/speech/manager.py @@ -39,7 +39,9 @@ def getChanged(self): @return: List of parameter change commands. @type: list of L{SynthParamCommand} """ - return self._commands.values() + # #9067 (Py3 review required): commands is a dictionary and will be consulted when speaking speech sequences. + # Therefore wrap this inside a list call. + return list(self._commands.values()) class _ManagerPriorityQueue(object): """A speech queue for a specific priority. diff --git a/source/speechDictHandler/dictFormatUpgrade.py b/source/speechDictHandler/dictFormatUpgrade.py index 6775fc18fcd..707b6f48045 100644 --- a/source/speechDictHandler/dictFormatUpgrade.py +++ b/source/speechDictHandler/dictFormatUpgrade.py @@ -103,7 +103,9 @@ def _doSynthVoiceDictBackupAndMove(synthName, oldFileNameToNewFileNameList=None) def _doEspeakDictUpgrade(): synthName = "espeak" def getNextVoice(): - for ID, oldNewTuple in espeakNameChanges.items(): + # #9067 (Py3 review required): originally called dict.items. + # Therefore wrap this inside a list call. + for ID, oldNewTuple in list(espeakNameChanges.items()): oldName = oldNewTuple[0] newName = oldNewTuple[1] yield ( diff --git a/source/speechXml.py b/source/speechXml.py index 87503d21c4f..3453d0bee12 100644 --- a/source/speechXml.py +++ b/source/speechXml.py @@ -110,7 +110,7 @@ def _text(self, text): def _openTag(self, tag, attrs, empty=False): self._out.append("<%s" % tag) - for attr, val in attrs.iteritems(): + for attr, val in attrs.items(): self._out.append(' %s="' % attr) self._out.append(_escapeXml(val)) self._out.append('"') @@ -145,7 +145,7 @@ def _outputTags(self): for tag in reversed(self._openTags): self._closeTag(tag) del self._openTags[:] - for tag, attrs in self._tags.iteritems(): + for tag, attrs in self._tags.items(): self._openTag(tag, attrs) self._openTags.append(tag) self._tagsChanged = False diff --git a/source/synthDrivers/espeak.py b/source/synthDrivers/espeak.py index d4019f01851..6ac4072e08d 100644 --- a/source/synthDrivers/espeak.py +++ b/source/synthDrivers/espeak.py @@ -120,7 +120,7 @@ def speak(self,speechSequence): if not prosody: continue textList.append("") elif isinstance(item,speech.PhonemeCommand): @@ -249,4 +249,4 @@ def _set_variant(self,val): _espeak.setVoiceAndVariant(variant=self._variant) def _getAvailableVariants(self): - return OrderedDict((ID,VoiceInfo(ID, name)) for ID, name in self._variantDict.iteritems()) + return OrderedDict((ID,VoiceInfo(ID, name)) for ID, name in self._variantDict.items()) diff --git a/source/synthDrivers/oneCore.py b/source/synthDrivers/oneCore.py index ba3d38ce8cd..24a2fd0260d 100644 --- a/source/synthDrivers/oneCore.py +++ b/source/synthDrivers/oneCore.py @@ -431,7 +431,8 @@ def _get_voice(self): def _set_voice(self, id): voices = self.availableVoices # Try setting the requested voice - for voice in voices.itervalues(): + # #9067 (Py3 review required): voices is an ordered dictionary. + for voice in voices.values(): if voice.id == id: self._dll.ocSpeech_setVoice(self._handle, voice.onecoreIndex) return @@ -449,16 +450,16 @@ def _getDefaultVoice(self): voices = self.availableVoices # Try matching to NVDA language fullLanguage=languageHandler.getWindowsLanguage() - for voice in voices.itervalues(): + for voice in voices.values(): if voice.language==fullLanguage: return voice.id baseLanguage=fullLanguage.split('_')[0] if baseLanguage!=fullLanguage: - for voice in voices.itervalues(): + for voice in voices.values(): if voice.language.startswith(baseLanguage): return voice.id # Just use the first available - for voice in voices.itervalues(): + for voice in voices.values(): return voice.id raise RuntimeError("No voices available") diff --git a/source/synthDrivers/sapi5.py b/source/synthDrivers/sapi5.py index c5abc1e0c91..0e40ed61c11 100644 --- a/source/synthDrivers/sapi5.py +++ b/source/synthDrivers/sapi5.py @@ -272,9 +272,9 @@ def outputTags(): for tag in reversed(openedTags): textList.append("" % tag) del openedTags[:] - for tag, attrs in tags.iteritems(): + for tag, attrs in tags.items(): textList.append("<%s" % tag) - for attr, val in attrs.iteritems(): + for attr, val in attrs.items(): textList.append(' %s="%s"' % (attr, val)) textList.append(">") openedTags.append(tag) diff --git a/source/synthSettingsRing.py b/source/synthSettingsRing.py index 5b1d7c735bf..7ed72c4884d 100644 --- a/source/synthSettingsRing.py +++ b/source/synthSettingsRing.py @@ -38,7 +38,9 @@ def _get_reportValue(self): class StringSynthSetting(SynthSetting): def __init__(self,synth,setting): - self._values=getattr(synth,"available%ss"%setting.id.capitalize()).values() + # #9067 (Py3 review required): pulls settings from a dictionary. + # Therefore wrap this inside a list call. + self._values=list(getattr(synth,"available%ss"%setting.id.capitalize()).values()) super(StringSynthSetting,self).__init__(synth,setting,0,len(self._values)-1) def _get_value(self): diff --git a/source/tableUtils.py b/source/tableUtils.py index 145b43de154..179e35e1ddc 100644 --- a/source/tableUtils.py +++ b/source/tableUtils.py @@ -8,7 +8,7 @@ class HeaderCellInfo(object): def __init__(self,**kwargs): self.rowSpan=self.colSpan=1 self.minColumnNumber=self.maxColumnNumber=self.minRowNumber=self.maxRowNumber=None - for name,value in kwargs.iteritems(): + for name,value in kwargs.items(): setattr(self,name,value) class HeaderCellTracker(object): diff --git a/source/textInfos/offsets.py b/source/textInfos/offsets.py index 7b7b319c2e6..5257476156a 100755 --- a/source/textInfos/offsets.py +++ b/source/textInfos/offsets.py @@ -396,7 +396,7 @@ def __init__(self,obj,position): # This is a direct TextInfo to TextInfo copy. # Copy over the contents of the property cache, and any private instance variables (includes the TextInfo's offsets) self._propertyCache.update(position._propertyCache) - self.__dict__.update({x:y for x,y in position.__dict__.iteritems() if x.startswith('_') and x!='_propertyCache'}) + self.__dict__.update({x:y for x,y in position.__dict__.items() if x.startswith('_') and x!='_propertyCache'}) elif position==textInfos.POSITION_FIRST: self._startOffset=self._endOffset=0 elif position==textInfos.POSITION_LAST: diff --git a/source/touchTracker.py b/source/touchTracker.py index bd92d6268b5..a5a189e8850 100644 --- a/source/touchTracker.py +++ b/source/touchTracker.py @@ -207,7 +207,7 @@ def makePreheldTrackerFromSingleTouchTrackers(self,trackers): return tracker def makePreheldTrackerForTracker(self,tracker): - curHoverSet={x for x in self.singleTouchTrackersByID.itervalues() if x.action==action_hover} + curHoverSet={x for x in self.singleTouchTrackersByID.values() if x.action==action_hover} excludeHoverSet={x for x in tracker.iterAllRawSingleTouchTrackers() if x.action==action_hover} return self.makePreheldTrackerFromSingleTouchTrackers(curHoverSet-excludeHoverSet) @@ -333,7 +333,7 @@ def emitTrackers(self): # yield hover downs for any new hovers # But only once there are no more trackers in the queue waiting to timeout (E.g. a hold for a tapAndHold) if len(self.multiTouchTrackers)==0: - for singleTouchTracker in self.singleTouchTrackersByID.itervalues(): + for singleTouchTracker in self.singleTouchTrackersByID.values(): if singleTouchTracker.action==action_hover and singleTouchTracker not in self.curHoverStack: self.curHoverStack.append(singleTouchTracker) tracker=MultiTouchTracker(action_hoverDown,singleTouchTracker.x,singleTouchTracker.y,singleTouchTracker.startTime,time.time()) diff --git a/source/vkCodes.py b/source/vkCodes.py index e35f2fb325e..4ef4439b12c 100755 --- a/source/vkCodes.py +++ b/source/vkCodes.py @@ -138,7 +138,7 @@ #: This is the inverse of the L{byCode} map #: except that names are all lower case to make case insensitive lookup easier. #: @type: dict with keys of str and values of tuple(int, bool) -byName = dict((name.lower(), code) for code, name in byCode.iteritems()) +byName = dict((name.lower(), code) for code, name in byCode.items()) # Used by SendInput for non-keyboard input to pass Unicode characters as if they were keystrokes. # The scan code is the Unicode character. diff --git a/source/watchdog.py b/source/watchdog.py index 117d28ca56c..2fd5e639307 100644 --- a/source/watchdog.py +++ b/source/watchdog.py @@ -175,7 +175,7 @@ def _crashHandler(exceptionInfo): log.critical("NVDA crashed! Minidump written to %s" % dumpPath) # Log Python stacks for every thread. - for logThread, logFrame in sys._current_frames().iteritems(): + for logThread, logFrame in sys._current_frames().items(): log.info("Python stack for thread %d" % logThread, stack_info=traceback.extract_stack(logFrame))