diff --git a/build/compare-mozconfig/compare-mozconfigs.py b/build/compare-mozconfig/compare-mozconfigs.py index 876e336fe5..9f83f65cd8 100644 --- a/build/compare-mozconfig/compare-mozconfigs.py +++ b/build/compare-mozconfig/compare-mozconfigs.py @@ -43,7 +43,7 @@ def readConfig(configfile, keys=[], required=[]): execfile(configfile, c) for k in keys: c = c[k] - items = c.keys() + items = list(c.keys()) err = False for key in required: if key not in items: diff --git a/build/mach_bootstrap.py b/build/mach_bootstrap.py index 22eaa3425a..108e3d070d 100644 --- a/build/mach_bootstrap.py +++ b/build/mach_bootstrap.py @@ -335,7 +335,7 @@ def bootstrap(topsrcdir, mozilla_dir=None): # always load local repository configuration mach.settings_paths.append(mozilla_dir) - for category, meta in CATEGORIES.items(): + for category, meta in list(CATEGORIES.items()): mach.define_category(category, meta['short'], meta['long'], meta['priority']) diff --git a/build/pymake/pymake/builtins.py b/build/pymake/pymake/builtins.py index eb6f2e11bd..e199cc6bbf 100644 --- a/build/pymake/pymake/builtins.py +++ b/build/pymake/pymake/builtins.py @@ -70,7 +70,7 @@ def sleep(args): values = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400} for a in args: multiplier = 1 - for k, v in values.iteritems(): + for k, v in values.items(): if a.endswith(k): a = a[:-1] multiplier = v diff --git a/build/pymake/pymake/data.py b/build/pymake/pymake/data.py index 540147cf31..dc479f7005 100644 --- a/build/pymake/pymake/data.py +++ b/build/pymake/pymake/data.py @@ -447,7 +447,7 @@ class Variables(object): self.parent = parent def readfromenvironment(self, env): - for k, v in env.iteritems(): + for k, v in env.items(): self.set(k, self.FLAVOR_RECURSIVE, self.SOURCE_ENVIRONMENT, v) def get(self, name, expand=True): @@ -547,7 +547,7 @@ class Variables(object): self.set(k, flavor, source, value) def __iter__(self): - for k, (flavor, source, value, valueexp) in self._map.iteritems(): + for k, (flavor, source, value, valueexp) in self._map.items(): yield k, flavor, source, value def __contains__(self, item): @@ -1678,7 +1678,7 @@ class Makefile(object): self.variables.set('MAKECMDGOALS', Variables.FLAVOR_SIMPLE, Variables.SOURCE_AUTOMATIC, ' '.join(targets)) - for vname, val in implicit.variables.iteritems(): + for vname, val in implicit.variables.items(): self.variables.set(vname, Variables.FLAVOR_SIMPLE, Variables.SOURCE_IMPLICIT, val) @@ -1753,7 +1753,7 @@ class Makefile(object): self._vpath = [e for e in re.split('[%s\s]+' % os.pathsep, value.resolvestr(self, self.variables, ['VPATH'])) if e != ''] - targets = list(self._targets.itervalues()) + targets = list(self._targets.values()) for t in targets: t.explicit = True for r in t.rules: @@ -1824,7 +1824,7 @@ class Makefile(object): def getsubenvironment(self, variables): env = dict(self.env) - for vname, v in self.exportedvars.iteritems(): + for vname, v in self.exportedvars.items(): if v: flavor, source, val = variables.get(vname) if val is None: diff --git a/build/pymake/pymake/parser.py b/build/pymake/pymake/parser.py index 4bff533688..e2633844af 100644 --- a/build/pymake/pymake/parser.py +++ b/build/pymake/pymake/parser.py @@ -108,7 +108,7 @@ _alltokens = re.compile(r'''\\*\# | # hash mark preceeded by any number of backs :: | (?:\$(?:$|[\(\{](?:%s)\s+|.)) | # dollar sign followed by EOF, a function keyword with whitespace, or any character :(?![\\/]) | # colon followed by anything except a slash (Windows path detection) - [=#{}();,|'"]''' % '|'.join(functions.functionmap.iterkeys()), re.VERBOSE) + [=#{}();,|'"]''' % '|'.join(iter(functions.functionmap.keys())), re.VERBOSE) def iterdata(d, offset, tokenlist, it): """ @@ -336,7 +336,7 @@ _conditionkeywords = { 'ifndef': ifndef } -_conditiontokens = tuple(_conditionkeywords.iterkeys()) +_conditiontokens = tuple(_conditionkeywords.keys()) _conditionre = re.compile(r'(%s)(?:$|\s+)' % '|'.join(_conditiontokens)) _directivestokenlist = _conditiontokens + \ diff --git a/build/pymake/pymake/process.py b/build/pymake/pymake/process.py index 85a1538877..d5d5aebc2d 100644 --- a/build/pymake/pymake/process.py +++ b/build/pymake/pymake/process.py @@ -28,7 +28,7 @@ def tokens2re(tokens): # which matches the pattern and captures it in a named match group. # The group names and patterns come are given as a dict in the function # argument. - nonescaped = r'(?%s)' % (name, value) for name, value in tokens.iteritems()) + nonescaped = r'(?%s)' % (name, value) for name, value in tokens.items()) # The final pattern matches either the above pattern, or an escaped # backslash, captured in the "escape" match group. return re.compile('(?:%s|%s)' % (nonescaped, r'(?P\\\\)')) @@ -115,7 +115,7 @@ class ClineSplitter(list): self._push(self.cline[:m.start()]) self.cline = self.cline[m.end():] - match = dict([(name, value) for name, value in m.groupdict().items() if value]) + match = dict([(name, value) for name, value in list(m.groupdict().items()) if value]) if 'quote' in match: # " or ' start a quoted string if match['quote'] == '"': @@ -166,7 +166,7 @@ class ClineSplitter(list): raise Exception, 'Unterminated quoted string in command' self._push(self.cline[:m.start()]) self.cline = self.cline[m.end():] - match = dict([(name, value) for name, value in m.groupdict().items() if value]) + match = dict([(name, value) for name, value in list(m.groupdict().items()) if value]) if 'quote' in match: # a double quote ends the quoted string, so go back to # unquoted parsing diff --git a/build/pymake/pymake/util.py b/build/pymake/pymake/util.py index c63f930cc2..6a606e6e7c 100644 --- a/build/pymake/pymake/util.py +++ b/build/pymake/pymake/util.py @@ -138,7 +138,7 @@ class MostUsedCache(object): return item.o def verify(self): - for k, v in self.d.iteritems(): + for k, v in self.d.items(): if v.o: assert v in self.active else: diff --git a/build/pymake/tests/datatests.py b/build/pymake/tests/datatests.py index 164961cf75..464ea8e19f 100644 --- a/build/pymake/tests/datatests.py +++ b/build/pymake/tests/datatests.py @@ -4,7 +4,7 @@ import re from cStringIO import StringIO def multitest(cls): - for name in cls.testdata.iterkeys(): + for name in cls.testdata.keys(): def m(self, name=name): return self.runSingle(*self.testdata[name]) diff --git a/build/pymake/tests/parsertests.py b/build/pymake/tests/parsertests.py index 3948b7e07f..9234852f47 100644 --- a/build/pymake/tests/parsertests.py +++ b/build/pymake/tests/parsertests.py @@ -5,7 +5,7 @@ import logging from cStringIO import StringIO def multitest(cls): - for name in cls.testdata.iterkeys(): + for name in cls.testdata.keys(): def m(self, name=name): return self.runSingle(*self.testdata[name]) @@ -217,7 +217,7 @@ class MakeSyntaxTest(TestBase): else: self.assertEqual(type(a), getattr(pymake.functions, e['type']), "compareRecursive: %s" % (ipath,)) - for k, v in e.iteritems(): + for k, v in e.items(): if k == 'type': pass elif k[0] == '[': @@ -264,7 +264,7 @@ class VariableTest(TestBase): m = pymake.data.Makefile() stmts.execute(m) - for k, v in self.expected.iteritems(): + for k, v in self.expected.items(): flavor, source, val = m.variables.get(k) if val is None: self.assertEqual(val, v, 'variable named %s' % k) diff --git a/build/pymake/tests/runtests.py b/build/pymake/tests/runtests.py index c263762a36..4d0ead4176 100644 --- a/build/pymake/tests/runtests.py +++ b/build/pymake/tests/runtests.py @@ -144,7 +144,7 @@ for makefile in makefiles: if sys.platform in data: d['returncode'] = data[sys.platform] elif key == 'environment': - for k, v in data.iteritems(): + for k, v in data.items(): d['env'][k] = v elif key == 'grep-for': d['grepfor'] = data diff --git a/build/release/info.py b/build/release/info.py index 7e7a30bcea..2fe8a6817b 100644 --- a/build/release/info.py +++ b/build/release/info.py @@ -90,7 +90,7 @@ def readConfig(configfile, keys=[], required=[]): execfile(configfile, c) for k in keys: c = c[k] - items = c.keys() + items = list(c.keys()) err = False for key in required: if key not in items: @@ -137,7 +137,7 @@ def getReleaseName(product, version, buildNumber): def getRepoMatchingBranch(branch, sourceRepositories): - for sr in sourceRepositories.values(): + for sr in list(sourceRepositories.values()): if branch in sr['path']: return sr return None diff --git a/build/util/hg.py b/build/util/hg.py index c76c8ef033..962d96f445 100644 --- a/build/util/hg.py +++ b/build/util/hg.py @@ -578,7 +578,7 @@ def adjust_paths(dest, **paths): config.add_section('paths') changed = False - for path_name, path_value in paths.items(): + for path_name, path_value in list(paths.items()): if (not config.has_option('paths', path_name) or config.get('paths', path_name) != path_value): changed = True diff --git a/config/check_spidermonkey_style.py b/config/check_spidermonkey_style.py index 5f06e6ad93..46cf852ce1 100644 --- a/config/check_spidermonkey_style.py +++ b/config/check_spidermonkey_style.py @@ -275,7 +275,7 @@ def check_style(): edges[inclname] = set() # Process all the JS files. - for filename in js_names.keys(): + for filename in list(js_names.keys()): inclname = js_names[filename] file_kind = FileKind.get(filename) if file_kind == FileKind.C or file_kind == FileKind.CPP or \ diff --git a/config/find_OOM_errors.py b/config/find_OOM_errors.py index 16065119b7..0cb8be5bd3 100644 --- a/config/find_OOM_errors.py +++ b/config/find_OOM_errors.py @@ -95,12 +95,12 @@ def count_lines(): """Keep track of the amount of times individual lines occur, in order to prioritize the errors which occur most frequently.""" counts = {} - for string,count in blacklist.items(): + for string,count in list(blacklist.items()): for line in string.split("\n"): counts[line] = counts.get(line, 0) + count lines = [] - for k,v in counts.items(): + for k,v in list(counts.items()): lines.append("{0:6}: {1}".format(v, k)) lines.sort() diff --git a/config/mozunit.py b/config/mozunit.py index 3dddf84ee4..f650628809 100644 --- a/config/mozunit.py +++ b/config/mozunit.py @@ -140,7 +140,7 @@ class MockedOpen(object): ''' def __init__(self, files = {}): self.files = {} - for name, content in files.iteritems(): + for name, content in files.items(): self.files[normcase(os.path.abspath(name))] = content def __call__(self, name, mode = 'r'): diff --git a/config/tests/unitMozZipFile.py b/config/tests/unitMozZipFile.py index 21833fbb47..7a7fc01cad 100644 --- a/config/tests/unitMozZipFile.py +++ b/config/tests/unitMozZipFile.py @@ -136,10 +136,10 @@ class TestExtensiveStored(unittest.TestCase): self.failIf(badEntry, badEntry) zlist = zf.namelist() zlist.sort() - vlist = self.ref.keys() + vlist = list(self.ref.keys()) vlist.sort() self.assertEqual(zlist, vlist) - for leaf, content in self.ref.iteritems(): + for leaf, content in self.ref.items(): zcontent = zf.read(leaf) self.assertEqual(content, zcontent) diff --git a/configure.py b/configure.py index f7392d0ffa..bb9a26bb2f 100644 --- a/configure.py +++ b/configure.py @@ -45,11 +45,11 @@ def config_status(config): sanitized_config = {} sanitized_config['substs'] = { - k: sanitized_bools(v) for k, v in config.iteritems() + k: sanitized_bools(v) for k, v in config.items() if k not in ('DEFINES', 'non_global_defines', 'TOPSRCDIR', 'TOPOBJDIR') } sanitized_config['defines'] = { - k: sanitized_bools(v) for k, v in config['DEFINES'].iteritems() + k: sanitized_bools(v) for k, v in config['DEFINES'].items() } sanitized_config['non_global_defines'] = config['non_global_defines'] sanitized_config['topsrcdir'] = config['TOPSRCDIR'] @@ -71,7 +71,7 @@ def config_status(config): ''') % {'python': config['PYTHON'], 'encoding': encoding}) # A lot of the build backend code is currently expecting byte # strings and breaks in subtle ways with unicode strings. (bug 1296508) - for k, v in sanitized_config.iteritems(): + for k, v in sanitized_config.items(): fh.write('%s = encode(%s, encoding)\n' % (k, indented_repr(v))) fh.write("__all__ = ['topobjdir', 'topsrcdir', 'defines', " "'non_global_defines', 'substs', 'mozconfig']") diff --git a/dom/bindings/Codegen.py b/dom/bindings/Codegen.py index 8e9d91b48f..79d7845789 100644 --- a/dom/bindings/Codegen.py +++ b/dom/bindings/Codegen.py @@ -9728,7 +9728,7 @@ class CGEnum(CGThing): name=ENUM_ENTRY_VARIABLE_NAME, count=self.nEnumStrings(), entries=''.join('{"%s", %d},\n' % (val, len(val)) - for val in self.enum.values())))) + for val in list(self.enum.values()))))) toJSValue = CGEnumToJSValue(enum) self.cgThings = CGList([strings, toJSValue], "\n") @@ -9736,7 +9736,7 @@ class CGEnum(CGThing): return self.enum.identifier.name + "Values" def nEnumStrings(self): - return len(self.enum.values()) + 1 + return len(list(self.enum.values())) + 1 def declare(self): decl = fill( @@ -9747,7 +9747,7 @@ class CGEnum(CGThing): }; """, name=self.enum.identifier.name, - enums=",\n".join(map(getEnumValueName, self.enum.values())) + ",\n") + enums=",\n".join(map(getEnumValueName, list(self.enum.values()))) + ",\n") strings = CGNamespace(self.stringsNamespace(), CGGeneric(declare="extern const EnumEntry %s[%d];\n" % (ENUM_ENTRY_VARIABLE_NAME, self.nEnumStrings()))) @@ -13658,7 +13658,7 @@ class ForwardDeclarationBuilder: if self.decls: decls.append(CGList([CGClassForwardDeclare(cname, isStruct) for cname, isStruct in sorted(self.decls)])) - for namespace, child in sorted(self.children.iteritems()): + for namespace, child in sorted(self.children.items()): decls.append(CGNamespace(namespace, child._build(atTopLevel=False), declareOnly=True)) cg = CGList(decls, "\n") @@ -14008,10 +14008,10 @@ class CGBindingRoot(CGThing): # Add header includes. bindingHeaders = [header - for header, include in bindingHeaders.iteritems() + for header, include in bindingHeaders.items() if include] bindingDeclareHeaders = [header - for header, include in bindingDeclareHeaders.iteritems() + for header, include in bindingDeclareHeaders.items() if include] curr = CGHeaders(descriptors, @@ -14619,7 +14619,7 @@ class CGBindingImplClass(CGClass): (returnType, args), descriptor.getExtendedAttributes(op))) # Sort things by name so we get stable ordering in the output. - ops = descriptor.operations.items() + ops = list(descriptor.operations.items()) ops.sort(key=lambda x: x[0]) for name, op in ops: appendSpecialOperation(name, op) @@ -16969,7 +16969,7 @@ class GlobalGenRoots(): @staticmethod def UnionConversions(config): unionTypes = [] - for l in config.unionsPerFilename.itervalues(): + for l in config.unionsPerFilename.values(): unionTypes.extend(l) unionTypes.sort(key=lambda u: u.name) headers, unions = UnionConversions(unionTypes, diff --git a/dom/bindings/Configuration.py b/dom/bindings/Configuration.py index 6b1b1e254a..1a0aafead9 100644 --- a/dom/bindings/Configuration.py +++ b/dom/bindings/Configuration.py @@ -169,7 +169,7 @@ class Configuration(DescriptorProvider): # Collect up our filters, because we may have a webIDLFile filter that # we always want to apply first. tofilter = [] - for key, val in filters.iteritems(): + for key, val in filters.items(): if key == 'webIDLFile': # Special-case this part to make it fast, since most of our # getDescriptors calls are conditioned on a webIDLFile. We may diff --git a/dom/bindings/mozwebidlcodegen/__init__.py b/dom/bindings/mozwebidlcodegen/__init__.py index 881cd57ea2..d2e8b529fd 100644 --- a/dom/bindings/mozwebidlcodegen/__init__.py +++ b/dom/bindings/mozwebidlcodegen/__init__.py @@ -99,7 +99,7 @@ class WebIDLCodegenManagerState(dict): self['version'] = state['version'] self['global_depends'] = state['global_depends'] - for k, v in state['webidls'].items(): + for k, v in list(state['webidls'].items()): self['webidls'][k] = v # Sets are converted to lists for serialization because JSON @@ -111,7 +111,7 @@ class WebIDLCodegenManagerState(dict): """Dump serialized state to a file handle.""" normalized = deepcopy(self) - for k, v in self['webidls'].items(): + for k, v in list(self['webidls'].items()): # Convert sets to lists because JSON doesn't support sets. normalized['webidls'][k]['outputs'] = sorted(v['outputs']) normalized['webidls'][k]['inputs'] = sorted(v['inputs']) @@ -296,7 +296,7 @@ class WebIDLCodegenManager(LoggingMixin): if self._make_deps_path: mk = Makefile() codegen_rule = mk.create_rule([self._make_deps_target]) - codegen_rule.add_dependencies(global_hashes.keys()) + codegen_rule.add_dependencies(list(global_hashes.keys())) codegen_rule.add_dependencies(self._input_paths) with FileAvoidWrite(self._make_deps_path) as fh: @@ -382,7 +382,7 @@ class WebIDLCodegenManager(LoggingMixin): # Now we move on to the input files. old_hashes = {v['filename']: v['sha1'] - for v in self._state['webidls'].values()} + for v in list(self._state['webidls'].values())} old_filenames = set(old_hashes.keys()) new_filenames = self._input_paths @@ -403,7 +403,7 @@ class WebIDLCodegenManager(LoggingMixin): # Inherit dependencies from previous run. The full set of dependencies # is associated with each record, so we don't need to perform any fancy # graph traversal. - for v in self._state['webidls'].values(): + for v in list(self._state['webidls'].values()): if any(dep for dep in v['inputs'] if dep in changed_inputs): changed_inputs.add(v['filename']) @@ -512,7 +512,7 @@ class WebIDLCodegenManager(LoggingMixin): return True, current_hashes # Compare hashes. - for f, sha1 in current_hashes.items(): + for f, sha1 in list(current_hashes.items()): if sha1 != self._state['global_depends'][f]: return True, current_hashes diff --git a/dom/bindings/parser/WebIDL.py b/dom/bindings/parser/WebIDL.py index 65686fba21..69d5e92616 100644 --- a/dom/bindings/parser/WebIDL.py +++ b/dom/bindings/parser/WebIDL.py @@ -1515,7 +1515,7 @@ class IDLInterfaceOrNamespace(IDLObjectWithScope, IDLExposureMixins): assert len(naviProp) == 1 assert isinstance(naviProp, list) assert len(naviProp[0]) != 0 - conditionExtendedAttributes = self._extendedAttrDict.viewkeys() & IDLInterfaceOrNamespace.conditionExtendedAttributes + conditionExtendedAttributes = self._extendedAttrDict.keys() & IDLInterfaceOrNamespace.conditionExtendedAttributes attr = IDLAttribute(self.location, IDLUnresolvedIdentifier(BuiltinLocation(""), naviProp[0]), IDLUnresolvedType(self.location, IDLUnresolvedIdentifier(self.location, self.identifier.name)), @@ -3249,7 +3249,7 @@ integerTypeSizes = { def matchIntegerValueToType(value): - for type, extremes in integerTypeSizes.items(): + for type, extremes in list(integerTypeSizes.items()): (min, max) = extremes if value <= max and value >= min: return BuiltinTypes[type] @@ -3328,7 +3328,7 @@ class IDLValue(IDLObject): elif self.type.isString() and type.isEnum(): # Just keep our string, but make sure it's a valid value for this enum enum = type.unroll().inner - if self.value not in enum.values(): + if self.value not in list(enum.values()): raise WebIDLError("'%s' is not a valid default value for enum %s" % (self.value, enum.identifier.name), [location, enum.location]) @@ -5261,7 +5261,7 @@ class Tokenizer(object): "ReadableStream": "READABLESTREAM", } - tokens.extend(keywords.values()) + tokens.extend(list(keywords.values())) def t_error(self, t): raise WebIDLError("Unrecognized Input", diff --git a/dom/bindings/parser/tests/test_enum.py b/dom/bindings/parser/tests/test_enum.py index 8622893918..a647fb83c5 100644 --- a/dom/bindings/parser/tests/test_enum.py +++ b/dom/bindings/parser/tests/test_enum.py @@ -26,7 +26,7 @@ def WebIDLTest(parser, harness): enum = results[0] harness.check(enum.identifier.QName(), "::TestEnum", "Enum has the right QName") harness.check(enum.identifier.name, "TestEnum", "Enum has the right name") - harness.check(enum.values(), ["", "foo", "bar"], "Enum has the right values") + harness.check(list(enum.values()), ["", "foo", "bar"], "Enum has the right values") iface = results[1] diff --git a/dom/imptests/parseFailures.py b/dom/imptests/parseFailures.py index 6824b836c6..ec108bcab4 100644 --- a/dom/imptests/parseFailures.py +++ b/dom/imptests/parseFailures.py @@ -58,7 +58,7 @@ def writeFiles(files): dirp, leaf = path.rsplit('/', 1) pathmap.setdefault(dirp, []).append(leaf) - for k, v in pathmap.items(): + for k, v in list(pathmap.items()): with open(k + '/mochitest.ini', 'w') as fh: result = writeBuildFiles.substManifest('parseFailures.py', v, []) fh.write(result) diff --git a/dom/media/test/external/external_media_tests/media_utils/youtube_puppeteer.py b/dom/media/test/external/external_media_tests/media_utils/youtube_puppeteer.py index 0f9db39b3b..cc861f300a 100644 --- a/dom/media/test/external/external_media_tests/media_utils/youtube_puppeteer.py +++ b/dom/media/test/external/external_media_tests/media_utils/youtube_puppeteer.py @@ -75,7 +75,7 @@ class YouTubePuppeteer(VideoPuppeteer): 'BUFFERING': 3, 'CUED': 5 } - _yt_player_state_name = {v: k for k, v in _yt_player_state.items()} + _yt_player_state_name = {v: k for k, v in list(_yt_player_state.items())} _time_pattern = re.compile('(?P\d+):(?P\d+)') def __init__(self, marionette, url, autostart=True, **kwargs): diff --git a/dom/media/test/external/mach_commands.py b/dom/media/test/external/mach_commands.py index e309f3c55e..487a7d21fe 100644 --- a/dom/media/test/external/mach_commands.py +++ b/dom/media/test/external/mach_commands.py @@ -45,7 +45,7 @@ def run_external_media_test(tests, testtype=None, topsrcdir=None, **kwargs): args = Namespace(tests=tests) - for k, v in kwargs.iteritems(): + for k, v in kwargs.items(): setattr(args, k, v) parser.verify_usage(args) diff --git a/dom/media/test/graph_latency.py b/dom/media/test/graph_latency.py index e5203406fa..ee3d706ab2 100644 --- a/dom/media/test/graph_latency.py +++ b/dom/media/test/graph_latency.py @@ -22,7 +22,7 @@ def compute_sum(data): out = ([],[]) for i in data: - if i[0] not in last_values.keys(): + if i[0] not in list(last_values.keys()): last_values[i[0]] = 0 last_values[i[0]] = float(i[3]) print(last_values) @@ -76,7 +76,7 @@ for tupl in data: name = tupl[0] if tupl[1] != 0: name = name+tupl[1] - if name not in final_data.keys(): + if name not in list(final_data.keys()): final_data[name] = ([], []) # sanity-check values if float(tupl[3]) < 10*1000: @@ -89,7 +89,7 @@ for tupl in data: pprint(final_data) fig = plt.figure() -for i in final_data.keys(): +for i in list(final_data.keys()): plt.plot(final_data[i][0], final_data[i][1], label=i) plt.legend() diff --git a/gfx/angle/src/libANGLE/renderer/angle_format.py b/gfx/angle/src/libANGLE/renderer/angle_format.py index e46bc7dba9..c0be62baec 100755 --- a/gfx/angle/src/libANGLE/renderer/angle_format.py +++ b/gfx/angle/src/libANGLE/renderer/angle_format.py @@ -39,7 +39,7 @@ def load_with_override(override_path): results = load_forward_table(map_path) overrides = load_json(override_path) - for k, v in overrides.iteritems(): + for k, v in overrides.items(): results[k] = v return results diff --git a/gfx/angle/src/libANGLE/renderer/d3d/d3d11/gen_dxgi_support_tables.py b/gfx/angle/src/libANGLE/renderer/d3d/d3d11/gen_dxgi_support_tables.py index 76411c1b5e..162bb5e9c6 100755 --- a/gfx/angle/src/libANGLE/renderer/d3d/d3d11/gen_dxgi_support_tables.py +++ b/gfx/angle/src/libANGLE/renderer/d3d/d3d11/gen_dxgi_support_tables.py @@ -141,7 +141,7 @@ def do_format(format_data): 'depthStencil': macro_prefix + 'DS' } - for format_name, format_support in sorted(format_data.iteritems()): + for format_name, format_support in sorted(format_data.items()): always_supported = set() never_supported = set() @@ -152,7 +152,7 @@ def do_format(format_data): fl_10_0_check_10_1_supported = set() fl_10_0_check_11_0_supported = set() - for json_flag, support in format_support.iteritems(): + for json_flag, support in format_support.items(): d3d_flag = [json_flag_to_d3d[json_flag]] diff --git a/gfx/angle/src/libANGLE/renderer/d3d/d3d11/gen_texture_format_table.py b/gfx/angle/src/libANGLE/renderer/d3d/d3d11/gen_texture_format_table.py index 981a77f51a..de79ae5755 100755 --- a/gfx/angle/src/libANGLE/renderer/d3d/d3d11/gen_texture_format_table.py +++ b/gfx/angle/src/libANGLE/renderer/d3d/d3d11/gen_texture_format_table.py @@ -158,8 +158,8 @@ def get_swizzle_format_id(internal_format, angle_format): raise ValueError('no bits information for determining swizzleformat for format: ' + internal_format) bits = angle_format['bits'] - max_component_bits = max(bits.itervalues()) - channels_different = not all([component_bits == bits.itervalues().next() for component_bits in bits.itervalues()]) + max_component_bits = max(bits.values()) + channels_different = not all([component_bits == iter(bits.values()).next() for component_bits in bits.values()]) # The format itself can be used for swizzles if it can be accessed as a render target and # sampled and the bit count for all 4 channels is the same. @@ -261,7 +261,7 @@ def json_to_table_data(internal_format, format_name, prefix, json): "condition": prefix, } - for k, v in json.iteritems(): + for k, v in json.items(): parsed[k] = v # Derived values. @@ -280,15 +280,15 @@ def parse_json_angle_format_case(format_name, angle_format, json_data): support_test = None fallback = None - for k, v in angle_format.iteritems(): + for k, v in angle_format.items(): if k == "FL10Plus": assert support_test is None support_test = "OnlyFL10Plus(deviceCaps)" - for k2, v2 in v.iteritems(): + for k2, v2 in v.items(): supported_case[k2] = v2 elif k == "FL9_3": split = True - for k2, v2 in v.iteritems(): + for k2, v2 in v.items(): unsupported_case[k2] = v2 elif k == "supportTest": assert support_test is None @@ -312,7 +312,7 @@ def parse_json_angle_format_case(format_name, angle_format, json_data): def parse_json_into_switch_angle_format_string(json_map, json_data): table_data = '' - for internal_format, format_name in sorted(json_map.iteritems()): + for internal_format, format_name in sorted(json_map.items()): if format_name not in json_data: continue diff --git a/gfx/angle/src/libANGLE/renderer/gen_angle_format_table.py b/gfx/angle/src/libANGLE/renderer/gen_angle_format_table.py index 20bd3e6db4..d6a8357ee5 100755 --- a/gfx/angle/src/libANGLE/renderer/gen_angle_format_table.py +++ b/gfx/angle/src/libANGLE/renderer/gen_angle_format_table.py @@ -183,7 +183,7 @@ def json_to_table_data(format_id, json, angle_to_gl): "id": format_id, } - for k, v in json.iteritems(): + for k, v in json.items(): parsed[k] = v if "glInternalFormat" not in parsed: @@ -227,7 +227,7 @@ def gen_enum_string(all_angle): gl_to_angle = angle_format.load_forward_table('angle_format_map.json') angle_to_gl = angle_format.load_inverse_table('angle_format_map.json') json_data = angle_format.load_json('angle_format_data.json') -all_angle = angle_to_gl.keys() +all_angle = list(angle_to_gl.keys()) angle_format_cases = parse_json_into_angle_format_switch_string( all_angle, json_data, angle_to_gl) diff --git a/gfx/angle/src/libANGLE/renderer/gen_load_functions_table.py b/gfx/angle/src/libANGLE/renderer/gen_load_functions_table.py index eb3e4c5bf0..2ba474680a 100755 --- a/gfx/angle/src/libANGLE/renderer/gen_load_functions_table.py +++ b/gfx/angle/src/libANGLE/renderer/gen_load_functions_table.py @@ -107,7 +107,7 @@ def get_load_func(func_name, type_functions): snippet += "{\n" snippet += " switch (type)\n" snippet += " {\n" - for gl_type, load_function in sorted(type_functions.iteritems()): + for gl_type, load_function in sorted(type_functions.items()): snippet += " case " + gl_type + ":\n" requiresConversion = str('LoadToNative<' not in load_function).lower() snippet += " return LoadImageFunctionInfo(" + load_function + ", " + requiresConversion + ");\n" @@ -127,13 +127,13 @@ def get_unknown_load_func(angle_to_type_map, internal_format): def parse_json(json_data): table_data = '' load_functions_data = '' - for internal_format, angle_to_type_map in sorted(json_data.iteritems()): + for internal_format, angle_to_type_map in sorted(json_data.items()): s = ' ' table_data += s + 'case ' + internal_format + ':\n' - do_switch = len(angle_to_type_map) > 1 or angle_to_type_map.keys()[0] != angle_format_unknown + do_switch = len(angle_to_type_map) > 1 or list(angle_to_type_map.keys())[0] != angle_format_unknown if do_switch: table_data += s + '{\n' @@ -142,7 +142,7 @@ def parse_json(json_data): table_data += s + '{\n' s += ' ' - for angle_format, type_functions in sorted(angle_to_type_map.iteritems()): + for angle_format, type_functions in sorted(angle_to_type_map.items()): if angle_format == angle_format_unknown: continue @@ -154,7 +154,7 @@ def parse_json(json_data): table_data += s + ' return ' + func_name + ';\n' if angle_format_unknown in angle_to_type_map: - for gl_type, load_function in angle_to_type_map[angle_format_unknown].iteritems(): + for gl_type, load_function in angle_to_type_map[angle_format_unknown].items(): if gl_type not in type_functions: type_functions[gl_type] = load_function diff --git a/gfx/gl/GLParseRegistryXML.py b/gfx/gl/GLParseRegistryXML.py index bdbce2ca1c..43e154653b 100755 --- a/gfx/gl/GLParseRegistryXML.py +++ b/gfx/gl/GLParseRegistryXML.py @@ -186,7 +186,7 @@ class GLDatabase: headerFile = GLConstHeader(f) headerFile.formatFileBegin() - constNames = self.consts.keys() + constNames = list(self.consts.keys()) constNames.sort() for lib in GLDatabase.LIBS: diff --git a/gfx/harfbuzz/src/gen-arabic-table.py b/gfx/harfbuzz/src/gen-arabic-table.py index 8360859478..74f4753341 100755 --- a/gfx/harfbuzz/src/gen-arabic-table.py +++ b/gfx/harfbuzz/src/gen-arabic-table.py @@ -66,13 +66,13 @@ def print_joining_table(f): values[u] = value short_value = {} - for value in sorted (set ([v for v in values.values ()] + ['JOINING_TYPE_X'])): + for value in sorted (set ([v for v in list(values.values ())] + ['JOINING_TYPE_X'])): short = ''.join(x[0] for x in value.split('_')[2:]) - assert short not in short_value.values() + assert short not in list(short_value.values()) short_value[value] = short print () - for value,short in short_value.items(): + for value,short in list(short_value.items()): print ("#define %s %s" % (short, value)) uu = sorted(values.keys()) @@ -149,7 +149,7 @@ def print_joining_table(f): print (" return X;") print ("}") print () - for value,short in short_value.items(): + for value,short in list(short_value.items()): print ("#undef %s" % (short)) print () @@ -217,7 +217,7 @@ def print_shaping_table(f): print ("static const uint16_t shaping_table[][4] =") print ("{") - keys = shapes.keys () + keys = list(shapes.keys ()) min_u, max_u = min (keys), max (keys) for u in range (min_u, max_u + 1): s = [shapes[u][shape] if u in shapes and shape in shapes[u] else 0 @@ -234,7 +234,7 @@ def print_shaping_table(f): ligas_2 = {} ligas_3 = {} ligas_mark_2 = {} - for key in ligatures.keys (): + for key in list(ligatures.keys ()): for shape in ligatures[key]: c = ligatures[key][shape] if len(key) == 3: diff --git a/gfx/harfbuzz/src/gen-emoji-table.py b/gfx/harfbuzz/src/gen-emoji-table.py index 540586037b..b7aa93b014 100644 --- a/gfx/harfbuzz/src/gen-emoji-table.py +++ b/gfx/harfbuzz/src/gen-emoji-table.py @@ -57,7 +57,7 @@ print () print ('#include "hb-unicode.hh"') print () -for typ, s in ranges.items(): +for typ, s in list(ranges.items()): if typ != "Extended_Pictographic": continue arr = dict() diff --git a/gfx/harfbuzz/src/gen-indic-table.py b/gfx/harfbuzz/src/gen-indic-table.py index b1029b6b7b..4d33124a7b 100755 --- a/gfx/harfbuzz/src/gen-indic-table.py +++ b/gfx/harfbuzz/src/gen-indic-table.py @@ -68,13 +68,13 @@ for i, f in enumerate (files): defaults = ('Other', 'Not_Applicable', 'No_Block') combined = {} for i,d in enumerate (unicode_data): - for u,v in d.items (): + for u,v in list(d.items ()): if i == 2 and not u in combined: continue if not u in combined: combined[u] = list (defaults) combined[u][i] = v -combined = {k:v for k,v in combined.items() if k in ALLOWED_SINGLES or v[2] in ALLOWED_BLOCKS} +combined = {k:v for k,v in list(combined.items()) if k in ALLOWED_SINGLES or v[2] in ALLOWED_BLOCKS} # Convert categories & positions types @@ -432,18 +432,18 @@ def position_to_category(pos): defaults = (category_map[defaults[0]], position_map[defaults[1]], defaults[2]) indic_data = {} -for k, (cat, pos, block) in combined.items(): +for k, (cat, pos, block) in list(combined.items()): cat = category_map[cat] pos = position_map[pos] indic_data[k] = (cat, pos, block) -for k,new_cat in category_overrides.items(): +for k,new_cat in list(category_overrides.items()): (cat, pos, _) = indic_data.get(k, defaults) indic_data[k] = (new_cat, pos, unicode_data[2][k]) # We only expect position for certain types positioned_categories = ('CM', 'SM', 'RS', 'H', 'M', 'MPst') -for k, (cat, pos, block) in indic_data.items(): +for k, (cat, pos, block) in list(indic_data.items()): if cat not in positioned_categories: pos = 'END' indic_data[k] = (cat, pos, block) @@ -454,7 +454,7 @@ for k, (cat, pos, block) in indic_data.items(): consonant_categories = ('C', 'CS', 'Ra','CM', 'V', 'PLACEHOLDER', 'DOTTEDCIRCLE') matra_categories = ('M', 'MPst') smvd_categories = ('SM', 'VD', 'A', 'Symbol') -for k, (cat, pos, block) in indic_data.items(): +for k, (cat, pos, block) in list(indic_data.items()): if cat in consonant_categories: pos = 'BASE_C' elif cat in matra_categories: @@ -466,13 +466,13 @@ for k, (cat, pos, block) in indic_data.items(): pos = 'SMVD'; indic_data[k] = (cat, pos, block) -for k,new_pos in position_overrides.items(): +for k,new_pos in list(position_overrides.items()): (cat, pos, _) = indic_data.get(k, defaults) indic_data[k] = (cat, new_pos, unicode_data[2][k]) values = [{_: 1} for _ in defaults] -for vv in indic_data.values(): +for vv in list(indic_data.values()): for i,v in enumerate(vv): values[i][v] = values[i].get (v, 0) + 1 @@ -513,7 +513,7 @@ for shaper in categories: print ('#include "hb-ot-shaper-%s-machine.hh"' % shaper) print () done = {} -for shaper, shaper_cats in categories.items(): +for shaper, shaper_cats in list(categories.items()): print ('/* %s */' % shaper) for cat in shaper_cats: v = shaper[0].upper() @@ -554,7 +554,7 @@ all_shorts = [{},{}] # Add some of the values, to make them more readable, and to avoid duplicates for i in range (2): - for v,s in short[i].items (): + for v,s in list(short[i].items ()): all_shorts[i][s] = v what = ["OT", "POS"] @@ -666,7 +666,7 @@ print (" {") pages = set ([u>>page_bits for u in starts+ends+list (singles.keys ())]) for p in sorted(pages): print (" case 0x%0Xu:" % p) - for u,d in singles.items (): + for u,d in list(singles.items ()): if p != u>>page_bits: continue print (" if (unlikely (u == 0x%04Xu)) return _(%s,%s);" % (u, short[0][d[0]], short[1][d[1]])) for (start,end) in zip (starts, ends): diff --git a/gfx/harfbuzz/src/gen-tag-table.py b/gfx/harfbuzz/src/gen-tag-table.py index 9fb595c116..24f7fc6c2a 100644 --- a/gfx/harfbuzz/src/gen-tag-table.py +++ b/gfx/harfbuzz/src/gen-tag-table.py @@ -405,7 +405,7 @@ class OpenTypeRegistryParser (HTMLParser): with open (filename, encoding='utf-8') as f: self.feed (f.read ()) expect (self.header) - for tag, iso_codes in self.to_bcp_47.items (): + for tag, iso_codes in list(self.to_bcp_47.items ()): for iso_code in iso_codes: self.from_bcp_47[iso_code].add (tag) @@ -483,7 +483,7 @@ class OpenTypeRegistryParser (HTMLParser): first_time = self.from_bcp_47_uninherited is None if first_time: self.from_bcp_47_uninherited = dict (self.from_bcp_47) - for macrolanguage, languages in dict (bcp_47.macrolanguages).items (): + for macrolanguage, languages in list(dict (bcp_47.macrolanguages).items ()): ot_macrolanguages = { ot_macrolanguage for ot_macrolanguage in self.from_bcp_47_uninherited.get (macrolanguage, set ()) } @@ -521,7 +521,7 @@ class OpenTypeRegistryParser (HTMLParser): def sort_languages (self): """Sort the values of ``from_bcp_47`` in ascending rank order.""" - for language, tags in self.from_bcp_47.items (): + for language, tags in list(self.from_bcp_47.items ()): self.from_bcp_47[language] = sorted (tags, key=lambda t: (self.ranks[t] + rank_delta (language, t), t)) @@ -642,10 +642,10 @@ class BCP47Parser (object): def remove_extra_macrolanguages (self): """Make every language have at most one macrolanguage.""" inverted = collections.defaultdict (list) - for macrolanguage, languages in self.macrolanguages.items (): + for macrolanguage, languages in list(self.macrolanguages.items ()): for language in languages: inverted[language].append (macrolanguage) - for language, macrolanguages in inverted.items (): + for language, macrolanguages in list(inverted.items ()): if len (macrolanguages) > 1: macrolanguages.sort (key=lambda ml: len (self.macrolanguages[ml])) biggest_macrolanguage = macrolanguages.pop () @@ -1008,7 +1008,7 @@ def print_subtag_matches (subtag, string, new_line): complex_tags = collections.defaultdict (list) for initial, group in itertools.groupby ((lt_tags for lt_tags in [ (LanguageTag (language), tags) - for language, tags in sorted (ot.from_bcp_47.items (), + for language, tags in sorted (list(ot.from_bcp_47.items ()), key=lambda i: (-len (i[0]), i[0])) ] if lt_tags[0].is_complex ()), key=lambda lt_tags: lt_tags[0].get_group ()): @@ -1160,7 +1160,7 @@ def verify_disambiguation_dict (): global bcp_47 global disambiguation global ot - for ot_tag, bcp_47_tags in ot.to_bcp_47.items (): + for ot_tag, bcp_47_tags in list(ot.to_bcp_47.items ()): if ot_tag == DEFAULT_LANGUAGE_SYSTEM: primary_tags = [] else: @@ -1194,7 +1194,7 @@ def verify_disambiguation_dict (): different_bcp_47_tags = sorted (t for t in bcp_47_tags if not same_tag (t, ot.from_bcp_47.get (t))) if different_bcp_47_tags and disambiguation[ot_tag] == different_bcp_47_tags[0] and '-' not in disambiguation[ot_tag]: del disambiguation[ot_tag] - for ot_tag in disambiguation.keys (): + for ot_tag in list(disambiguation.keys ()): expect (ot_tag in ot.to_bcp_47, 'unknown OT tag: %s' % ot_tag) verify_disambiguation_dict () diff --git a/gfx/harfbuzz/src/gen-ucd-table.py b/gfx/harfbuzz/src/gen-ucd-table.py index f8ff26ab54..59f32dfa10 100644 --- a/gfx/harfbuzz/src/gen-ucd-table.py +++ b/gfx/harfbuzz/src/gen-ucd-table.py @@ -51,15 +51,15 @@ dm = {i:tuple(int(v, 16) for v in u['dm'].split()) for i,u in enumerate(ucd) if u['dm'] != '#' and u['dt'] == 'can' and not (0xAC00 <= i < 0xAC00+11172)} ce = {i for i,u in enumerate(ucd) if u['Comp_Ex'] == 'Y'} -assert not any(v for v in dm.values() if len(v) not in (1,2)) -dm1 = sorted(set(v for v in dm.values() if len(v) == 1)) +assert not any(v for v in list(dm.values()) if len(v) not in (1,2)) +dm1 = sorted(set(v for v in list(dm.values()) if len(v) == 1)) assert all((v[0] >> 16) in (0,2) for v in dm1) dm1_p0_array = ['0x%04Xu' % (v[0] & 0xFFFF) for v in dm1 if (v[0] >> 16) == 0] dm1_p2_array = ['0x%04Xu' % (v[0] & 0xFFFF) for v in dm1 if (v[0] >> 16) == 2] dm1_order = {v:i+1 for i,v in enumerate(dm1)} dm2 = sorted((v+(i if i not in ce and not ccc[i] else 0,), v) - for i,v in dm.items() if len(v) == 2) + for i,v in list(dm.items()) if len(v) == 2) filt = lambda v: ((v[0] & 0xFFFFF800) == 0x0000 and (v[1] & 0xFFFFFF80) == 0x0300 and diff --git a/gfx/harfbuzz/src/gen-use-table.py b/gfx/harfbuzz/src/gen-use-table.py index f0859be21c..2082c0cf9d 100755 --- a/gfx/harfbuzz/src/gen-use-table.py +++ b/gfx/harfbuzz/src/gen-use-table.py @@ -86,13 +86,13 @@ for i,v in enumerate (defaults): values[i][v] = values[i].get (v, 0) + 1 combined = {} for i,d in enumerate (unicode_data): - for u,v in d.items (): + for u,v in list(d.items ()): if not u in combined: if i >= 4: continue combined[u] = list (defaults) combined[u][i] = v -combined = {k: v for k, v in combined.items() if v[6] not in DISABLED_SCRIPTS} +combined = {k: v for k, v in list(combined.items()) if v[6] not in DISABLED_SCRIPTS} property_names = [ @@ -350,8 +350,8 @@ use_positions = { def map_to_use(data): out = {} - items = use_mapping.items() - for U, (UISC, UIPC, AJT, UDI, UGC, UBlock, _) in data.items(): + items = list(use_mapping.items()) + for U, (UISC, UIPC, AJT, UDI, UGC, UBlock, _) in list(data.items()): # Resolve Indic_Syllabic_Category @@ -381,7 +381,7 @@ def map_to_use(data): pos_mapping = use_positions.get(USE, None) if pos_mapping: - values = [k for k,v in pos_mapping.items() if v and UIPC in v] + values = [k for k,v in list(pos_mapping.items()) if v and UIPC in v] assert len(values) == 1, "%s %s %s %s %s %s %s %s" % (hex(U), UIPC, USE, UISC, UDI, UGC, AJT, values) USE = USE + values[0] @@ -459,7 +459,7 @@ for k,v in sorted(use_mapping.items()): print ("#define %s USE(%s) /* %s */" % (k, k, v.__name__[3:])) for k,v in sorted(use_positions.items()): if not v: continue - for suf in v.keys(): + for suf in list(v.keys()): tag = k + suf print ("#define %s USE(%s)" % (tag, tag)) print ('#pragma GCC diagnostic pop') @@ -467,7 +467,7 @@ print ("") import packTab -data = {u:v[0] for u,v in use_data.items()} +data = {u:v[0] for u,v in list(use_data.items())} DEFAULT = 5 COMPACT = 9 @@ -498,7 +498,7 @@ for k in sorted(use_mapping.keys()): print ("#undef %s" % k) for k,v in sorted(use_positions.items()): if not v: continue - for suf in v.keys(): + for suf in list(v.keys()): tag = k + suf print ("#undef %s" % tag) print () diff --git a/gfx/harfbuzz/src/gen-vowel-constraints.py b/gfx/harfbuzz/src/gen-vowel-constraints.py index f06f103ab9..3a4ebf90f4 100644 --- a/gfx/harfbuzz/src/gen-vowel-constraints.py +++ b/gfx/harfbuzz/src/gen-vowel-constraints.py @@ -110,7 +110,7 @@ class ConstraintSet (object): cases = collections.defaultdict (set) for first, rest in sorted (self._c.items ()): cases[rest.__str__ (index + 1, depth + 2)].add (first) - for body, labels in sorted (cases.items (), key=lambda b_ls: sorted (b_ls[1])[0]): + for body, labels in sorted (list(cases.items ()), key=lambda b_ls: sorted (b_ls[1])[0]): for i, cp in enumerate (sorted (labels)): if i % 4 == 0: s.append (self._indent (depth + 1)) @@ -205,7 +205,7 @@ print (' unsigned int count = buffer->len;') print (' switch ((unsigned) buffer->props.script)') print (' {') -for script, constraints in sorted (constraints.items (), key=lambda s_c: script_order[s_c[0]]): +for script, constraints in sorted (list(constraints.items ()), key=lambda s_c: script_order[s_c[0]]): print((' case HB_SCRIPT_{}:'.format (script.upper ()))) print (' for (buffer->idx = 0; buffer->idx + 1 < count && buffer->successful;)') print (' {') diff --git a/gfx/skia/dump_mozbuild.py b/gfx/skia/dump_mozbuild.py index b5d40a65dc..f4ebf0a7e8 100644 --- a/gfx/skia/dump_mozbuild.py +++ b/gfx/skia/dump_mozbuild.py @@ -31,7 +31,7 @@ for unused in ['RULE_INPUT_PATH', 'RULE_INPUT_ROOT', 'RULE_INPUT_NAME', def CalculateVariables(default_variables, params): generator_flags = params.get('generator_flags', {}) - for key, val in generator_flags.items(): + for key, val in list(generator_flags.items()): default_variables.setdefault(key, val) default_variables.setdefault('OS', gyp.common.GetFlavor(params)) diff --git a/gfx/skia/generate_mozbuild.py b/gfx/skia/generate_mozbuild.py index 752fe300d8..d0ae5c3918 100755 --- a/gfx/skia/generate_mozbuild.py +++ b/gfx/skia/generate_mozbuild.py @@ -174,7 +174,7 @@ def generate_platform_sources(): sources[plat] = set(v.replace('../', 'skia/') for v in json.load(f)); f.close() - return dict(sources.items() + generate_opt_sources().items()) + return dict(list(sources.items()) + list(generate_opt_sources().items())) def generate_separated_sources(platform_sources): @@ -281,7 +281,7 @@ def generate_separated_sources(platform_sources): 'gpu': set() }) - for plat in platform_sources.keys(): + for plat in list(platform_sources.keys()): for value in platform_sources[plat]: if isblacklisted(value): continue diff --git a/intl/icu/source/python/icutools/databuilder/filtration.py b/intl/icu/source/python/icutools/databuilder/filtration.py index 08b69a7dd1..66e6d637e3 100644 --- a/intl/icu/source/python/icutools/databuilder/filtration.py +++ b/intl/icu/source/python/icutools/databuilder/filtration.py @@ -398,7 +398,7 @@ class ResourceFilterInfo(object): new_requests = [] i = 0 - for rules, filter_files in unique_rules.items(): + for rules, filter_files in list(unique_rules.items()): base_filter_file = filter_files[0] new_requests += [ PrintFileRequest( @@ -451,7 +451,7 @@ def _apply_resource_filters(all_requests, config, io): # Add the filter generation requests to the beginning so that by default # they are made before genrb gets run (order is required by windirect) new_requests = [] - for filter_info in collected.values(): + for filter_info in list(collected.values()): new_requests += filter_info.make_requests() new_requests += all_requests return new_requests diff --git a/intl/icu/source/python/icutools/databuilder/request_types.py b/intl/icu/source/python/icutools/databuilder/request_types.py index 55fcb2564d..c3a804ba2b 100644 --- a/intl/icu/source/python/icutools/databuilder/request_types.py +++ b/intl/icu/source/python/icutools/databuilder/request_types.py @@ -106,7 +106,7 @@ class AbstractExecutionRequest(AbstractRequest): def _del_at(self, i): del self.input_files[i] - for _, v in self.format_with.items(): + for _, v in list(self.format_with.items()): if isinstance(v, list): assert len(v) == len(self.input_files) + 1 del v[i] @@ -177,7 +177,7 @@ class RepeatedExecutionRequest(AbstractExecutionRequest): super(RepeatedExecutionRequest, self)._del_at(i) del self.output_files[i] del self.specific_dep_files[i] - for _, v in self.repeat_with.items(): + for _, v in list(self.repeat_with.items()): if isinstance(v, list): del v[i] @@ -222,7 +222,7 @@ class RepeatedOrSingleExecutionRequest(AbstractExecutionRequest): def _del_at(self, i): super(RepeatedOrSingleExecutionRequest, self)._del_at(i) del self.output_files[i] - for _, v in self.repeat_with.items(): + for _, v in list(self.repeat_with.items()): if isinstance(v, list): del v[i] diff --git a/intl/icu/source/python/icutools/databuilder/utils.py b/intl/icu/source/python/icutools/databuilder/utils.py index 3073abbd08..dcbb5df116 100644 --- a/intl/icu/source/python/icutools/databuilder/utils.py +++ b/intl/icu/source/python/icutools/databuilder/utils.py @@ -46,7 +46,7 @@ def get_local_dirname(dirname): return LOCAL_DIRNAME_SUBSTITUTIONS[variable] + dirname[sep_idx:] print( "Error: Local directory must be absolute, or relative to one of: " + - (", ".join("$%s" % v for v in LOCAL_DIRNAME_SUBSTITUTIONS.keys())), + (", ".join("$%s" % v for v in list(LOCAL_DIRNAME_SUBSTITUTIONS.keys()))), file=sys.stderr ) exit(1) @@ -77,7 +77,7 @@ def repeated_execution_request_looper(request): # dictionary of lists to list of dictionaries: ld = [ dict(list(zip(request.repeat_with, t))) - for t in zip(*request.repeat_with.values()) + for t in zip(*list(request.repeat_with.values())) ] if not ld: # No special options given in repeat_with diff --git a/intl/locale/props2arrays.py b/intl/locale/props2arrays.py index 510e0d51a0..3b3e564362 100644 --- a/intl/locale/props2arrays.py +++ b/intl/locale/props2arrays.py @@ -15,7 +15,7 @@ def main(header, propFile): if len(parts) == 2 and len(parts[0]) > 0: mappings[parts[0].strip()] = parts[1].strip() - keys = mappings.keys() + keys = list(mappings.keys()) keys.sort() header.write("// This is a generated file. Please do not edit.\n") diff --git a/ipc/chromium/src/third_party/libevent/event_rpcgen.py b/ipc/chromium/src/third_party/libevent/event_rpcgen.py index 9228f5aa03..ca4a351133 100755 --- a/ipc/chromium/src/third_party/libevent/event_rpcgen.py +++ b/ipc/chromium/src/third_party/libevent/event_rpcgen.py @@ -412,7 +412,7 @@ class Entry: "optaddarg" : self._optaddarg and ", const %s value" % self._ctype or "" } - for (k, v) in extradict.items(): + for (k, v) in list(extradict.items()): mapping[k] = v return mapping diff --git a/ipc/ipdl/ipdl/lower.py b/ipc/ipdl/ipdl/lower.py index 61855a7a9e..4b373fda7d 100644 --- a/ipc/ipdl/ipdl/lower.py +++ b/ipc/ipdl/ipdl/lower.py @@ -1730,7 +1730,7 @@ class _GenerateProtocolCode(ipdl.ast.Visitor): transitions.append(ifsametrigger) msgToTransitions[msgid] = transitions - for msgid, transitions in msgToTransitions.iteritems(): + for msgid, transitions in msgToTransitions.items(): block = Block() block.addstmts(transitions +[ StmtBreak() ]) msgswitch.addcase(CaseLabel(msgid), block) diff --git a/ipc/ipdl/ipdl/type.py b/ipc/ipdl/ipdl/type.py index 3cc3d40f9e..d28f7c8703 100644 --- a/ipc/ipdl/ipdl/type.py +++ b/ipc/ipdl/ipdl/type.py @@ -1581,7 +1581,7 @@ class Process: self.spawn.add(spawn) def iteredges(self): - for edgelist in self.edges.itervalues(): + for edgelist in self.edges.values(): for edge in edgelist: yield edge @@ -1690,7 +1690,7 @@ class ProcessGraph: @classmethod def iterbridges(cls): - for edges in cls.bridges.itervalues(): + for edges in cls.bridges.values(): for bridge in edges: yield bridge @@ -1711,7 +1711,7 @@ class ProcessGraph: @classmethod def iteropens(cls): - for edges in cls.opens.itervalues(): + for edges in cls.opens.values(): for opens in edges: yield opens @@ -1885,11 +1885,11 @@ class CheckProcessGraph(TcheckVisitor): for edge in process.iteredges(): print(' ', edge) print('Bridges') - for bridgeList in ProcessGraph.bridges.itervalues(): + for bridgeList in ProcessGraph.bridges.values(): for bridge in bridgeList: print(' ', bridge) print('Opens') - for opensList in ProcessGraph.opens.itervalues(): + for opensList in ProcessGraph.opens.values(): for opens in opensList: print(' ', opens) @@ -2140,7 +2140,7 @@ direction as trigger |t|''' root.loc, "when starting from state `%s', actors of protocol `%s' cannot be deleted", root.state.name, p.name) - for ts in p.states.itervalues(): + for ts in p.states.values(): if ts.state is not State.DEAD and ts.state not in allvisited: self.error(ts.loc, "unreachable state `%s' in protocol `%s'", diff --git a/js/src/builtin/embedjs.py b/js/src/builtin/embedjs.py index 5a0973e1e7..503c0c5a1c 100644 --- a/js/src/builtin/embedjs.py +++ b/js/src/builtin/embedjs.py @@ -132,7 +132,7 @@ def messages(jsmsg): def get_config_defines(buildconfig): # Collect defines equivalent to ACDEFINES and add MOZ_DEBUG_DEFINES. - env = {key: value for key, value in buildconfig.defines.iteritems() + env = {key: value for key, value in buildconfig.defines.items() if key not in buildconfig.non_global_defines} for define in buildconfig.substs['MOZ_DEBUG_DEFINES']: env[define] = 1 diff --git a/js/src/builtin/intl/make_intl_data.py b/js/src/builtin/intl/make_intl_data.py index 7cd4b2c652..ea2b93b493 100644 --- a/js/src/builtin/intl/make_intl_data.py +++ b/js/src/builtin/intl/make_intl_data.py @@ -64,7 +64,7 @@ def writeMappingsVar(println, mapping, name, description, source, url): println(u"") writeMappingHeader(println, description, source, url) println(u"var {0} = {{".format(name)) - for (key, value) in sorted(mapping.items(), key=itemgetter(0)): + for (key, value) in sorted(list(mapping.items()), key=itemgetter(0)): println(u' "{0}": "{1}",'.format(key, value)) println(u"};") @@ -103,7 +103,7 @@ bool js::intl::LanguageTag::{0}({1} {2}) {{ # Sort the subtags by length. That enables using an optimized comparator # for the binary search, which only performs a single |memcmp| for multiple # of two subtag lengths. - mappings_keys = mappings.keys() if type(mappings) == dict else mappings + mappings_keys = list(mappings.keys()) if type(mappings) == dict else mappings for (length, subtags) in groupby(sorted(mappings_keys, key=len), len): # Omit the length check if the current length is the maximum length. if length != tag_maxlength: @@ -198,7 +198,7 @@ void js::intl::LanguageTag::performComplexLanguageMappings() { # Merge duplicate language entries. language_aliases = {} for (deprecated_language, (language, script, region)) in ( - sorted(complex_language_mappings.items(), key=itemgetter(0)) + sorted(list(complex_language_mappings.items()), key=itemgetter(0)) ): key = (language, script, region) if key not in language_aliases: @@ -208,7 +208,7 @@ void js::intl::LanguageTag::performComplexLanguageMappings() { first_language = True for (deprecated_language, (language, script, region)) in ( - sorted(complex_language_mappings.items(), key=itemgetter(0)) + sorted(list(complex_language_mappings.items()), key=itemgetter(0)) ): key = (language, script, region) if deprecated_language in language_aliases[key]: @@ -265,7 +265,7 @@ void js::intl::LanguageTag::performComplexRegionMappings() { # Merge duplicate region entries. region_aliases = {} for (deprecated_region, (default, non_default_replacements)) in ( - sorted(complex_region_mappings.items(), key=itemgetter(0)) + sorted(list(complex_region_mappings.items()), key=itemgetter(0)) ): key = hash_key(default, non_default_replacements) if key not in region_aliases: @@ -275,7 +275,7 @@ void js::intl::LanguageTag::performComplexRegionMappings() { first_region = True for (deprecated_region, (default, non_default_replacements)) in ( - sorted(complex_region_mappings.items(), key=itemgetter(0)) + sorted(list(complex_region_mappings.items()), key=itemgetter(0)) ): key = hash_key(default, non_default_replacements) if deprecated_region in region_aliases[key]: @@ -380,7 +380,7 @@ bool js::intl::LanguageTag::performVariantMappings(JSContext* cx) { first_variant = True for (deprecated_variant, (type, replacement)) in ( - sorted(variant_mappings.items(), key=itemgetter(0)) + sorted(list(variant_mappings.items()), key=itemgetter(0)) ): if_kind = u"if" if first_variant else u"else if" first_variant = False @@ -498,7 +498,7 @@ bool js::intl::LanguageTag::updateGrandfatheredMappings(JSContext* cx) { is_first = True - for (tag, modern) in sorted(grandfathered_mappings.items(), key=itemgetter(0)): + for (tag, modern) in sorted(list(grandfathered_mappings.items()), key=itemgetter(0)): tag_match = re_unicode_locale_id.match(tag) assert tag_match is not None @@ -823,12 +823,12 @@ def readSupplementalData(core_file): complex_region_mappings_final = {} - for (deprecated_region, replacements) in complex_region_mappings.items(): + for (deprecated_region, replacements) in list(complex_region_mappings.items()): # Find all likely subtag entries which don't already contain a region # subtag and whose target region is in the list of replacement regions. region_likely_subtags = [(from_language, from_script, to_region) for ((from_language, from_script, from_region), - (_, _, to_region)) in likely_subtags.items() + (_, _, to_region)) in list(likely_subtags.items()) if from_region is None and to_region in replacements] # The first replacement entry is the default region. @@ -1152,7 +1152,7 @@ static bool IsCanonicallyCasedTransformType(mozilla::Span type) { "const LanguageSubtag&", "language", "IsStructurallyValidLanguageTag", "IsCanonicallyCasedLanguageTag", - complex_language_mappings.keys(), language_maxlength, + list(complex_language_mappings.keys()), language_maxlength, "Language subtags with complex mappings.", source, url) writeMappingsBinarySearch(println, "regionMapping", "RegionSubtag&", "region", @@ -1164,7 +1164,7 @@ static bool IsCanonicallyCasedTransformType(mozilla::Span type) { "const RegionSubtag&", "region", "IsStructurallyValidRegionTag", "IsCanonicallyCasedRegionTag", - complex_region_mappings.keys(), region_maxlength, + list(complex_region_mappings.keys()), region_maxlength, "Region subtags with complex mappings.", source, url) writeComplexLanguageTagMappings(println, complex_language_mappings, @@ -1282,17 +1282,17 @@ def writeCLDRLanguageTagLikelySubtagsTest(println, data, url): return to_canonical # |likely_subtags| contains non-canonicalized tags, so canonicalize it first. - likely_subtags_canonical = {k: likely_canonical(k, v) for (k, v) in likely_subtags.items()} + likely_subtags_canonical = {k: likely_canonical(k, v) for (k, v) in list(likely_subtags.items())} # Add test data for |Intl.Locale.prototype.maximize()|. - writeMappingsVar(println, {bcp47(k): bcp47(v) for (k, v) in likely_subtags_canonical.items()}, + writeMappingsVar(println, {bcp47(k): bcp47(v) for (k, v) in list(likely_subtags_canonical.items())}, "maxLikelySubtags", "Extracted from likelySubtags.xml.", source, url) # Use the maximalized tags as the input for the remove likely-subtags test. - minimized = {tag: removeLikelySubtags(tag) for tag in likely_subtags_canonical.values()} + minimized = {tag: removeLikelySubtags(tag) for tag in list(likely_subtags_canonical.values())} # Add test data for |Intl.Locale.prototype.minimize()|. - writeMappingsVar(println, {bcp47(k): bcp47(v) for (k, v) in minimized.items()}, + writeMappingsVar(println, {bcp47(k): bcp47(v) for (k, v) in list(minimized.items())}, "minLikelySubtags", "Extracted from likelySubtags.xml.", source, url) println(u""" @@ -1435,13 +1435,13 @@ class TzDataFile: def validateTimeZones(zones, links): """ Validate the zone and link entries. """ - linkZones = set(links.viewkeys()) + linkZones = set(links.keys()) intersect = linkZones.intersection(zones) if intersect: raise RuntimeError("Links also present in zones: %s" % intersect) zoneNames = set(z.name for z in zones) - linkTargets = set(links.viewvalues()) + linkTargets = set(links.values()) if not linkTargets.issubset(zoneNames): raise RuntimeError("Link targets not found: %s" % linkTargets.difference(zoneNames)) @@ -1507,7 +1507,7 @@ def readIANATimeZones(tzdataDir, ignoreBackzone, ignoreFactory): # Merge with backzone data. if not ignoreBackzone: zones |= backzones - links = {name: target for name, target in links.iteritems() if name not in backzones} + links = {name: target for name, target in links.items() if name not in backzones} links.update(backlinks) validateTimeZones(zones, links) @@ -1644,7 +1644,7 @@ def readICUTimeZonesFromZoneInfo(icuTzDir): elif name == namesKey: tzNames.extend(value) - links = dict((Zone(tzNames[zone]), tzNames[target]) for (zone, target) in tzLinks.iteritems()) + links = dict((Zone(tzNames[zone]), tzNames[target]) for (zone, target) in tzLinks.items()) zones = set([Zone(v) for v in tzNames if Zone(v) not in links]) validateTimeZones(zones, links) @@ -1673,7 +1673,7 @@ def readICUTimeZones(icuDir, icuTzDir, ignoreFactory): # Remove any outdated ICU links. for links in (zoneinfoLinks, typesLinks): - for zone in otherICULegacyLinks().keys(): + for zone in list(otherICULegacyLinks().keys()): if zone not in links: raise KeyError("Can't remove non-existent link from '%s'" % zone) del links[zone] @@ -1685,7 +1685,7 @@ def readICUTimeZones(icuDir, icuTzDir, ignoreFactory): if notFoundInZoneInfo64: raise RuntimeError("Missing time zones in zoneinfo64.txt: %s" % notFoundInZoneInfo64) - notFoundInZoneInfo64 = [zone for zone in typesLinks.iterkeys() if not inZoneInfo64(zone)] + notFoundInZoneInfo64 = [zone for zone in typesLinks.keys() if not inZoneInfo64(zone)] if notFoundInZoneInfo64: raise RuntimeError("Missing time zones in zoneinfo64.txt: %s" % notFoundInZoneInfo64) @@ -1697,8 +1697,8 @@ def readICUTimeZones(icuDir, icuTzDir, ignoreFactory): (zone for zone in typesZones) )) icuLinks = dict(chain( - ((zone, target) for (zone, target) in zoneinfoLinks.iteritems() if zone not in typesZones), - ((zone, target) for (zone, target) in typesLinks.iteritems()) + ((zone, target) for (zone, target) in zoneinfoLinks.items() if zone not in typesZones), + ((zone, target) for (zone, target) in typesLinks.items()) )) return (icuZones, icuLinks) @@ -1723,7 +1723,7 @@ def readICULegacyZones(icuDir): # A handful of non-IANA zones/links are not in icuzones and must be added # manually so that we won't invoke ICU with them. - for (zone, target) in otherICULegacyLinks().items(): + for (zone, target) in list(otherICULegacyLinks().items()): if zone in links: if links[zone] != target: raise KeyError( @@ -1813,23 +1813,23 @@ def findIncorrectICULinks(ianaZones, ianaLinks, icuZones, icuLinks): isICUZone = lambda zone: zone in icuZones # All links should be present in ICU. - missingTimeZones = [zone for zone in ianaLinks.iterkeys() if not isICUTimeZone(zone)] + missingTimeZones = [zone for zone in ianaLinks.keys() if not isICUTimeZone(zone)] if missingTimeZones: raise RuntimeError("Not all zones are present in ICU, did you forget " "to run intl/update-tzdata.sh? %s" % missingTimeZones) # Links which are only present in ICU? - additionalTimeZones = [zone for zone in icuLinks.iterkeys() if not isIANATimeZone(zone)] + additionalTimeZones = [zone for zone in icuLinks.keys() if not isIANATimeZone(zone)] if additionalTimeZones: raise RuntimeError("Additional links present in ICU, did you forget " "to run intl/update-tzdata.sh? %s" % additionalTimeZones) result = chain( # IANA links which have a different target in ICU. - ((zone, target, icuLinks[zone]) for (zone, target) in ianaLinks.iteritems() if isICULink(zone) and target != icuLinks[zone]), + ((zone, target, icuLinks[zone]) for (zone, target) in ianaLinks.items() if isICULink(zone) and target != icuLinks[zone]), # IANA links which are zones in ICU. - ((zone, target, zone.name) for (zone, target) in ianaLinks.iteritems() if isICUZone(zone)) + ((zone, target, zone.name) for (zone, target) in ianaLinks.items() if isICUZone(zone)) ) # Remove unnecessary UTC mappings. @@ -1851,7 +1851,7 @@ def processTimeZones(tzdataDir, icuDir, icuTzDir, version, ignoreBackzone, ignor # Remove all egacy ICU time zones. icuZones = {zone for zone in icuZones if zone not in legacyZones} icuLinks = { - zone: target for (zone, target) in icuLinks.items() if zone not in legacyLinks + zone: target for (zone, target) in list(icuLinks.items()) if zone not in legacyLinks } incorrectZones = findIncorrectICUZones(ianaZones, ianaLinks, icuZones, icuLinks, ignoreBackzone) @@ -1919,7 +1919,7 @@ def processTimeZones(tzdataDir, icuDir, icuTzDir, version, ignoreBackzone, ignor def updateBackzoneLinks(tzdataDir, links): (backzoneZones, backzoneLinks) = readIANAFiles(tzdataDir, ["backzone"]) (stableZones, updatedLinks, updatedZones) = partition( - links.iteritems(), + iter(links.items()), # Link not changed in backzone. lambda (zone, target): zone not in backzoneLinks and zone not in backzoneZones, # Link has a new target. @@ -1981,7 +1981,7 @@ def generateTzDataTestBackwardLinks(tzdataDir, version, ignoreBackzone, testDir) testDir, version, "timeZone_backward_links.js", u"// Link names derived from IANA Time Zone Database, backward file.", - links.iteritems() + iter(links.items()) ) def generateTzDataTestNotBackwardLinks(tzdataDir, version, ignoreBackzone, testDir): @@ -1995,7 +1995,7 @@ def generateTzDataTestNotBackwardLinks(tzdataDir, version, ignoreBackzone, testD testDir, version, "timeZone_notbackward_links.js", u"// Link names derived from IANA Time Zone Database, excluding backward file.", - links.iteritems() + iter(links.items()) ) def generateTzDataTestBackzone(tzdataDir, version, ignoreBackzone, testDir): @@ -2056,7 +2056,7 @@ def generateTzDataTestBackzoneLinks(tzdataDir, version, ignoreBackzone, testDir) testDir, version, "timeZone_backzone_links.js", comment + u"// Backzone links derived from IANA Time Zone Database.", - ((zone, target if not ignoreBackzone else links[zone]) for (zone, target) in backlinks.iteritems()) + ((zone, target if not ignoreBackzone else links[zone]) for (zone, target) in backlinks.items()) ) def generateTzDataTests(tzdataDir, version, ignoreBackzone, testDir): @@ -2146,8 +2146,8 @@ static inline bool Is{0}Type( linear_search_max_length = 4 - needs_binary_search = any(len(replacements.items()) > linear_search_max_length - for replacements in mapping.values()) + needs_binary_search = any(len(list(replacements.items())) > linear_search_max_length + for replacements in list(mapping.values())) if needs_binary_search: println(u""" @@ -2220,7 +2220,7 @@ const char* js::intl::LanguageTag::replace{0}ExtensionType( # Merge duplicate keys. key_aliases = {} - for (key, replacements) in sorted(mapping.items(), key=itemgetter(0)): + for (key, replacements) in sorted(list(mapping.items()), key=itemgetter(0)): hash_key = to_hash_key(replacements) if hash_key not in key_aliases: key_aliases[hash_key] = [] @@ -2228,7 +2228,7 @@ const char* js::intl::LanguageTag::replace{0}ExtensionType( key_aliases[hash_key].append(key) first_key = True - for (key, replacements) in sorted(mapping.items(), key=itemgetter(0)): + for (key, replacements) in sorted(list(mapping.items()), key=itemgetter(0)): hash_key = to_hash_key(replacements) if key in key_aliases[hash_key]: continue @@ -2242,7 +2242,7 @@ const char* js::intl::LanguageTag::replace{0}ExtensionType( {} ({}) {{""".format(if_kind, cond).strip("\n")) first_key = False - replacements = sorted(replacements.items(), key=itemgetter(0)) + replacements = sorted(list(replacements.items()), key=itemgetter(0)) if len(replacements) > linear_search_max_length: types = [t for (t, _) in replacements] diff --git a/js/src/ctypes/libffi/generate-darwin-source-and-headers.py b/js/src/ctypes/libffi/generate-darwin-source-and-headers.py index 964e861d43..b53ce68c9c 100644 --- a/js/src/ctypes/libffi/generate-darwin-source-and-headers.py +++ b/js/src/ctypes/libffi/generate-darwin-source-and-headers.py @@ -194,7 +194,7 @@ def generate_source_and_headers(generate_osx=True, generate_ios=True): build_target(desktop64_platform, platform_headers) mkdir_p('darwin_common/include') - for header_name, tag_tuples in platform_headers.iteritems(): + for header_name, tag_tuples in platform_headers.items(): basename, suffix = os.path.splitext(header_name) with open(os.path.join('darwin_common/include', header_name), 'w') as header: for tag_tuple in tag_tuples: diff --git a/js/src/devtools/automation/autospider.py b/js/src/devtools/automation/autospider.py index 63f88d6a6a..eadb4484bb 100755 --- a/js/src/devtools/automation/autospider.py +++ b/js/src/devtools/automation/autospider.py @@ -274,7 +274,7 @@ def run_command(command, check=False, **kwargs): # Add in environment variable settings for this variant. Normally used to # modify the flags passed to the shell or to set the GC zeal mode. -for k, v in variant.get('env', {}).items(): +for k, v in list(variant.get('env', {}).items()): env[k] = v.format( DIR=DIR.scripts, TOOLTOOL_CHECKOUT=DIR.tooltool, diff --git a/js/src/devtools/gc/gc-test.py b/js/src/devtools/gc/gc-test.py index fef8a92bf1..c7e55663f3 100644 --- a/js/src/devtools/gc/gc-test.py +++ b/js/src/devtools/gc/gc-test.py @@ -87,11 +87,11 @@ def run_tests(tests, test_dir): print('fail') return dict((filename, dict(TMax=TMax, TAvg=TAvg, MMax=MMax, MAvg=MAvg, SMax=SMax, SAvg=SAvg)) - for filename, (TMax, TAvg, MMax, MAvg, SMax, SAvg) in bench_map.iteritems()) + for filename, (TMax, TAvg, MMax, MAvg, SMax, SAvg) in bench_map.items()) def compare(current, baseline): percent_speedups = [] - for key, current_result in current.iteritems(): + for key, current_result in current.items(): try: baseline_result = baseline[key] except KeyError: diff --git a/js/src/devtools/rootAnalysis/analyze.py b/js/src/devtools/rootAnalysis/analyze.py index 58135d378b..551870664e 100755 --- a/js/src/devtools/rootAnalysis/analyze.py +++ b/js/src/devtools/rootAnalysis/analyze.py @@ -44,12 +44,12 @@ def print_command(command, outfile=None, env=None): if env: changed = {} e = os.environ - for key,value in env.items(): + for key,value in list(env.items()): if (key not in e) or (e[key] != value): changed[key] = value if changed: outputs = [] - for key, value in changed.items(): + for key, value in list(changed.items()): if key in e and e[key] in value: start = value.index(e[key]) end = start + len(e[key]) @@ -184,7 +184,7 @@ def run_job(name, config): else: with open(stdout_filename, 'w') as output: subprocess.check_call(command, stdout=output, env=env(config)) - for (temp, final) in temp_map.items(): + for (temp, final) in list(temp_map.items()): try: os.rename(temp, final) except OSError: @@ -232,7 +232,7 @@ for default in defaults: data = config.copy() -for k,v in vars(args).items(): +for k,v in list(vars(args).items()): if v is not None: data[k] = v diff --git a/js/src/devtools/rootAnalysis/t/sixgill.py b/js/src/devtools/rootAnalysis/t/sixgill.py index 2bdf76a49b..e26689449e 100644 --- a/js/src/devtools/rootAnalysis/t/sixgill.py +++ b/js/src/devtools/rootAnalysis/t/sixgill.py @@ -21,14 +21,14 @@ class Body(dict): # Indexes self['Line2Points'] = defaultdict(list) - for point, line in self['Points'].items(): + for point, line in list(self['Points'].items()): self['Line2Points'][line].append(point) self['SrcPoint2Edges'] = defaultdict(list) for edge in self['Edges']: src, dst = edge['Index'] self['SrcPoint2Edges'][src].append(edge) self['Line2Edges'] = defaultdict(list) - for (src, edges) in self['SrcPoint2Edges'].items(): + for (src, edges) in list(self['SrcPoint2Edges'].items()): line = self['Points'][src] self['Line2Edges'][line].extend(edges) diff --git a/js/src/frontend/GenerateReservedWords.py b/js/src/frontend/GenerateReservedWords.py index 465f9d0094..9945976374 100644 --- a/js/src/frontend/GenerateReservedWords.py +++ b/js/src/frontend/GenerateReservedWords.py @@ -80,7 +80,7 @@ def split_list_per_column(reserved_word_list, column): per_column = column_dict.setdefault(word[column], []) per_column.append(item) - return sorted(column_dict.items(), key=lambda (char, word): ord(char)) + return sorted(list(column_dict.items()), key=lambda (char, word): ord(char)) def generate_letter_switch(opt, unprocessed_columns, reserved_word_list, columns=None): @@ -161,7 +161,7 @@ def split_list_per_length(reserved_word_list): per_length = length_dict.setdefault(len(word), []) per_length.append(item) - return sorted(length_dict.items(), key=lambda (length, word): length) + return sorted(list(length_dict.items()), key=lambda (length, word): length) def generate_switch(opt, reserved_word_list): assert(len(reserved_word_list) != 0); diff --git a/js/src/gdb/mozilla/jsval.py b/js/src/gdb/mozilla/jsval.py index d6f5e01fdf..7380d4cc16 100644 --- a/js/src/gdb/mozilla/jsval.py +++ b/js/src/gdb/mozilla/jsval.py @@ -178,7 +178,7 @@ class jsvalTypeCache(object): # the i'th magic value. d = gdb.types.make_enum_dict(gdb.lookup_type('JSWhyMagic')) self.magic_names = list(range(max(d.values()) + 1)) - for (k,v) in d.items(): self.magic_names[v] = k + for (k,v) in list(d.items()): self.magic_names[v] = k # Choose an unboxing scheme for this architecture. self.boxer = Punbox if cache.void_ptr_t.sizeof == 8 else Nunbox diff --git a/js/src/gdb/mozilla/prettyprinters.py b/js/src/gdb/mozilla/prettyprinters.py index 87035d0eff..9bfe6e93d9 100644 --- a/js/src/gdb/mozilla/prettyprinters.py +++ b/js/src/gdb/mozilla/prettyprinters.py @@ -107,7 +107,7 @@ def clear_module_printers(module_name): # should remove. (It's not safe to delete entries from a dictionary # while we're iterating over it.) to_delete = [] - for (k, v) in d.items(): + for (k, v) in list(d.items()): if v.__module__ == module_name: to_delete.append(k) remove_from_subprinter_list(v) diff --git a/js/src/jsautokw.py b/js/src/jsautokw.py index e620668461..1bd21d4d70 100644 --- a/js/src/jsautokw.py +++ b/js/src/jsautokw.py @@ -80,7 +80,7 @@ def split_list_per_column(keyword_list, column): per_column = column_dict.setdefault(keyword[column], []) per_column.append(item) - return sorted(column_dict.items(), key=lambda (char, keyword): ord(char)) + return sorted(list(column_dict.items()), key=lambda (char, keyword): ord(char)) def generate_letter_switch(opt, unprocessed_columns, keyword_list, columns=None): @@ -161,7 +161,7 @@ def split_list_per_length(keyword_list): per_length = length_dict.setdefault(len(keyword), []) per_length.append(item) - return sorted(length_dict.items(), key=lambda (length, keyword): length) + return sorted(list(length_dict.items()), key=lambda (length, keyword): length) def generate_switch(opt, keyword_list): assert(len(keyword_list) != 0); diff --git a/js/src/tests/compare_bench.py b/js/src/tests/compare_bench.py index cfe9508cd4..012bd3e0ee 100644 --- a/js/src/tests/compare_bench.py +++ b/js/src/tests/compare_bench.py @@ -15,7 +15,7 @@ def avg(seq): def compare(current, baseline): percent_speedups = [] - for key, current_result in current.iteritems(): + for key, current_result in current.items(): try: baseline_result = baseline[key] except KeyError: diff --git a/js/src/tests/lib/jittests.py b/js/src/tests/lib/jittests.py index 5b62935617..e32258da9b 100755 --- a/js/src/tests/lib/jittests.py +++ b/js/src/tests/lib/jittests.py @@ -567,7 +567,7 @@ def process_test_results(results, num_tests, pb, options): sys.stdout.write(res.err) if options.check_output: - if res.test.path in output_dict.keys(): + if res.test.path in list(output_dict.keys()): if output_dict[res.test.path] != res.out: pb.message("FAIL - OUTPUT DIFFERS {}".format(res.test.relpath_tests)) else: diff --git a/js/src/tests/lib/manifest.py b/js/src/tests/lib/manifest.py index 7079a186f6..5570ca329b 100644 --- a/js/src/tests/lib/manifest.py +++ b/js/src/tests/lib/manifest.py @@ -199,7 +199,7 @@ def _emit_manifest_at(location, relative, test_gen, depth): filename = os.path.join(location, 'jstests.list') manifest = [] numTestFiles = 0 - for k, test_list in manifests.iteritems(): + for k, test_list in manifests.items(): fullpath = os.path.join(location, k) if os.path.isdir(fullpath): manifest.append("include " + k + "/jstests.list") diff --git a/js/src/tests/lib/results.py b/js/src/tests/lib/results.py index 451fe5b657..f3f91d3fee 100644 --- a/js/src/tests/lib/results.py +++ b/js/src/tests/lib/results.py @@ -131,7 +131,7 @@ class ResultsSink: dev_label = self.LABELS[tup][1] if self.options.check_output: - if output.test.path in self.output_dict.keys(): + if output.test.path in list(self.output_dict.keys()): if self.output_dict[output.test.path] != output: self.counts['FAIL'] += 1 self.print_automation_result( diff --git a/js/src/tests/lib/tests.py b/js/src/tests/lib/tests.py index 47eea194f3..baf6681d44 100644 --- a/js/src/tests/lib/tests.py +++ b/js/src/tests/lib/tests.py @@ -50,7 +50,7 @@ def get_jitflags(variant, **kwargs): return JITFLAGS[variant] def valid_jitflags(): - return JITFLAGS.keys() + return list(JITFLAGS.keys()) def get_environment_overlay(js_shell): """ @@ -81,7 +81,7 @@ def get_environment_overlay(js_shell): def change_env(env_overlay): # Apply the overlaid environment and record the current state. prior_env = {} - for key, val in env_overlay.items(): + for key, val in list(env_overlay.items()): prior_env[key] = os.environ.get(key, None) if 'PATH' in key and key in os.environ: os.environ[key] = '{}{}{}'.format(val, os.pathsep, os.environ[key]) @@ -94,7 +94,7 @@ def change_env(env_overlay): finally: # Restore the prior environment. - for key, val in prior_env.items(): + for key, val in list(prior_env.items()): if val is not None: os.environ[key] = val else: diff --git a/js/src/tests/parsemark.py b/js/src/tests/parsemark.py index 5c2fa4a71f..13420fba97 100644 --- a/js/src/tests/parsemark.py +++ b/js/src/tests/parsemark.py @@ -96,7 +96,7 @@ def parsemark(filepaths, fbench, stfu=False): print('Parsemarking {}...'.format(filename)) bench_map[filename] = fbench(filepath) print('{') - for i, (filename, (avg, stddev)) in enumerate(bench_map.iteritems()): + for i, (filename, (avg, stddev)) in enumerate(bench_map.items()): assert '"' not in filename fmt = ' {:30s}: {{"average_ms": {:6.2f}, "stddev_ms": {:6.2f}}}' if i != len(bench_map) - 1: @@ -105,7 +105,7 @@ def parsemark(filepaths, fbench, stfu=False): print(fmt.format(filename_str, avg, stddev)) print('}') return dict((filename, dict(average_ms=avg, stddev_ms=stddev)) - for filename, (avg, stddev) in bench_map.iteritems()) + for filename, (avg, stddev) in bench_map.items()) def main(): diff --git a/js/src/vm/make_unicode.py b/js/src/vm/make_unicode.py index 7a85ddb2c3..3c6ffe73bb 100755 --- a/js/src/vm/make_unicode.py +++ b/js/src/vm/make_unicode.py @@ -527,10 +527,10 @@ def process_special_casing(special_casing, table, index): return upper def ascii(char_dict): - return ifilter(lambda ch: ch <= 0x7f, char_dict.iterkeys()) + return ifilter(lambda ch: ch <= 0x7f, iter(char_dict.keys())) def latin1(char_dict): - return ifilter(lambda ch: ch <= 0xff, char_dict.iterkeys()) + return ifilter(lambda ch: ch <= 0xff, iter(char_dict.keys())) def is_empty(iterable): return not any(True for _ in iterable) @@ -567,11 +567,11 @@ def process_special_casing(special_casing, table, index): assert all(ch != lowerCase(ch) for ch in [0x0130, 0x03A3]) # Ensure Azeri, Lithuanian, and Turkish are the only languages with conditional case mappings. - assert is_equals(["az", "lt", "tr"], sorted(lang_conditional_tolower.iterkeys())) - assert is_equals(["az", "lt", "tr"], sorted(lang_conditional_toupper.iterkeys())) + assert is_equals(["az", "lt", "tr"], sorted(lang_conditional_tolower.keys())) + assert is_equals(["az", "lt", "tr"], sorted(lang_conditional_toupper.keys())) # Maximum case mapping length is three characters. - itervals = lambda d: d.itervalues() + itervals = lambda d: iter(d.values()) assert max(imap(len, chain( itervals(unconditional_tolower), itervals(unconditional_toupper), @@ -732,7 +732,7 @@ def write_special_casing_methods(unconditional_toupper, codepoint_table, println assert unconditional_toupper, "|unconditional_toupper| is not empty" # Sorted list of code units with special upper case mappings. - code_list = sorted(unconditional_toupper.iterkeys()) + code_list = sorted(unconditional_toupper.keys()) # Fail-fast if the input character isn't a special casing character. println(' if ({})'.format(out_range(code_list[0], code_list[-1]))) @@ -787,7 +787,7 @@ def write_special_casing_methods(unconditional_toupper, codepoint_table, println println('{') println(' switch(ch) {') - for (code, converted) in sorted(unconditional_toupper.iteritems(), key=itemgetter(0)): + for (code, converted) in sorted(iter(unconditional_toupper.items()), key=itemgetter(0)): println(' case {}: return {}; // {}'.format(hexlit(code), len(converted), codepoint_table.name(code))) println(' }') @@ -804,7 +804,7 @@ def write_special_casing_methods(unconditional_toupper, codepoint_table, println println('{') println(' switch(ch) {') - for (code, converted) in sorted(unconditional_toupper.iteritems(), key=itemgetter(0)): + for (code, converted) in sorted(iter(unconditional_toupper.items()), key=itemgetter(0)): println(' case {}: // {}'.format(hexlit(code), codepoint_table.name(code))) for ch in converted: println(' elements[(*index)++] = {}; // {}'.format(hexlit(ch), @@ -1072,7 +1072,7 @@ def make_unicode_file(version, println('bool') println('js::unicode::{}(uint32_t codePoint)'.format(name)) println('{') - for (from_code, to_code) in int_ranges(group_set.keys()): + for (from_code, to_code) in int_ranges(list(group_set.keys())): println(' if (codePoint >= 0x{:X} && codePoint <= 0x{:X}) // {} .. {}'.format(from_code, to_code, codepoint_table.name(from_code), @@ -1117,7 +1117,7 @@ def make_unicode_file(version, # If the following assert fails, it means space character is added to # non-BMP area. In that case the following code should be uncommented # and the corresponding code should be added to frontend. - assert len(non_bmp_space_set.keys()) == 0 + assert len(list(non_bmp_space_set.keys())) == 0 write_supplemental_identifier_method('IsIdentifierStartNonBMP', non_bmp_id_start_set, println) @@ -1304,7 +1304,7 @@ def make_irregexp_tables(version, println(' return {};'.format(consequent(casefolded))) println(' }') println('') - for (ch, casemapped_chars) in casemap_for_latin1.iteritems(): + for (ch, casemapped_chars) in casemap_for_latin1.items(): for casemapped in casemapped_chars: println(' // "{}" case maps to "{}".'.format(char_name(casemapped), char_name(ch))) diff --git a/layout/generic/frame-graph.py b/layout/generic/frame-graph.py index ac1076b83c..025ada76d5 100644 --- a/layout/generic/frame-graph.py +++ b/layout/generic/frame-graph.py @@ -34,7 +34,7 @@ for line in sys.stdin: sys.stdout.write('digraph g {\n') -for olist in classdict.itervalues(): +for olist in classdict.values(): for line in olist: sys.stdout.write(line) diff --git a/layout/reftests/w3c-css/import-tests.py b/layout/reftests/w3c-css/import-tests.py index 1a631e2bec..077e5528a8 100755 --- a/layout/reftests/w3c-css/import-tests.py +++ b/layout/reftests/w3c-css/import-tests.py @@ -339,7 +339,7 @@ def main(): listfile.write("\ndefault-preferences {0}\n\n".format(defaultPreferences)) lastDefaultPreferences = defaultPreferences key = 1 - while not test[key] in gTestFlags.keys() and key < len(test): + while not test[key] in list(gTestFlags.keys()) and key < len(test): key = key + 1 testType = test[key - 1] testFlags = gTestFlags[test[key]] diff --git a/layout/tools/reftest/reftestcommandline.py b/layout/tools/reftest/reftestcommandline.py index 40bd8a5ee1..7469bc65f1 100644 --- a/layout/tools/reftest/reftestcommandline.py +++ b/layout/tools/reftest/reftestcommandline.py @@ -254,7 +254,7 @@ class ReftestArgumentsParser(argparse.ArgumentParser): return for test_path in options.tests: - for manifest_file, suite in manifests.iteritems(): + for manifest_file, suite in manifests.items(): if os.path.exists(os.path.join(test_path, manifest_file)): options.suite = suite return diff --git a/layout/tools/reftest/runreftest.py b/layout/tools/reftest/runreftest.py index f539d2d8dc..cd0516b2f8 100644 --- a/layout/tools/reftest/runreftest.py +++ b/layout/tools/reftest/runreftest.py @@ -194,7 +194,7 @@ class ReftestResolver(object): manifests[manifest] = set() manifests[manifest].add(filter_str) - for key in manifests.iterkeys(): + for key in manifests.keys(): if None in manifests[key]: manifests[key] = None else: diff --git a/layout/tools/reftest/runreftestb2g.py b/layout/tools/reftest/runreftestb2g.py index a62429da2a..57c870ce0f 100644 --- a/layout/tools/reftest/runreftestb2g.py +++ b/layout/tools/reftest/runreftestb2g.py @@ -37,12 +37,12 @@ class ProfileConfigParser(ConfigParser.RawConfigParser): def write(self, fp): if self._defaults: fp.write("[%s]\n" % ConfigParser.DEFAULTSECT) - for (key, value) in self._defaults.items(): + for (key, value) in list(self._defaults.items()): fp.write("%s=%s\n" % (key, str(value).replace('\n', '\n\t'))) fp.write("\n") for section in self._sections: fp.write("[%s]\n" % section) - for (key, value) in self._sections[section].items(): + for (key, value) in list(self._sections[section].items()): if key == "__name__": continue if (value is not None) or (self._optcre == self.OPTCRE): diff --git a/media/libaom/src/test/gviz_api.py b/media/libaom/src/test/gviz_api.py index d3a443dabf..6868c80682 100755 --- a/media/libaom/src/test/gviz_api.py +++ b/media/libaom/src/test/gviz_api.py @@ -491,9 +491,9 @@ class DataTable(object): # dictionary). # NOTE: this way of differentiating might create ambiguity. See docs. if (len(table_description) != 1 or - (isinstance(table_description.keys()[0], types.StringTypes) and - isinstance(table_description.values()[0], tuple) and - len(table_description.values()[0]) < 4)): + (isinstance(list(table_description.keys())[0], types.StringTypes) and + isinstance(list(table_description.values())[0], tuple) and + len(list(table_description.values())[0]) < 4)): # This is the most inner dictionary. Parsing types. columns = [] # We sort the items, equivalent to sort the keys since they are unique @@ -509,11 +509,11 @@ class DataTable(object): columns.append(parsed_col) return columns # This is an outer dictionary, must have at most one key. - parsed_col = DataTable.ColumnTypeParser(table_description.keys()[0]) + parsed_col = DataTable.ColumnTypeParser(list(table_description.keys())[0]) parsed_col["depth"] = depth parsed_col["container"] = "dict" return ([parsed_col] + - DataTable.TableDescriptionParser(table_description.values()[0], + DataTable.TableDescriptionParser(list(table_description.values())[0], depth=depth + 1)) @property @@ -622,7 +622,7 @@ class DataTable(object): return # We have a dictionary in an inner depth level. - if not data.keys(): + if not list(data.keys()): # In case this is an empty dictionary, we add a record with the columns # filled only until this point. self.__data.append(prev_col_values) diff --git a/media/libaom/src/tools/auto_refactor/auto_refactor.py b/media/libaom/src/tools/auto_refactor/auto_refactor.py index dd0d4415f9..f0dc4f0c1d 100644 --- a/media/libaom/src/tools/auto_refactor/auto_refactor.py +++ b/media/libaom/src/tools/auto_refactor/auto_refactor.py @@ -90,12 +90,12 @@ class StructInfo(): def update_struct_item_list(self): # Collect all struct_items from struct_name_dic and typedef_name_dic # Compute child_decl_map for each struct item. - for struct_name in self.struct_name_dic.keys(): + for struct_name in list(self.struct_name_dic.keys()): struct_item = self.struct_name_dic[struct_name] struct_item.compute_child_decl_map(self) self.struct_item_list.append(struct_item) - for typedef_name in self.typedef_name_dic.keys(): + for typedef_name in list(self.typedef_name_dic.keys()): struct_item = self.typedef_name_dic[typedef_name] if struct_item.struct_name not in self.struct_name_dic: struct_item.compute_child_decl_map(self) diff --git a/media/libaom/src/tools/cpplint.py b/media/libaom/src/tools/cpplint.py index cc11a8b45b..aba40709e3 100755 --- a/media/libaom/src/tools/cpplint.py +++ b/media/libaom/src/tools/cpplint.py @@ -512,7 +512,7 @@ _ALT_TOKEN_REPLACEMENT = { # False positives include C-style multi-line comments and multi-line strings # but those have always been troublesome for cpplint. _ALT_TOKEN_REPLACEMENT_PATTERN = re.compile( - r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)') + r'[ =()](' + ('|'.join(list(_ALT_TOKEN_REPLACEMENT.keys()))) + r')(?=[ (]|$)') # These constants define types of headers for use with @@ -952,7 +952,7 @@ class _CppLintState(object): def PrintErrorCounts(self): """Print a summary of errors by category, and the total.""" - for category, count in self.errors_by_category.iteritems(): + for category, count in self.errors_by_category.items(): sys.stderr.write('Category \'%s\' errors found: %d\n' % (category, count)) sys.stdout.write('Total errors found: %d\n' % self.error_count) @@ -4622,7 +4622,7 @@ def _GetTextInside(text, start_pattern): # Give opening punctuations to get the matching close-punctuations. matching_punctuation = {'(': ')', '{': '}', '[': ']'} - closing_punctuation = set(matching_punctuation.itervalues()) + closing_punctuation = set(matching_punctuation.values()) # Find the position to start extracting text. match = re.search(start_pattern, text, re.M) @@ -5570,7 +5570,7 @@ def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error, # include_dict is modified during iteration, so we iterate over a copy of # the keys. - header_keys = include_dict.keys() + header_keys = list(include_dict.keys()) for header in header_keys: (same_module, common_path) = FilesBelongToSameModule(abs_filename, header) fullpath = common_path + header diff --git a/media/libaom/src/tools/lint-hunks.py b/media/libaom/src/tools/lint-hunks.py index 81ababb430..9d8d2d4fa9 100755 --- a/media/libaom/src/tools/lint-hunks.py +++ b/media/libaom/src/tools/lint-hunks.py @@ -105,7 +105,7 @@ def main(argv=None): # Run each affected file through cpplint lint_failed = False - for filename, affected_lines in file_affected_line_map.iteritems(): + for filename, affected_lines in file_affected_line_map.items(): if filename.split(".")[-1] not in ("c", "h", "cc"): continue diff --git a/media/libjxl/src/tools/benchmark/metrics/plots.py b/media/libjxl/src/tools/benchmark/metrics/plots.py index 04b2bb24e5..19b475b2f3 100755 --- a/media/libjxl/src/tools/benchmark/metrics/plots.py +++ b/media/libjxl/src/tools/benchmark/metrics/plots.py @@ -236,7 +236,7 @@ def remap(metric): for (m, img) in data: fname = "%s/%s_%s" % (output_dir, m, img) fig = go.Figure() - for method in sorted(data[(m, img)].keys(), key=pos): + for method in sorted(list(data[(m, img)].keys()), key=pos): vals = data[(m, img)][method] zvals = list(zip(*sorted(vals))) if not zvals: diff --git a/media/libjxl/src/tools/conformance/conformance.py b/media/libjxl/src/tools/conformance/conformance.py index 6f5ccb659f..29246e7075 100755 --- a/media/libjxl/src/tools/conformance/conformance.py +++ b/media/libjxl/src/tools/conformance/conformance.py @@ -77,7 +77,7 @@ def CheckMeta(dec, ref): if isinstance(ref, dict): if not isinstance(dec, dict): return Failure("Malformed metadata file") - for k, v in ref.items(): + for k, v in list(ref.items()): if k in TEST_KEYS: continue if k not in dec: diff --git a/media/libjxl/src/tools/scripts/build_cleaner.py b/media/libjxl/src/tools/scripts/build_cleaner.py index b352887c35..3bf9739fc8 100644 --- a/media/libjxl/src/tools/scripts/build_cleaner.py +++ b/media/libjxl/src/tools/scripts/build_cleaner.py @@ -232,7 +232,7 @@ def BuildCleaner(args): with open(os.path.join(args.src_dir, 'lib/CMakeLists.txt'), 'r') as f: cmake_text = f.read() version = {'major_version': '', 'minor_version': '', 'patch_version': ''} - for var in version.keys(): + for var in list(version.keys()): cmake_var = f'JPEGXL_{var.upper()}' # TODO(eustas): use `cmake -L` # Regexp: diff --git a/media/libjxl/src/tools/scripts/build_stats.py b/media/libjxl/src/tools/scripts/build_stats.py index d95396968a..4b8d567146 100755 --- a/media/libjxl/src/tools/scripts/build_stats.py +++ b/media/libjxl/src/tools/scripts/build_stats.py @@ -232,7 +232,7 @@ def PrintStats(stats): for objstat in stats: bin_size = 0 ram_size = 0 - for kind, size in objstat.size_map.items(): + for kind, size in list(objstat.size_map.items()): if kind in BIN_SIZE: bin_size += size if kind in RAM_SIZE: @@ -263,7 +263,7 @@ def PrintStackStats(tgt_stack_sizes, top_entries=20): if not tgt_stack_sizes: return print(' Stack Symbol name') - for i, (name, size) in zip(itertools.count(), tgt_stack_sizes.items()): + for i, (name, size) in zip(itertools.count(), list(tgt_stack_sizes.items())): if top_entries > 0 and i >= top_entries: break print('%8d %s' % (size, name)) @@ -304,7 +304,7 @@ def SizeStats(args): # Cache of symbols of a target. syms = {} # Load the symbols from the all targets and its deps. - all_deps = set(tgts.keys()).union(*[set(tgt.deps) for tgt in tgts.values()]) + all_deps = set(tgts.keys()).union(*[set(tgt.deps) for tgt in list(tgts.values())]) for entry in all_deps: fn = os.path.join(args.build_dir, tgts[entry].filename if entry in tgts else entry) @@ -396,7 +396,7 @@ def SizeStats(args): # Check the maximum stack size. exit_code = 0 if args.max_stack: - for name, size in tgt_stack_sizes.items(): + for name, size in list(tgt_stack_sizes.items()): if size > args.max_stack: print('Error: %s exceeds stack limit: %d vs %d' % ( name, size, args.max_stack), diff --git a/media/libjxl/src/tools/wasm_demo/build_site.py b/media/libjxl/src/tools/wasm_demo/build_site.py index f47fa976b4..182130dc90 100644 --- a/media/libjxl/src/tools/wasm_demo/build_site.py +++ b/media/libjxl/src/tools/wasm_demo/build_site.py @@ -124,7 +124,7 @@ if __name__ == "__main__": print(f'Processing template {name}') path = source_path.joinpath(name) text = path.read_text().strip() - for key, value in substitutes.items(): + for key, value in list(substitutes.items()): text = text.replace(key, value) #text = uglify(text, name) output_path.joinpath(name).write_text(text) diff --git a/media/libvpx/libvpx/tools/cpplint.py b/media/libvpx/libvpx/tools/cpplint.py index cc11a8b45b..aba40709e3 100755 --- a/media/libvpx/libvpx/tools/cpplint.py +++ b/media/libvpx/libvpx/tools/cpplint.py @@ -512,7 +512,7 @@ _ALT_TOKEN_REPLACEMENT = { # False positives include C-style multi-line comments and multi-line strings # but those have always been troublesome for cpplint. _ALT_TOKEN_REPLACEMENT_PATTERN = re.compile( - r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)') + r'[ =()](' + ('|'.join(list(_ALT_TOKEN_REPLACEMENT.keys()))) + r')(?=[ (]|$)') # These constants define types of headers for use with @@ -952,7 +952,7 @@ class _CppLintState(object): def PrintErrorCounts(self): """Print a summary of errors by category, and the total.""" - for category, count in self.errors_by_category.iteritems(): + for category, count in self.errors_by_category.items(): sys.stderr.write('Category \'%s\' errors found: %d\n' % (category, count)) sys.stdout.write('Total errors found: %d\n' % self.error_count) @@ -4622,7 +4622,7 @@ def _GetTextInside(text, start_pattern): # Give opening punctuations to get the matching close-punctuations. matching_punctuation = {'(': ')', '{': '}', '[': ']'} - closing_punctuation = set(matching_punctuation.itervalues()) + closing_punctuation = set(matching_punctuation.values()) # Find the position to start extracting text. match = re.search(start_pattern, text, re.M) @@ -5570,7 +5570,7 @@ def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error, # include_dict is modified during iteration, so we iterate over a copy of # the keys. - header_keys = include_dict.keys() + header_keys = list(include_dict.keys()) for header in header_keys: (same_module, common_path) = FilesBelongToSameModule(abs_filename, header) fullpath = common_path + header diff --git a/media/libvpx/libvpx/tools/lint-hunks.py b/media/libvpx/libvpx/tools/lint-hunks.py index 0a94afebb9..4384aee8bd 100755 --- a/media/libvpx/libvpx/tools/lint-hunks.py +++ b/media/libvpx/libvpx/tools/lint-hunks.py @@ -103,7 +103,7 @@ def main(argv=None): # Run each affected file through cpplint lint_failed = False - for filename, affected_lines in file_affected_line_map.items(): + for filename, affected_lines in list(file_affected_line_map.items()): if filename.split(".")[-1] not in ("c", "h", "cc"): continue if filename.startswith("third_party"): diff --git a/media/libyuv/tools_libyuv/autoroller/roll_deps.py b/media/libyuv/tools_libyuv/autoroller/roll_deps.py index 5496e42403..2d0496f0f5 100755 --- a/media/libyuv/tools_libyuv/autoroller/roll_deps.py +++ b/media/libyuv/tools_libyuv/autoroller/roll_deps.py @@ -110,7 +110,7 @@ def _RunCommand(command, working_dir=None, ignore_exit_code=False, logging.debug('CMD: %s CWD: %s', ' '.join(command), working_dir) env = os.environ.copy() if extra_env: - assert all(isinstance(value, str) for value in extra_env.values()) + assert all(isinstance(value, str) for value in list(extra_env.values())) logging.debug('extra env: %s', extra_env) env.update(extra_env) p = subprocess.Popen(command, @@ -195,7 +195,7 @@ def GetMatchingDepsEntries(depsentry_dict, dir_path): A list of DepsEntry objects. """ result = [] - for path, depsentry in depsentry_dict.items(): + for path, depsentry in list(depsentry_dict.items()): if path == dir_path: result.append(depsentry) else: @@ -210,7 +210,7 @@ def BuildDepsentryDict(deps_dict): result = {} def AddDepsEntries(deps_subdict): - for path, deps_url_spec in deps_subdict.items(): + for path, deps_url_spec in list(deps_subdict.items()): if isinstance(deps_url_spec, dict): if deps_url_spec.get('dep_type') == 'cipd': continue @@ -245,7 +245,7 @@ def CalculateChangedDeps(libyuv_deps, new_cr_deps): result = [] libyuv_entries = BuildDepsentryDict(libyuv_deps) new_cr_entries = BuildDepsentryDict(new_cr_deps) - for path, libyuv_deps_entry in libyuv_entries.items(): + for path, libyuv_deps_entry in list(libyuv_entries.items()): if path in DONT_AUTOROLL_THESE: continue cr_deps_entry = new_cr_entries.get(path) diff --git a/media/webrtc/trunk/build/android/adb_logcat_monitor.py b/media/webrtc/trunk/build/android/adb_logcat_monitor.py index 43f814caf1..8fea5bd7d0 100755 --- a/media/webrtc/trunk/build/android/adb_logcat_monitor.py +++ b/media/webrtc/trunk/build/android/adb_logcat_monitor.py @@ -138,7 +138,7 @@ def main(base_dir, adb_cmd='adb'): except: logging.exception('Unexpected exception in main.') finally: - for process, _ in devices.itervalues(): + for process, _ in devices.values(): if process: try: process.terminate() diff --git a/media/webrtc/trunk/build/android/adb_logcat_printer.py b/media/webrtc/trunk/build/android/adb_logcat_printer.py index 5977945191..654a0eb595 100755 --- a/media/webrtc/trunk/build/android/adb_logcat_printer.py +++ b/media/webrtc/trunk/build/android/adb_logcat_printer.py @@ -106,7 +106,7 @@ def GetDeviceLogs(log_filenames, logger): """ device_logs = [] - for device, device_files in log_filenames.iteritems(): + for device, device_files in log_filenames.items(): logger.debug('%s: %s', device, str(device_files)) device_file_lines = [] for cur_file in device_files: diff --git a/media/webrtc/trunk/build/android/pylib/android_commands.py b/media/webrtc/trunk/build/android/pylib/android_commands.py index 80f1b08d58..ebd5bd8564 100644 --- a/media/webrtc/trunk/build/android/pylib/android_commands.py +++ b/media/webrtc/trunk/build/android/pylib/android_commands.py @@ -991,7 +991,7 @@ class AndroidCommands(object): for pid in pid_list: usage_dict_per_pid, smaps_per_pid = self.GetMemoryUsageForPid(pid) smaps[pid] = smaps_per_pid - for (key, value) in usage_dict_per_pid.items(): + for (key, value) in list(usage_dict_per_pid.items()): usage_dict[key] += value return usage_dict, smaps diff --git a/media/webrtc/trunk/build/android/pylib/apk_info.py b/media/webrtc/trunk/build/android/pylib/apk_info.py index 7e8867570b..65fd9377b4 100644 --- a/media/webrtc/trunk/build/android/pylib/apk_info.py +++ b/media/webrtc/trunk/build/android/pylib/apk_info.py @@ -129,7 +129,7 @@ class ApkInfo(object): def GetAnnotatedTests(self, annotation_filter_list): """Returns a list of all tests that match the given annotation filters.""" - return [test for test, annotations in self._GetAnnotationMap().iteritems() + return [test for test, annotations in self._GetAnnotationMap().items() if self._IsTestMethod(test) and self._AnnotationsMatchFilters( annotation_filter_list, annotations)] diff --git a/media/webrtc/trunk/build/android/pylib/tests_annotations.py b/media/webrtc/trunk/build/android/pylib/tests_annotations.py index f2a183466d..17e7564535 100644 --- a/media/webrtc/trunk/build/android/pylib/tests_annotations.py +++ b/media/webrtc/trunk/build/android/pylib/tests_annotations.py @@ -52,7 +52,7 @@ class AnnotatedFunctions(object): List of all annotations for this function. """ return [annotation - for annotation, tests in AnnotatedFunctions._ANNOTATED.iteritems() + for annotation, tests in AnnotatedFunctions._ANNOTATED.items() if qualified_function_name in tests] diff --git a/media/webrtc/trunk/testing/gtest/scripts/upload.py b/media/webrtc/trunk/testing/gtest/scripts/upload.py index 47374b8c43..bfdd4d47f4 100755 --- a/media/webrtc/trunk/testing/gtest/scripts/upload.py +++ b/media/webrtc/trunk/testing/gtest/scripts/upload.py @@ -165,7 +165,7 @@ class AbstractRpcServer(object): req = urllib2.Request(url, data=data) if self.host_override: req.add_header("Host", self.host_override) - for key, value in self.extra_headers.iteritems(): + for key, value in self.extra_headers.items(): req.add_header(key, value) return req @@ -698,7 +698,7 @@ class VersionControlSystem(object): patches = dict() [patches.setdefault(v, k) for k, v in patch_list] - for filename in patches.keys(): + for filename in list(patches.keys()): base_content, new_content, is_binary, status = files[filename] file_id_str = patches.get(filename) if file_id_str.find("nobase") != -1: @@ -1324,7 +1324,7 @@ def RealMain(argv, data=None): # Send a hash of all the base file so the server can determine if a copy # already exists in an earlier patchset. base_hashes = "" - for file, info in files.iteritems(): + for file, info in files.items(): if not info[0] is None: checksum = md5.new(info[0]).hexdigest() if base_hashes: diff --git a/media/webrtc/trunk/testing/gtest/test/gtest_test_utils.py b/media/webrtc/trunk/testing/gtest/test/gtest_test_utils.py index 39a6031cd5..41ccda4930 100755 --- a/media/webrtc/trunk/testing/gtest/test/gtest_test_utils.py +++ b/media/webrtc/trunk/testing/gtest/test/gtest_test_utils.py @@ -241,7 +241,7 @@ class Subprocess: # Changes made by os.environ.clear are not inheritable by child # processes until Python 2.6. To produce inheritable changes we have # to delete environment items with the del statement. - for key in dest.keys(): + for key in list(dest.keys()): del dest[key] dest.update(src) diff --git a/media/webrtc/trunk/testing/gtest/test/gtest_xml_test_utils.py b/media/webrtc/trunk/testing/gtest/test/gtest_xml_test_utils.py index 0e5a1089d1..6d815dd9f2 100755 --- a/media/webrtc/trunk/testing/gtest/test/gtest_xml_test_utils.py +++ b/media/webrtc/trunk/testing/gtest/test/gtest_xml_test_utils.py @@ -97,7 +97,7 @@ class GTestXMLTestCase(gtest_test_utils.TestCase): self.assertEquals( len(expected_children), len(actual_children), 'number of child elements differ in element ' + actual_node.tagName) - for child_id, child in expected_children.iteritems(): + for child_id, child in expected_children.items(): self.assert_(child_id in actual_children, '<%s> is not in <%s> (in element %s)' % (child_id, actual_children, actual_node.tagName)) diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/MSVSSettings.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/MSVSSettings.py index bafff625c0..e2ba0c1e00 100644 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/MSVSSettings.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/MSVSSettings.py @@ -433,7 +433,7 @@ def ConvertVCMacrosToMSBuild(s): '$(PlatformName)': '$(Platform)', '$(SafeInputName)': '%(Filename)', } - for old, new in replace_map.iteritems(): + for old, new in replace_map.items(): s = s.replace(old, new) s = FixVCMacroSlashes(s) return s @@ -453,10 +453,10 @@ def ConvertToMSBuildSettings(msvs_settings, stderr=sys.stderr): dictionaries of settings and their values. """ msbuild_settings = {} - for msvs_tool_name, msvs_tool_settings in msvs_settings.iteritems(): + for msvs_tool_name, msvs_tool_settings in msvs_settings.items(): if msvs_tool_name in _msvs_to_msbuild_converters: msvs_tool = _msvs_to_msbuild_converters[msvs_tool_name] - for msvs_setting, msvs_value in msvs_tool_settings.iteritems(): + for msvs_setting, msvs_value in msvs_tool_settings.items(): if msvs_setting in msvs_tool: # Invoke the translation function. try: @@ -513,7 +513,7 @@ def _ValidateSettings(validators, settings, stderr): for tool_name in settings: if tool_name in validators: tool_validators = validators[tool_name] - for setting, value in settings[tool_name].iteritems(): + for setting, value in settings[tool_name].items(): if setting in tool_validators: try: tool_validators[setting](value) diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/MSVSUserFile.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/MSVSUserFile.py index 6c07e9a893..2264d64015 100644 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/MSVSUserFile.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/MSVSUserFile.py @@ -91,7 +91,7 @@ class Writer(object): if environment and isinstance(environment, dict): env_list = ['%s="%s"' % (key, val) - for (key,val) in environment.iteritems()] + for (key,val) in environment.items()] environment = ' '.join(env_list) else: environment = '' @@ -135,7 +135,7 @@ class Writer(object): def WriteIfChanged(self): """Writes the user file.""" configs = ['Configurations'] - for config, spec in sorted(self.configurations.iteritems()): + for config, spec in sorted(self.configurations.items()): configs.append(spec) content = ['VisualStudioUserFile', diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/MSVSUtil.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/MSVSUtil.py index 96dea6c2c9..f24530b275 100644 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/MSVSUtil.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/MSVSUtil.py @@ -236,7 +236,7 @@ def InsertLargePdbShims(target_list, target_dicts, vars): # Set up the shim to output its PDB to the same location as the final linker # target. - for config_name, config in shim_dict.get('configurations').iteritems(): + for config_name, config in shim_dict.get('configurations').items(): pdb_path = _GetPdbPath(target_dict, config_name, vars) # A few keys that we don't want to propagate. diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/__init__.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/__init__.py index f76761a77a..2ac7afa0fa 100755 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/__init__.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/__init__.py @@ -92,7 +92,7 @@ def Load(build_files, format, default_variables={}, # These parameters are passed in order (as opposed to by key) # because ActivePython cannot handle key parameters to __import__. generator = __import__(generator_name, globals(), locals(), generator_name) - for (key, val) in generator.generator_default_variables.items(): + for (key, val) in list(generator.generator_default_variables.items()): default_variables.setdefault(key, val) # Give the generator the opportunity to set additional variables based on @@ -210,7 +210,7 @@ def RegenerateFlags(options): # We always want to ignore the environment when regenerating, to avoid # duplicate or changed flags in the environment at the time of regeneration. flags = ['--ignore-environment'] - for name, metadata in options._regeneration_metadata.iteritems(): + for name, metadata in options._regeneration_metadata.items(): opt = metadata['opt'] value = getattr(options, name) value_predicate = metadata['type'] == 'path' and FixPath or Noop @@ -493,7 +493,7 @@ def gyp_main(args): if options.generator_flags: gen_flags += options.generator_flags generator_flags = NameValueListToDict(gen_flags) - if DEBUG_GENERAL in gyp.debug.keys(): + if DEBUG_GENERAL in list(gyp.debug.keys()): DebugOutput(DEBUG_GENERAL, "generator_flags: %s", generator_flags) # Generate all requested formats (use a set in case we got one format request @@ -526,7 +526,7 @@ def gyp_main(args): generator.GenerateOutput(flat_list, targets, data, params) if options.configs: - valid_configs = targets[flat_list[0]]['configurations'].keys() + valid_configs = list(targets[flat_list[0]]['configurations'].keys()) for conf in options.configs: if conf not in valid_configs: raise GypError('Invalid config specified via --build: %s' % conf) diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/common_test.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/common_test.py index ad6f9a1438..a009f32389 100755 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/common_test.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/common_test.py @@ -23,7 +23,7 @@ class TestTopologicallySorted(unittest.TestCase): def GetEdge(node): return tuple(graph[node]) self.assertEqual( - gyp.common.TopologicallySorted(graph.keys(), GetEdge), + gyp.common.TopologicallySorted(list(graph.keys()), GetEdge), ['a', 'c', 'd', 'b']) def test_Cycle(self): @@ -38,7 +38,7 @@ class TestTopologicallySorted(unittest.TestCase): return tuple(graph[node]) self.assertRaises( gyp.common.CycleError, gyp.common.TopologicallySorted, - graph.keys(), GetEdge) + list(graph.keys()), GetEdge) class TestGetFlavor(unittest.TestCase): diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/easy_xml.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/easy_xml.py index bf949b6ac9..0bd28d0296 100644 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/easy_xml.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/easy_xml.py @@ -79,7 +79,7 @@ def _ConstructContentList(xml_parts, specification, pretty, level=0): # Optionally in second position is a dictionary of the attributes. rest = specification[1:] if rest and isinstance(rest[0], dict): - for at, val in sorted(rest[0].iteritems()): + for at, val in sorted(rest[0].items()): xml_parts.append(' %s="%s"' % (at, _XmlEscape(val, attr=True))) rest = rest[1:] if rest: @@ -143,7 +143,7 @@ _xml_escape_map = { _xml_escape_re = re.compile( - "(%s)" % "|".join(map(re.escape, _xml_escape_map.keys()))) + "(%s)" % "|".join(map(re.escape, list(_xml_escape_map.keys())))) def _XmlEscape(value, attr=False): diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/analyzer.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/analyzer.py index fd2e0a246c..ccb4cf4af9 100644 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/analyzer.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/analyzer.py @@ -410,7 +410,7 @@ def _GetUnqualifiedToTargetMapping(all_targets, to_find): if not to_find: return {}, [] to_find = set(to_find) - for target_name in all_targets.keys(): + for target_name in list(all_targets.keys()): extracted = gyp.common.ParseQualifiedTarget(target_name) if len(extracted) > 1 and extracted[1] in to_find: to_find.remove(extracted[1]) @@ -669,7 +669,7 @@ class TargetCalculator(object): assert self.is_build_impacted(); # Compile targets are found by searching up from changed targets. # Reset the visited status for _GetBuildTargets. - for target in self._name_to_target.itervalues(): + for target in self._name_to_target.values(): target.visited = False supplied_targets = _LookupTargets(self._supplied_target_names_no_all(), diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/cmake.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/cmake.py index 6c47d5d17a..de97aba007 100644 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/cmake.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/cmake.py @@ -979,7 +979,7 @@ def WriteTarget(namer, qualified_target, target_dicts, build_dir, config_to_use, # XCode settings xcode_settings = config.get('xcode_settings', {}) - for xcode_setting, xcode_value in xcode_settings.viewitems(): + for xcode_setting, xcode_value in xcode_settings.items(): SetTargetProperty(output, cmake_target_name, "XCODE_ATTRIBUTE_%s" % xcode_setting, xcode_value, '' if isinstance(xcode_value, str) else ' ') @@ -1230,7 +1230,7 @@ def GenerateOutput(target_list, target_dicts, data, params): GenerateOutputForConfig(target_list, target_dicts, data, params, user_config) else: - config_names = target_dicts[target_list[0]]['configurations'].keys() + config_names = list(target_dicts[target_list[0]]['configurations'].keys()) if params['parallel']: try: pool = multiprocessing.Pool(len(config_names)) diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/dump_dependency_json.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/dump_dependency_json.py index 719b6c1e54..c4b8872c64 100644 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/dump_dependency_json.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/dump_dependency_json.py @@ -34,7 +34,7 @@ for unused in ['RULE_INPUT_PATH', 'RULE_INPUT_ROOT', 'RULE_INPUT_NAME', def CalculateVariables(default_variables, params): generator_flags = params.get('generator_flags', {}) - for key, val in generator_flags.items(): + for key, val in list(generator_flags.items()): default_variables.setdefault(key, val) default_variables.setdefault('OS', gyp.common.GetFlavor(params)) diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/eclipse.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/eclipse.py index 3544347b3b..94a07f04a9 100644 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/eclipse.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/eclipse.py @@ -52,7 +52,7 @@ generator_default_variables['SHARED_INTERMEDIATE_DIR'] = \ def CalculateVariables(default_variables, params): generator_flags = params.get('generator_flags', {}) - for key, val in generator_flags.items(): + for key, val in list(generator_flags.items()): default_variables.setdefault(key, val) flavor = gyp.common.GetFlavor(params) default_variables.setdefault('OS', flavor) @@ -272,7 +272,7 @@ def WriteMacros(out, eclipse_langs, defines): out.write(' \n') for lang in eclipse_langs: out.write(' \n' % lang) - for key in sorted(defines.iterkeys()): + for key in sorted(defines.keys()): out.write(' %s%s\n' % (escape(key), escape(defines[key]))) out.write(' \n') @@ -418,7 +418,7 @@ def GenerateOutput(target_list, target_dicts, data, params): GenerateOutputForConfig(target_list, target_dicts, data, params, user_config) else: - config_names = target_dicts[target_list[0]]['configurations'].keys() + config_names = list(target_dicts[target_list[0]]['configurations'].keys()) for config_name in config_names: GenerateOutputForConfig(target_list, target_dicts, data, params, config_name) diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/gypd.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/gypd.py index 3efdb9966a..78eeaa61b2 100644 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/gypd.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/gypd.py @@ -88,7 +88,7 @@ def GenerateOutput(target_list, target_dicts, data, params): if not output_file in output_files: output_files[output_file] = input_file - for output_file, input_file in output_files.iteritems(): + for output_file, input_file in output_files.items(): output = open(output_file, 'w') pprint.pprint(data[input_file], output) output.close() diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/make.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/make.py index 60dde71390..f55fe4487c 100644 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/make.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/make.py @@ -499,7 +499,7 @@ cmd_infoplist = $(CC.$(TOOLSET)) -E -P -Wno-trigraphs -x c $(INFOPLIST_DEFINES) def WriteRootHeaderSuffixRules(writer): - extensions = sorted(COMPILABLE_EXTENSIONS.keys(), key=str.lower) + extensions = sorted(list(COMPILABLE_EXTENSIONS.keys()), key=str.lower) writer.write('# Suffix rules, putting all outputs into $(obj).\n') for ext in extensions: @@ -645,7 +645,7 @@ def _ValidateSourcesForOSX(spec, all_sources): basenames.setdefault(basename, []).append(source) error = '' - for basename, files in basenames.iteritems(): + for basename, files in basenames.items(): if len(files) > 1: error += ' %s: %s\n' % (basename, ' '.join(files)) @@ -680,7 +680,7 @@ class MakefileWriter(object): self.suffix_rules_objdir2 = {} # Generate suffix rules for all compilable extensions. - for ext in COMPILABLE_EXTENSIONS.keys(): + for ext in list(COMPILABLE_EXTENSIONS.keys()): # Suffix rules for source folder. self.suffix_rules_srcdir.update({ext: ("""\ $(obj).$(TOOLSET)/$(TARGET)/%%.o: $(srcdir)/%%%s FORCE_DO_CMD diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/msvs.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/msvs.py index cc5c4baf6d..d337ada706 100644 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/msvs.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/msvs.py @@ -457,7 +457,7 @@ def _AddCustomBuildToolForMSVS(p, spec, primary_input, 'CommandLine': cmd, }) # Add to the properties of primary input for each config. - for config_name, c_data in spec['configurations'].iteritems(): + for config_name, c_data in spec['configurations'].items(): p.AddFileConfig(_FixPath(primary_input), _ConfigFullName(config_name, c_data), tools=[tool]) @@ -878,7 +878,7 @@ def _FilterActionsFromExcluded(excluded_sources, actions_to_add): Returns: excluded_sources with files that have actions attached removed. """ - must_keep = OrderedSet(_FixPaths(actions_to_add.keys())) + must_keep = OrderedSet(_FixPaths(list(actions_to_add.keys()))) return [s for s in excluded_sources if s not in must_keep] @@ -979,7 +979,7 @@ def _ValidateSourcesForMSVSProject(spec, version): basenames.setdefault(basename, []).append(source) error = '' - for basename, files in basenames.iteritems(): + for basename, files in basenames.items(): if len(files) > 1: error += ' %s: %s\n' % (basename, ' '.join(files)) @@ -1011,7 +1011,7 @@ def _GenerateMSVSProject(project, options, version, generator_flags): relative_path_of_gyp_file = gyp.common.RelativePath(gyp_path, project_dir) config_type = _GetMSVSConfigurationType(spec, project.build_file) - for config_name, config in spec['configurations'].iteritems(): + for config_name, config in spec['configurations'].items(): _AddConfigurationToMSVSProject(p, spec, config_type, config_name, config) # MSVC08 and prior version cannot handle duplicate basenames in the same @@ -1380,10 +1380,10 @@ def _ConvertToolsToExpectedForm(tools): A list of Tool objects. """ tool_list = [] - for tool, settings in tools.iteritems(): + for tool, settings in tools.items(): # Collapse settings with lists. settings_fixed = {} - for setting, value in settings.iteritems(): + for setting, value in settings.items(): if type(value) == list: if ((tool == 'VCLinkerTool' and setting == 'AdditionalDependencies') or @@ -1558,7 +1558,7 @@ def _IdlFilesHandledNonNatively(spec, sources): def _GetPrecompileRelatedFiles(spec): # Gather a list of precompiled header related sources. precompiled_related = [] - for _, config in spec['configurations'].iteritems(): + for _, config in spec['configurations'].items(): for k in precomp_keys: f = config.get(k) if f: @@ -1569,7 +1569,7 @@ def _GetPrecompileRelatedFiles(spec): def _ExcludeFilesFromBeingBuilt(p, spec, excluded_sources, excluded_idl, list_excluded): exclusions = _GetExcludedFilesFromBuild(spec, excluded_sources, excluded_idl) - for file_name, excluded_configs in exclusions.iteritems(): + for file_name, excluded_configs in exclusions.items(): if (not list_excluded and len(excluded_configs) == len(spec['configurations'])): # If we're not listing excluded files, then they won't appear in the @@ -1586,7 +1586,7 @@ def _GetExcludedFilesFromBuild(spec, excluded_sources, excluded_idl): # Exclude excluded sources from being built. for f in excluded_sources: excluded_configs = [] - for config_name, config in spec['configurations'].iteritems(): + for config_name, config in spec['configurations'].items(): precomped = [_FixPath(config.get(i, '')) for i in precomp_keys] # Don't do this for ones that are precompiled header related. if f not in precomped: @@ -1596,7 +1596,7 @@ def _GetExcludedFilesFromBuild(spec, excluded_sources, excluded_idl): # Exclude them now. for f in excluded_idl: excluded_configs = [] - for config_name, config in spec['configurations'].iteritems(): + for config_name, config in spec['configurations'].items(): excluded_configs.append((config_name, config)) exclusions[f] = excluded_configs return exclusions @@ -1605,7 +1605,7 @@ def _GetExcludedFilesFromBuild(spec, excluded_sources, excluded_idl): def _AddToolFilesToMSVS(p, spec): # Add in tool files (rules). tool_files = OrderedSet() - for _, config in spec['configurations'].iteritems(): + for _, config in spec['configurations'].items(): for f in config.get('msvs_tool_files', []): tool_files.add(f) for f in tool_files: @@ -1618,7 +1618,7 @@ def _HandlePreCompiledHeaders(p, sources, spec): # kind (i.e. C vs. C++) as the precompiled header source stub needs # to have use of precompiled headers disabled. extensions_excluded_from_precompile = [] - for config_name, config in spec['configurations'].iteritems(): + for config_name, config in spec['configurations'].items(): source = config.get('msvs_precompiled_source') if source: source = _FixPath(source) @@ -1639,7 +1639,7 @@ def _HandlePreCompiledHeaders(p, sources, spec): else: basename, extension = os.path.splitext(source) if extension in extensions_excluded_from_precompile: - for config_name, config in spec['configurations'].iteritems(): + for config_name, config in spec['configurations'].items(): tool = MSVSProject.Tool('VCCLCompilerTool', {'UsePrecompiledHeader': '0', 'ForcedIncludeFiles': '$(NOINHERIT)'}) @@ -1690,7 +1690,7 @@ def _WriteMSVSUserFile(project_path, version, spec): return # Nothing to add # Write out the user file. user_file = _CreateMSVSUserFile(project_path, version, spec) - for config_name, c_data in spec['configurations'].iteritems(): + for config_name, c_data in spec['configurations'].items(): user_file.AddDebugSettings(_ConfigFullName(config_name, c_data), action, environment, working_directory) user_file.WriteIfChanged() @@ -1741,7 +1741,7 @@ def _GetPathDict(root, path): def _DictsToFolders(base_path, bucket, flat): # Convert to folders recursively. children = [] - for folder, contents in bucket.iteritems(): + for folder, contents in bucket.items(): if type(contents) == dict: folder_children = _DictsToFolders(os.path.join(base_path, folder), contents, flat) @@ -1763,8 +1763,8 @@ def _CollapseSingles(parent, node): # such projects up one level. if (type(node) == dict and len(node) == 1 and - node.keys()[0] == parent + '.vcproj'): - return node[node.keys()[0]] + list(node.keys())[0] == parent + '.vcproj'): + return node[list(node.keys())[0]] if type(node) != dict: return node for child in node: @@ -1783,8 +1783,8 @@ def _GatherSolutionFolders(sln_projects, project_objects, flat): # Walk down from the top until we hit a folder that has more than one entry. # In practice, this strips the top-level "src/" dir from the hierarchy in # the solution. - while len(root) == 1 and type(root[root.keys()[0]]) == dict: - root = root[root.keys()[0]] + while len(root) == 1 and type(root[list(root.keys())[0]]) == dict: + root = root[list(root.keys())[0]] # Collapse singles. root = _CollapseSingles('', root) # Merge buckets until everything is a root entry. @@ -1813,7 +1813,7 @@ def _GetPlatformOverridesOfProject(spec): # Prepare a dict indicating which project configurations are used for which # solution configurations for this target. config_platform_overrides = {} - for config_name, c in spec['configurations'].iteritems(): + for config_name, c in spec['configurations'].items(): config_fullname = _ConfigFullName(config_name, c) platform = c.get('msvs_target_platform', _ConfigPlatform(c)) fixed_config_fullname = '%s|%s' % ( @@ -1863,7 +1863,7 @@ def _CreateProjectObjects(target_list, target_dicts, options, msvs_version): projects[qualified_target] = obj # Set all the dependencies, but not if we are using an external builder like # ninja - for project in projects.values(): + for project in list(projects.values()): if not project.spec.get('msvs_external_builder'): deps = project.spec.get('dependencies', []) deps = [projects[d] for d in deps] @@ -1952,7 +1952,7 @@ def PerformBuild(data, configurations, params): msvs_version = params['msvs_version'] devenv = os.path.join(msvs_version.path, 'Common7', 'IDE', 'devenv.com') - for build_file, build_file_dict in data.iteritems(): + for build_file, build_file_dict in data.items(): (build_file_root, build_file_ext) = os.path.splitext(build_file) if build_file_ext != '.gyp': continue @@ -2014,7 +2014,7 @@ def GenerateOutput(target_list, target_dicts, data, params): configs = set() for qualified_target in target_list: spec = target_dicts[qualified_target] - for config_name, config in spec['configurations'].iteritems(): + for config_name, config in spec['configurations'].items(): configs.add(_ConfigFullName(config_name, config)) configs = list(configs) @@ -2024,7 +2024,7 @@ def GenerateOutput(target_list, target_dicts, data, params): # Generate each project. missing_sources = [] - for project in project_objects.values(): + for project in list(project_objects.values()): fixpath_prefix = project.fixpath_prefix missing_sources.extend(_GenerateProject(project, options, msvs_version, generator_flags)) @@ -2654,7 +2654,7 @@ def _GetConfigurationCondition(name, settings): def _GetMSBuildProjectConfigurations(configurations): group = ['ItemGroup', {'Label': 'ProjectConfigurations'}] - for (name, settings) in sorted(configurations.iteritems()): + for (name, settings) in sorted(configurations.items()): configuration, platform = _GetConfigurationAndPlatform(name, settings) designation = '%s|%s' % (configuration, platform) group.append( @@ -2706,7 +2706,7 @@ def _GetMSBuildGlobalProperties(spec, guid, gyp_file_name): platform_name = None msvs_windows_sdk_version = None - for configuration in spec['configurations'].itervalues(): + for configuration in spec['configurations'].values(): platform_name = platform_name or _ConfigPlatform(configuration) msvs_windows_sdk_version = (msvs_windows_sdk_version or _ConfigWindowsTargetPlatformVersion(configuration)) @@ -2724,7 +2724,7 @@ def _GetMSBuildGlobalProperties(spec, guid, gyp_file_name): def _GetMSBuildConfigurationDetails(spec, build_file): properties = {} - for name, settings in spec['configurations'].iteritems(): + for name, settings in spec['configurations'].items(): msbuild_attributes = _GetMSBuildAttributes(spec, settings, build_file) condition = _GetConfigurationCondition(name, settings) character_set = msbuild_attributes.get('CharacterSet') @@ -2758,7 +2758,7 @@ def _GetMSBuildPropertySheets(configurations): user_props = r'$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props' additional_props = {} props_specified = False - for name, settings in sorted(configurations.iteritems()): + for name, settings in sorted(configurations.items()): configuration = _GetConfigurationCondition(name, settings) if settings.has_key('msbuild_props'): additional_props[configuration] = _FixPaths(settings['msbuild_props']) @@ -2780,7 +2780,7 @@ def _GetMSBuildPropertySheets(configurations): ] else: sheets = [] - for condition, props in additional_props.iteritems(): + for condition, props in additional_props.items(): import_group = [ 'ImportGroup', {'Label': 'PropertySheets', @@ -2906,7 +2906,7 @@ def _GetMSBuildConfigurationGlobalProperties(spec, configurations, build_file): new_paths = '$(ExecutablePath);' + ';'.join(new_paths) properties = {} - for (name, configuration) in sorted(configurations.iteritems()): + for (name, configuration) in sorted(configurations.items()): condition = _GetConfigurationCondition(name, configuration) attributes = _GetMSBuildAttributes(spec, configuration, build_file) msbuild_settings = configuration['finalized_msbuild_settings'] @@ -2928,7 +2928,7 @@ def _GetMSBuildConfigurationGlobalProperties(spec, configurations, build_file): _AddConditionalProperty(properties, condition, 'ExecutablePath', new_paths) tool_settings = msbuild_settings.get('', {}) - for name, value in sorted(tool_settings.iteritems()): + for name, value in sorted(tool_settings.items()): formatted_value = _GetValueFormattedForMSBuild('', name, value) _AddConditionalProperty(properties, condition, name, formatted_value) return _GetMSBuildPropertyGroup(spec, None, properties) @@ -2990,14 +2990,14 @@ def _GetMSBuildPropertyGroup(spec, label, properties): if v in properties and v != node])) return edges properties_ordered = gyp.common.TopologicallySorted( - properties.keys(), GetEdges) + list(properties.keys()), GetEdges) # Walk properties in the reverse of a topological sort on # user_of_variable -> used_variable as this ensures variables are # defined before they are used. # NOTE: reverse(topsort(DAG)) = topsort(reverse_edges(DAG)) for name in reversed(properties_ordered): values = properties[name] - for value, conditions in sorted(values.iteritems()): + for value, conditions in sorted(values.items()): if len(conditions) == num_configurations: # If the value is the same all configurations, # just add one unconditional entry. @@ -3010,18 +3010,18 @@ def _GetMSBuildPropertyGroup(spec, label, properties): def _GetMSBuildToolSettingsSections(spec, configurations): groups = [] - for (name, configuration) in sorted(configurations.iteritems()): + for (name, configuration) in sorted(configurations.items()): msbuild_settings = configuration['finalized_msbuild_settings'] group = ['ItemDefinitionGroup', {'Condition': _GetConfigurationCondition(name, configuration)} ] - for tool_name, tool_settings in sorted(msbuild_settings.iteritems()): + for tool_name, tool_settings in sorted(msbuild_settings.items()): # Skip the tool named '' which is a holder of global settings handled # by _GetMSBuildConfigurationGlobalProperties. if tool_name: if tool_settings: tool = [tool_name] - for name, value in sorted(tool_settings.iteritems()): + for name, value in sorted(tool_settings.items()): formatted_value = _GetValueFormattedForMSBuild(tool_name, name, value) tool.append([name, formatted_value]) @@ -3221,7 +3221,7 @@ def _AddSources2(spec, sources, exclusions, grouped_sources, {'Condition': condition}, 'true']) # Add precompile if needed - for config_name, configuration in spec['configurations'].iteritems(): + for config_name, configuration in spec['configurations'].items(): precompiled_source = configuration.get('msvs_precompiled_source', '') if precompiled_source != '': precompiled_source = _FixPath(precompiled_source) @@ -3267,7 +3267,7 @@ def _GetMSBuildProjectReferences(project): ['Project', guid], ['ReferenceOutputAssembly', 'false'] ] - for config in dependency.spec.get('configurations', {}).itervalues(): + for config in dependency.spec.get('configurations', {}).values(): # If it's disabled in any config, turn it off in the reference. if config.get('msvs_2010_disable_uldi_when_referenced', 0): project_ref.append(['UseLibraryDependencyInputs', 'false']) @@ -3333,7 +3333,7 @@ def _GenerateMSBuildProject(project, options, version, generator_flags): extension_to_rule_name) missing_sources = _VerifySourcesExist(sources, project_dir) - for configuration in configurations.itervalues(): + for configuration in configurations.values(): _FinalizeMSBuildSettings(spec, configuration) # Add attributes to root element @@ -3458,7 +3458,7 @@ def _GenerateActionsForMSBuild(spec, actions_to_add): """ sources_handled_by_action = OrderedSet() actions_spec = [] - for primary_input, actions in actions_to_add.iteritems(): + for primary_input, actions in actions_to_add.items(): inputs = OrderedSet() outputs = OrderedSet() descriptions = [] diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/ninja.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/ninja.py index d16e2df410..e1e920c305 100644 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/ninja.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/ninja.py @@ -838,7 +838,7 @@ class NinjaWriter(object): 'XCASSETS_LAUNCH_IMAGE': 'launch-image', } settings = self.xcode_settings.xcode_settings[self.config_name] - for settings_key, arg_name in settings_to_arg.iteritems(): + for settings_key, arg_name in settings_to_arg.items(): value = settings.get(settings_key) if value: extra_arguments[arg_name] = value @@ -1943,7 +1943,7 @@ def GenerateOutputForConfig(target_list, target_dicts, data, params, wrappers[key[:-len('_wrapper')]] = os.path.join(build_to_root, value) # Support wrappers from environment variables too. - for key, value in os.environ.iteritems(): + for key, value in os.environ.items(): if key.lower().endswith('_wrapper'): key_prefix = key[:-len('_wrapper')] key_prefix = re.sub(r'\.HOST$', '.host', key_prefix) @@ -1963,7 +1963,7 @@ def GenerateOutputForConfig(target_list, target_dicts, data, params, configs, generator_flags) cl_paths = gyp.msvs_emulation.GenerateEnvironmentFiles( toplevel_build, generator_flags, shared_system_includes, OpenOutput) - for arch, path in sorted(cl_paths.iteritems()): + for arch, path in sorted(cl_paths.items()): if clang_cl: # If we have selected clang-cl, use that instead. path = clang_cl @@ -2465,7 +2465,7 @@ def GenerateOutput(target_list, target_dicts, data, params): GenerateOutputForConfig(target_list, target_dicts, data, params, user_config) else: - config_names = target_dicts[target_list[0]]['configurations'].keys() + config_names = list(target_dicts[target_list[0]]['configurations'].keys()) if params['parallel']: try: pool = multiprocessing.Pool(len(config_names)) diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/xcode.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/xcode.py index 168c026323..233b3bbc09 100644 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/xcode.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/generator/xcode.py @@ -183,7 +183,7 @@ class XcodeProject(object): # the tree tree view for UI display. # Any values set globally are applied to all configurations, then any # per-configuration values are applied. - for xck, xcv in self.build_file_dict.get('xcode_settings', {}).iteritems(): + for xck, xcv in self.build_file_dict.get('xcode_settings', {}).items(): xccl.SetBuildSetting(xck, xcv) if 'xcode_config_file' in self.build_file_dict: config_ref = self.project.AddOrGetFileInRootGroup( @@ -197,7 +197,7 @@ class XcodeProject(object): if build_file_configuration_named: xcc = xccl.ConfigurationNamed(config_name) for xck, xcv in build_file_configuration_named.get('xcode_settings', - {}).iteritems(): + {}).items(): xcc.SetBuildSetting(xck, xcv) if 'xcode_config_file' in build_file_configuration_named: config_ref = self.project.AddOrGetFileInRootGroup( @@ -273,7 +273,7 @@ class XcodeProject(object): script = script + "\n".join( ['export %s="%s"' % (key, gyp.xcodeproj_file.ConvertVariablesToShellSyntax(val)) - for (key, val) in command.get('environment').iteritems()]) + "\n" + for (key, val) in command.get('environment').items()]) + "\n" # Some test end up using sockets, files on disk, etc. and can get # confused if more then one test runs at a time. The generator @@ -408,7 +408,7 @@ sys.exit(subprocess.call(sys.argv[1:]))" """ # it opens the project file, which will result in unnecessary diffs. # TODO(mark): This is evil because it relies on internal knowledge of # PBXProject._other_pbxprojects. - for other_pbxproject in self.project._other_pbxprojects.keys(): + for other_pbxproject in list(self.project._other_pbxprojects.keys()): self.project.AddOrGetProjectReference(other_pbxproject) self.project.SortRemoteProductReferences() @@ -566,7 +566,7 @@ def EscapeXcodeDefine(s): def PerformBuild(data, configurations, params): options = params['options'] - for build_file, build_file_dict in data.iteritems(): + for build_file, build_file_dict in data.items(): (build_file_root, build_file_ext) = os.path.splitext(build_file) if build_file_ext != '.gyp': continue @@ -625,7 +625,7 @@ def GenerateOutput(target_list, target_dicts, data, params): skip_excluded_files = \ not generator_flags.get('xcode_list_excluded_files', True) xcode_projects = {} - for build_file, build_file_dict in data.iteritems(): + for build_file, build_file_dict in data.items(): (build_file_root, build_file_ext) = os.path.splitext(build_file) if build_file_ext != '.gyp': continue @@ -1288,7 +1288,7 @@ exit 1 set_define = EscapeXcodeDefine(define) xcbc.AppendBuildSetting('GCC_PREPROCESSOR_DEFINITIONS', set_define) if 'xcode_settings' in configuration: - for xck, xcv in configuration['xcode_settings'].iteritems(): + for xck, xcv in configuration['xcode_settings'].items(): xcbc.SetBuildSetting(xck, xcv) if 'xcode_config_file' in configuration: config_ref = pbxp.AddOrGetFileInRootGroup( @@ -1296,7 +1296,7 @@ exit 1 xcbc.SetBaseConfiguration(config_ref) build_files = [] - for build_file, build_file_dict in data.iteritems(): + for build_file, build_file_dict in data.items(): if build_file.endswith('.gyp'): build_files.append(build_file) diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/input.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/input.py index 355e5d6195..fe62de0c31 100644 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/input.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/input.py @@ -302,7 +302,7 @@ def LoadBuildFileIncludesIntoDict(subdict, subdict_path, data, aux_data, subdict_path, include) # Recurse into subdictionaries. - for k, v in subdict.iteritems(): + for k, v in subdict.items(): if type(v) is dict: LoadBuildFileIncludesIntoDict(v, subdict_path, data, aux_data, None, check) @@ -488,7 +488,7 @@ def CallLoadTargetBuildFile(global_flags, signal.signal(signal.SIGINT, signal.SIG_IGN) # Apply globals so that the worker process behaves the same. - for key, value in global_flags.iteritems(): + for key, value in global_flags.items(): globals()[key] = value SetGeneratorGlobals(generator_input_info) @@ -1151,7 +1151,7 @@ def ProcessConditionsInDict(the_dict, phase, variables, build_file): def LoadAutomaticVariablesFromDict(variables, the_dict): # Any keys with plain string values in the_dict become automatic variables. # The variable name is the key name with a "_" character prepended. - for key, value in the_dict.iteritems(): + for key, value in the_dict.items(): if type(value) in (str, int, list): variables['_' + key] = value @@ -1164,7 +1164,7 @@ def LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key): # the_dict in the_dict's parent dict. If the_dict's parent is not a dict # (it could be a list or it could be parentless because it is a root dict), # the_dict_key will be None. - for key, value in the_dict.get('variables', {}).iteritems(): + for key, value in the_dict.get('variables', {}).items(): if type(value) not in (str, int, list): continue @@ -1203,7 +1203,7 @@ def ProcessVariablesAndConditionsInDict(the_dict, phase, variables_in, # list before we process them so that you can reference one # variable from another. They will be fully expanded by recursion # in ExpandVariables. - for key, value in the_dict['variables'].iteritems(): + for key, value in the_dict['variables'].items(): variables[key] = value # Handle the associated variables dict first, so that any variable @@ -1216,7 +1216,7 @@ def ProcessVariablesAndConditionsInDict(the_dict, phase, variables_in, LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key) - for key, value in the_dict.iteritems(): + for key, value in the_dict.items(): # Skip "variables", which was already processed if present. if key != 'variables' and type(value) is str: expanded = ExpandVariables(value, phase, variables, build_file) @@ -1274,7 +1274,7 @@ def ProcessVariablesAndConditionsInDict(the_dict, phase, variables_in, # Recurse into child dicts, or process child lists which may result in # further recursion into descendant dicts. - for key, value in the_dict.iteritems(): + for key, value in the_dict.items(): # Skip "variables" and string values, which were already processed if # present. if key == 'variables' or type(value) is str: @@ -1371,7 +1371,7 @@ def QualifyDependencies(targets): for dep in dependency_sections for op in ('', '!', '/')] - for target, target_dict in targets.iteritems(): + for target, target_dict in targets.items(): target_build_file = gyp.common.BuildFile(target) toolset = target_dict['toolset'] for dependency_key in all_dependency_sections: @@ -1411,7 +1411,7 @@ def ExpandWildcardDependencies(targets, data): dependency list, must be qualified when this function is called. """ - for target, target_dict in targets.iteritems(): + for target, target_dict in targets.items(): toolset = target_dict['toolset'] target_build_file = gyp.common.BuildFile(target) for dependency_key in dependency_sections: @@ -1473,7 +1473,7 @@ def Unify(l): def RemoveDuplicateDependencies(targets): """Makes sure every dependency appears only once in all targets's dependency lists.""" - for target_name, target_dict in targets.iteritems(): + for target_name, target_dict in targets.items(): for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) if dependencies: @@ -1489,7 +1489,7 @@ def Filter(l, item): def RemoveSelfDependencies(targets): """Remove self dependencies from targets that have the prune_self_dependency variable set.""" - for target_name, target_dict in targets.iteritems(): + for target_name, target_dict in targets.items(): for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) if dependencies: @@ -1502,7 +1502,7 @@ def RemoveSelfDependencies(targets): def RemoveLinkDependenciesFromNoneTargets(targets): """Remove dependencies having the 'link_dependency' attribute from the 'none' targets.""" - for target_name, target_dict in targets.iteritems(): + for target_name, target_dict in targets.items(): for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) if dependencies: @@ -1794,14 +1794,14 @@ def BuildDependencyList(targets): # Create a DependencyGraphNode for each target. Put it into a dict for easy # access. dependency_nodes = {} - for target, spec in targets.iteritems(): + for target, spec in targets.items(): if target not in dependency_nodes: dependency_nodes[target] = DependencyGraphNode(target) # Set up the dependency links. Targets that have no dependencies are treated # as dependent on root_node. root_node = DependencyGraphNode(None) - for target, spec in targets.iteritems(): + for target, spec in targets.items(): target_node = dependency_nodes[target] target_build_file = gyp.common.BuildFile(target) dependencies = spec.get('dependencies') @@ -1825,7 +1825,7 @@ def BuildDependencyList(targets): if not root_node.dependents: # If all targets have dependencies, add the first target as a dependent # of root_node so that the cycle can be discovered from root_node. - target = targets.keys()[0] + target = list(targets.keys())[0] target_node = dependency_nodes[target] target_node.dependencies.append(root_node) root_node.dependents.append(target_node) @@ -1844,13 +1844,13 @@ def VerifyNoGYPFileCircularDependencies(targets): # Create a DependencyGraphNode for each gyp file containing a target. Put # it into a dict for easy access. dependency_nodes = {} - for target in targets.iterkeys(): + for target in targets.keys(): build_file = gyp.common.BuildFile(target) if not build_file in dependency_nodes: dependency_nodes[build_file] = DependencyGraphNode(build_file) # Set up the dependency links. - for target, spec in targets.iteritems(): + for target, spec in targets.items(): build_file = gyp.common.BuildFile(target) build_file_node = dependency_nodes[build_file] target_dependencies = spec.get('dependencies', []) @@ -1875,7 +1875,7 @@ def VerifyNoGYPFileCircularDependencies(targets): # Files that have no dependencies are treated as dependent on root_node. root_node = DependencyGraphNode(None) - for build_file_node in dependency_nodes.itervalues(): + for build_file_node in dependency_nodes.values(): if len(build_file_node.dependencies) == 0: build_file_node.dependencies.append(root_node) root_node.dependents.append(build_file_node) @@ -1888,7 +1888,7 @@ def VerifyNoGYPFileCircularDependencies(targets): if not root_node.dependents: # If all files have dependencies, add the first file as a dependent # of root_node so that the cycle can be discovered from root_node. - file_node = dependency_nodes.values()[0] + file_node = list(dependency_nodes.values())[0] file_node.dependencies.append(root_node) root_node.dependents.append(file_node) cycles = [] @@ -2115,7 +2115,7 @@ def MergeLists(to, fro, to_file, fro_file, is_paths=False, append=True): def MergeDicts(to, fro, to_file, fro_file): # I wanted to name the parameter "from" but it's a Python keyword... - for k, v in fro.iteritems(): + for k, v in fro.items(): # It would be nice to do "if not k in to: to[k] = v" but that wouldn't give # copy semantics. Something else may want to merge from the |fro| dict # later, and having the same dict ref pointed to twice in the tree isn't @@ -2250,13 +2250,13 @@ def SetUpConfigurations(target, target_dict): if not 'configurations' in target_dict: target_dict['configurations'] = {'Default': {}} if not 'default_configuration' in target_dict: - concrete = [i for (i, config) in target_dict['configurations'].iteritems() + concrete = [i for (i, config) in target_dict['configurations'].items() if not config.get('abstract')] target_dict['default_configuration'] = sorted(concrete)[0] merged_configurations = {} configs = target_dict['configurations'] - for (configuration, old_configuration_dict) in configs.iteritems(): + for (configuration, old_configuration_dict) in configs.items(): # Skip abstract configurations (saves work only). if old_configuration_dict.get('abstract'): continue @@ -2264,7 +2264,7 @@ def SetUpConfigurations(target, target_dict): # Get the inheritance relationship right by making a copy of the target # dict. new_configuration_dict = {} - for (key, target_val) in target_dict.iteritems(): + for (key, target_val) in target_dict.items(): key_ext = key[-1:] if key_ext in key_suffixes: key_base = key[:-1] @@ -2280,12 +2280,12 @@ def SetUpConfigurations(target, target_dict): merged_configurations[configuration] = new_configuration_dict # Put the new configurations back into the target dict as a configuration. - for configuration in merged_configurations.keys(): + for configuration in list(merged_configurations.keys()): target_dict['configurations'][configuration] = ( merged_configurations[configuration]) # Now drop all the abstract ones. - for configuration in target_dict['configurations'].keys(): + for configuration in list(target_dict['configurations'].keys()): old_configuration_dict = target_dict['configurations'][configuration] if old_configuration_dict.get('abstract'): del target_dict['configurations'][configuration] @@ -2306,9 +2306,9 @@ def SetUpConfigurations(target, target_dict): del target_dict[key] # Check the configurations to see if they contain invalid keys. - for configuration in target_dict['configurations'].keys(): + for configuration in list(target_dict['configurations'].keys()): configuration_dict = target_dict['configurations'][configuration] - for key in configuration_dict.keys(): + for key in list(configuration_dict.keys()): if key in invalid_configuration_keys: raise GypError('%s not allowed in the %s configuration, found in ' 'target %s' % (key, configuration, target)) @@ -2348,7 +2348,7 @@ def ProcessListFiltersInDict(name, the_dict): lists = [] del_lists = [] - for key, value in the_dict.iteritems(): + for key, value in the_dict.items(): operation = key[-1] if operation != '!' and operation != '/': continue @@ -2466,7 +2466,7 @@ def ProcessListFiltersInDict(name, the_dict): the_dict[excluded_key] = excluded_list # Now recurse into subdicts and lists that may contain dicts. - for key, value in the_dict.iteritems(): + for key, value in the_dict.items(): if type(value) is dict: ProcessListFiltersInDict(key, value) elif type(value) is list: @@ -2523,7 +2523,7 @@ def ValidateSourcesInTarget(target, target_dict, build_file, basenames.setdefault(basename, []).append(source) error = '' - for basename, files in basenames.iteritems(): + for basename, files in basenames.items(): if len(files) > 1: error += ' %s: %s\n' % (basename, ' '.join(files)) @@ -2645,7 +2645,7 @@ def TurnIntIntoStrInDict(the_dict): """ # Use items instead of iteritems because there's no need to try to look at # reinserted keys and their associated values. - for k, v in the_dict.items(): + for k, v in list(the_dict.items()): if type(v) is int: v = str(v) the_dict[k] = v @@ -2802,7 +2802,7 @@ def Load(build_files, variables, includes, depth, generator_input_info, check, RemoveLinkDependenciesFromNoneTargets(targets) # Apply exclude (!) and regex (/) list filters only for dependency_sections. - for target_name, target_dict in targets.iteritems(): + for target_name, target_dict in targets.items(): tmp_dict = {} for key_base in dependency_sections: for op in ('', '!', '/'): diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/input_test.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/input_test.py index 4234fbb830..6c4b1cc526 100755 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/input_test.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/input_test.py @@ -22,7 +22,7 @@ class TestFindCycles(unittest.TestCase): dependency.dependents.append(dependent) def test_no_cycle_empty_graph(self): - for label, node in self.nodes.iteritems(): + for label, node in self.nodes.items(): self.assertEquals([], node.FindCycles()) def test_no_cycle_line(self): @@ -30,7 +30,7 @@ class TestFindCycles(unittest.TestCase): self._create_dependency(self.nodes['b'], self.nodes['c']) self._create_dependency(self.nodes['c'], self.nodes['d']) - for label, node in self.nodes.iteritems(): + for label, node in self.nodes.items(): self.assertEquals([], node.FindCycles()) def test_no_cycle_dag(self): @@ -38,7 +38,7 @@ class TestFindCycles(unittest.TestCase): self._create_dependency(self.nodes['a'], self.nodes['c']) self._create_dependency(self.nodes['b'], self.nodes['c']) - for label, node in self.nodes.iteritems(): + for label, node in self.nodes.items(): self.assertEquals([], node.FindCycles()) def test_cycle_self_reference(self): diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/mac_tool.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/mac_tool.py index 395489e3b4..031ff49227 100755 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/mac_tool.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/mac_tool.py @@ -170,7 +170,7 @@ class MacTool(object): # Insert synthesized key/value pairs (e.g. BuildMachineOSBuild). plist = plistlib.readPlistFromString(lines) if keys: - plist = dict(plist.items() + json.loads(keys[0]).items()) + plist = dict(list(plist.items()) + list(json.loads(keys[0]).items())) lines = plistlib.writePlistToString(plist) # Go through all the environment variables and replace them as variables in @@ -381,7 +381,7 @@ class MacTool(object): ]) if keys: keys = json.loads(keys) - for key, value in keys.iteritems(): + for key, value in keys.items(): arg_name = '--' + key if isinstance(value, bool): if value: @@ -523,7 +523,7 @@ class MacTool(object): def _MergePlist(self, merged_plist, plist): """Merge |plist| into |merged_plist|.""" - for key, value in plist.iteritems(): + for key, value in plist.items(): if isinstance(value, dict): merged_value = merged_plist.get(key, {}) if isinstance(merged_value, dict): @@ -633,7 +633,7 @@ class MacTool(object): the key was not found. """ if isinstance(data, str): - for key, value in substitutions.iteritems(): + for key, value in substitutions.items(): data = data.replace('$(%s)' % key, value) return data if isinstance(data, list): @@ -663,7 +663,7 @@ def WriteHmap(output_name, filelist): count = len(filelist) capacity = NextGreaterPowerOf2(count) strings_offset = 24 + (12 * capacity) - max_value_length = len(max(filelist.items(), key=lambda (k,v):len(v))[1]) + max_value_length = len(max(list(filelist.items()), key=lambda (k,v):len(v))[1]) out = open(output_name, "wb") out.write(struct.pack(' None. Remove all items from od.' try: - for node in self.__map.itervalues(): + for node in self.__map.values(): del node[:] root = self.__root root[:] = [root, root, None] @@ -191,12 +191,12 @@ class OrderedDict(dict): for key in other: self[key] = other[key] elif hasattr(other, 'keys'): - for key in other.keys(): + for key in list(other.keys()): self[key] = other[key] else: for key, value in other: self[key] = value - for key, value in kwds.items(): + for key, value in list(kwds.items()): self[key] = value __update = update # let subclasses override update without breaking __init__ @@ -232,7 +232,7 @@ class OrderedDict(dict): try: if not self: return '%s()' % (self.__class__.__name__,) - return '%s(%r)' % (self.__class__.__name__, self.items()) + return '%s(%r)' % (self.__class__.__name__, list(self.items())) finally: del _repr_running[call_key] @@ -267,7 +267,7 @@ class OrderedDict(dict): ''' if isinstance(other, OrderedDict): - return len(self)==len(other) and self.items() == other.items() + return len(self)==len(other) and list(self.items()) == list(other.items()) return dict.__eq__(self, other) def __ne__(self, other): diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/simple_copy.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/simple_copy.py index 74c98c5a79..463929386e 100644 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/simple_copy.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/simple_copy.py @@ -38,7 +38,7 @@ d[list] = _deepcopy_list def _deepcopy_dict(x): y = {} - for key, value in x.iteritems(): + for key, value in x.items(): y[deepcopy(key)] = deepcopy(value) return y d[dict] = _deepcopy_dict diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/win_tool.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/win_tool.py index 35d995714f..bfb887232f 100755 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/win_tool.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/win_tool.py @@ -300,7 +300,7 @@ class WinTool(object): env = self._GetEnv(arch) # TODO(scottmg): This is a temporary hack to get some specific variables # through to actions that are set after gyp-time. http://crbug.com/333738. - for k, v in os.environ.iteritems(): + for k, v in os.environ.items(): if k not in env: env[k] = v args = open(rspfile).read() diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/xcode_emulation.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/xcode_emulation.py index 948759d7c7..2a7202e713 100644 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/xcode_emulation.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/xcode_emulation.py @@ -171,7 +171,7 @@ class XcodeSettings(object): # the same for all configs are implicitly per-target settings. self.xcode_settings = {} configs = spec['configurations'] - for configname, config in configs.iteritems(): + for configname, config in configs.items(): self.xcode_settings[configname] = config.get('xcode_settings', {}) self._ConvertConditionalKeys(configname) if self.xcode_settings[configname].get('IPHONEOS_DEPLOYMENT_TARGET', @@ -963,7 +963,7 @@ class XcodeSettings(object): result = dict(self.xcode_settings[configname]) first_pass = False else: - for key, value in self.xcode_settings[configname].iteritems(): + for key, value in self.xcode_settings[configname].items(): if key not in result: continue elif result[key] != value: @@ -1462,7 +1462,7 @@ def MergeGlobalXcodeSettingsToSpec(global_dict, spec): # that amounts to merging in the global xcode_settings into each local # xcode_settings dict. global_xcode_settings = global_dict.get('xcode_settings', {}) - for config in spec['configurations'].values(): + for config in list(spec['configurations'].values()): if 'xcode_settings' in config: new_settings = global_xcode_settings.copy() new_settings.update(config['xcode_settings']) @@ -1734,7 +1734,7 @@ def _TopologicallySortedEnvVarKeys(env): # Topologically sort, and then reverse, because we used an edge definition # that's inverted from the expected result of this function (see comment # above). - order = gyp.common.TopologicallySorted(env.keys(), GetEdges) + order = gyp.common.TopologicallySorted(list(env.keys()), GetEdges) order.reverse() return order except gyp.common.CycleError, e: @@ -1764,8 +1764,8 @@ def GetSpecPostbuildCommands(spec, quiet=False): def _HasIOSTarget(targets): """Returns true if any target contains the iOS specific key IPHONEOS_DEPLOYMENT_TARGET.""" - for target_dict in targets.values(): - for config in target_dict['configurations'].values(): + for target_dict in list(targets.values()): + for config in list(target_dict['configurations'].values()): if config.get('xcode_settings', {}).get('IPHONEOS_DEPLOYMENT_TARGET'): return True return False @@ -1774,10 +1774,10 @@ def _HasIOSTarget(targets): def _AddIOSDeviceConfigurations(targets): """Clone all targets and append -iphoneos to the name. Configure these targets to build for iOS devices and use correct architectures for those builds.""" - for target_dict in targets.itervalues(): + for target_dict in targets.values(): toolset = target_dict['toolset'] configs = target_dict['configurations'] - for config_name, simulator_config_dict in dict(configs).iteritems(): + for config_name, simulator_config_dict in dict(configs).items(): iphoneos_config_dict = copy.deepcopy(simulator_config_dict) configs[config_name + '-iphoneos'] = iphoneos_config_dict configs[config_name + '-iphonesimulator'] = simulator_config_dict diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/xcode_ninja.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/xcode_ninja.py index bc76ffff4e..b2ad90d99e 100644 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/xcode_ninja.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/xcode_ninja.py @@ -85,7 +85,7 @@ def _TargetFromSpec(old_spec, params): "%s/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)" % ninja_toplevel if 'configurations' in old_spec: - for config in old_spec['configurations'].iterkeys(): + for config in old_spec['configurations'].keys(): old_xcode_settings = \ old_spec['configurations'][config].get('xcode_settings', {}) if 'IPHONEOS_DEPLOYMENT_TARGET' in old_xcode_settings: @@ -167,7 +167,7 @@ def CreateWrapper(target_list, target_dicts, data, params): params: Dict of global options for gyp. """ orig_gyp = params['build_files'][0] - for gyp_name, gyp_dict in data.iteritems(): + for gyp_name, gyp_dict in data.items(): if gyp_name == orig_gyp: depth = gyp_dict['_DEPTH'] @@ -238,7 +238,7 @@ def CreateWrapper(target_list, target_dicts, data, params): not generator_flags.get('xcode_ninja_list_excluded_files', True) sources = [] - for target, target_dict in target_dicts.iteritems(): + for target, target_dict in target_dicts.items(): base = os.path.dirname(target) files = target_dict.get('sources', []) + \ target_dict.get('mac_bundle_resources', []) diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/xcodeproj_file.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/xcodeproj_file.py index 1e2b2aa805..79509d6ef2 100644 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/xcodeproj_file.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/xcodeproj_file.py @@ -314,7 +314,7 @@ class XCObject(object): """ that = self.__class__(id=self.id, parent=self.parent) - for key, value in self._properties.iteritems(): + for key, value in self._properties.items(): is_strong = self._schema[key][2] if isinstance(value, XCObject): @@ -475,7 +475,7 @@ class XCObject(object): """Returns a list of all of this object's owned (strong) children.""" children = [] - for property, attributes in self._schema.iteritems(): + for property, attributes in self._schema.items(): (is_list, property_type, is_strong) = attributes[0:3] if is_strong and property in self._properties: if not is_list: @@ -622,7 +622,7 @@ class XCObject(object): printable += end_tabs + ')' elif isinstance(value, dict): printable = '{' + sep - for item_key, item_value in sorted(value.iteritems()): + for item_key, item_value in sorted(value.items()): printable += element_tabs + \ self._XCPrintableValue(tabs + 1, item_key, flatten_list) + ' = ' + \ self._XCPrintableValue(tabs + 1, item_value, flatten_list) + ';' + \ @@ -730,7 +730,7 @@ class XCObject(object): self._XCKVPrint(file, 3, 'isa', self.__class__.__name__) # The remaining elements of an object dictionary are sorted alphabetically. - for property, value in sorted(self._properties.iteritems()): + for property, value in sorted(self._properties.items()): self._XCKVPrint(file, 3, property, value) # End the object. @@ -752,7 +752,7 @@ class XCObject(object): if properties is None: return - for property, value in properties.iteritems(): + for property, value in properties.items(): # Make sure the property is in the schema. if not property in self._schema: raise KeyError(property + ' not in ' + self.__class__.__name__) @@ -865,7 +865,7 @@ class XCObject(object): # TODO(mark): A stronger verification mechanism is needed. Some # subclasses need to perform validation beyond what the schema can enforce. - for property, attributes in self._schema.iteritems(): + for property, attributes in self._schema.items(): (is_list, property_type, is_strong, is_required) = attributes[0:4] if is_required and not property in self._properties: raise KeyError(self.__class__.__name__ + ' requires ' + property) @@ -875,7 +875,7 @@ class XCObject(object): overwrite properties that have already been set.""" defaults = {} - for property, attributes in self._schema.iteritems(): + for property, attributes in self._schema.items(): (is_list, property_type, is_strong, is_required) = attributes[0:4] if is_required and len(attributes) >= 5 and \ not property in self._properties: @@ -2911,7 +2911,7 @@ class PBXProject(XCContainerPortal): # determine the sort order. return cmp(x_index, y_index) - for other_pbxproject, ref_dict in self._other_pbxprojects.iteritems(): + for other_pbxproject, ref_dict in self._other_pbxprojects.items(): # Build up a list of products in the remote project file, ordered the # same as the targets that produce them. remote_products = [] @@ -2956,7 +2956,7 @@ class XCProjectFile(XCObject): self._XCPrint(file, 0, '{ ') else: self._XCPrint(file, 0, '{\n') - for property, value in sorted(self._properties.iteritems(), + for property, value in sorted(iter(self._properties.items()), cmp=lambda x, y: cmp(x, y)): if property == 'objects': self._PrintObjects(file) diff --git a/media/webrtc/trunk/tools/gyp/pylib/gyp/xml_fix.py b/media/webrtc/trunk/tools/gyp/pylib/gyp/xml_fix.py index 5de848158d..14436da41c 100644 --- a/media/webrtc/trunk/tools/gyp/pylib/gyp/xml_fix.py +++ b/media/webrtc/trunk/tools/gyp/pylib/gyp/xml_fix.py @@ -32,7 +32,7 @@ def _Replacement_writexml(self, writer, indent="", addindent="", newl=""): writer.write(indent+"<" + self.tagName) attrs = self._get_attributes() - a_names = attrs.keys() + a_names = list(attrs.keys()) a_names.sort() for a_name in a_names: diff --git a/media/webrtc/trunk/tools/gyp/tools/graphviz.py b/media/webrtc/trunk/tools/gyp/tools/graphviz.py index 99c5a5c6dc..c7d921352c 100755 --- a/media/webrtc/trunk/tools/gyp/tools/graphviz.py +++ b/media/webrtc/trunk/tools/gyp/tools/graphviz.py @@ -46,7 +46,7 @@ def WriteGraph(edges): # Bucket targets by file. files = collections.defaultdict(list) - for src, dst in edges.items(): + for src, dst in list(edges.items()): build_file, target_name, toolset = ParseTarget(src) files[build_file].append(src) @@ -57,7 +57,7 @@ def WriteGraph(edges): # Output nodes by file. We must first write out each node within # its file grouping before writing out any edges that may refer # to those nodes. - for filename, targets in files.items(): + for filename, targets in list(files.items()): if len(targets) == 1: # If there's only one node for this file, simplify # the display by making it a box without an internal node. @@ -76,7 +76,7 @@ def WriteGraph(edges): # Now that we've placed all the nodes within subgraphs, output all # the edges between nodes. - for src, dsts in edges.items(): + for src, dsts in list(edges.items()): for dst in dsts: print(' "%s" -> "%s"' % (src, dst)) diff --git a/media/webrtc/trunk/tools/gyp/tools/pretty_vcproj.py b/media/webrtc/trunk/tools/gyp/tools/pretty_vcproj.py index 7fea25122b..5e1b822bd9 100755 --- a/media/webrtc/trunk/tools/gyp/tools/pretty_vcproj.py +++ b/media/webrtc/trunk/tools/gyp/tools/pretty_vcproj.py @@ -45,7 +45,7 @@ class CmpNode(object): node_string += node.getAttribute("Name") all_nodes = [] - for (name, value) in node.attributes.items(): + for (name, value) in list(node.attributes.items()): all_nodes.append((name, value)) all_nodes.sort(CmpTuple()) @@ -78,7 +78,7 @@ def PrettyPrintNode(node, indent=0): print('%s<%s' % (' '*indent, node.nodeName)) all_attributes = [] - for (name, value) in node.attributes.items(): + for (name, value) in list(node.attributes.items()): all_attributes.append((name, value)) all_attributes.sort(CmpTuple()) for (name, value) in all_attributes: @@ -128,7 +128,7 @@ def FixFilenames(filenames, current_directory): def AbsoluteNode(node): """Makes all the properties we know about in this node absolute.""" if node.attributes: - for (name, value) in node.attributes.items(): + for (name, value) in list(node.attributes.items()): if name in ['InheritedPropertySheets', 'RelativePath', 'AdditionalIncludeDirectories', 'IntermediateDirectory', 'OutputDirectory', @@ -157,7 +157,7 @@ def CleanupVcproj(node): # Fix all the semicolon separated attributes to be sorted, and we also # remove the dups. if node.attributes: - for (name, value) in node.attributes.items(): + for (name, value) in list(node.attributes.items()): sorted_list = sorted(value.split(';')) unique_list = [] for i in sorted_list: @@ -246,7 +246,7 @@ def MergeAttributes(node1, node2): if not node2.attributes: return - for (name, value2) in node2.attributes.items(): + for (name, value2) in list(node2.attributes.items()): # Don't merge the 'Name' attribute. if name == 'Name': continue diff --git a/other-licenses/ply/ply/lex.py b/other-licenses/ply/ply/lex.py index 267ec100fc..ea3aa86c12 100644 --- a/other-licenses/ply/ply/lex.py +++ b/other-licenses/ply/ply/lex.py @@ -147,7 +147,7 @@ class Lexer: if object: newtab = { } - for key, ritem in self.lexstatere.items(): + for key, ritem in list(self.lexstatere.items()): newre = [] for cre, findex in ritem: newfindex = [] @@ -160,7 +160,7 @@ class Lexer: newtab[key] = newre c.lexstatere = newtab c.lexstateerrorf = { } - for key, ef in self.lexstateerrorf.items(): + for key, ef in list(self.lexstateerrorf.items()): c.lexstateerrorf[key] = getattr(object,ef.__name__) c.lexmodule = object return c @@ -190,7 +190,7 @@ class Lexer: if f and f[0]: initialfuncs.append(f) - for key, lre in self.lexstatere.items(): + for key, lre in list(self.lexstatere.items()): titem = [] for i in range(len(lre)): titem.append((self.lexstateretext[key][i],_funcs_to_names(lre[i][1],self.lexstaterenames[key][i]))) @@ -200,7 +200,7 @@ class Lexer: tf.write("_lexstateignore = %s\n" % repr(self.lexstateignore)) taberr = { } - for key, ef in self.lexstateerrorf.items(): + for key, ef in list(self.lexstateerrorf.items()): if ef: taberr[key] = ef.__name__ else: @@ -232,7 +232,7 @@ class Lexer: self.lexstateignore = lextab._lexstateignore self.lexstatere = { } self.lexstateretext = { } - for key,lre in lextab._lexstatere.items(): + for key,lre in list(lextab._lexstatere.items()): titem = [] txtitem = [] for i in range(len(lre)): @@ -241,7 +241,7 @@ class Lexer: self.lexstatere[key] = titem self.lexstateretext[key] = txtitem self.lexstateerrorf = { } - for key,ef in lextab._lexstateerrorf.items(): + for key,ef in list(lextab._lexstateerrorf.items()): self.lexstateerrorf[key] = fdict[ef] self.begin('INITIAL') @@ -489,7 +489,7 @@ def _form_master_re(relist,reflags,ldict,toknames): lexindexfunc = [ None ] * (max(lexre.groupindex.values())+1) lexindexnames = lexindexfunc[:] - for f,i in lexre.groupindex.items(): + for f,i in list(lexre.groupindex.items()): handle = ldict.get(f,None) if type(handle) in (types.FunctionType, types.MethodType): lexindexfunc[i] = (handle,toknames[f]) @@ -704,7 +704,7 @@ class LexerReflect(object): self.error = 1 # Sort the functions by line number - for f in self.funcsym.values(): + for f in list(self.funcsym.values()): if sys.version_info[0] < 3: f.sort(lambda x,y: cmp(func_code(x[1]).co_firstlineno,func_code(y[1]).co_firstlineno)) else: @@ -712,7 +712,7 @@ class LexerReflect(object): f.sort(key=lambda x: func_code(x[1]).co_firstlineno) # Sort the strings by regular expression length - for s in self.strsym.values(): + for s in list(self.strsym.values()): if sys.version_info[0] < 3: s.sort(lambda x,y: (len(x[1]) < len(y[1])) - (len(x[1]) > len(y[1]))) else: @@ -960,7 +960,7 @@ def lex(module=None,object=None,debug=0,optimize=0,lextab="lextab",reflags=0,now debuglog.info("lex: state '%s' : regex[%d] = '%s'",state, i, re_text[i]) # For inclusive states, we need to add the regular expressions from the INITIAL state - for state,stype in stateinfo.items(): + for state,stype in list(stateinfo.items()): if state != "INITIAL" and stype == 'inclusive': lexobj.lexstatere[state].extend(lexobj.lexstatere['INITIAL']) lexobj.lexstateretext[state].extend(lexobj.lexstateretext['INITIAL']) @@ -982,7 +982,7 @@ def lex(module=None,object=None,debug=0,optimize=0,lextab="lextab",reflags=0,now errorlog.warning("No t_error rule is defined") # Check state information for ignore and error rules - for s,stype in stateinfo.items(): + for s,stype in list(stateinfo.items()): if stype == 'exclusive': if not s in linfo.errorf: errorlog.warning("No error rule is defined for exclusive state '%s'", s) diff --git a/other-licenses/ply/ply/yacc.py b/other-licenses/ply/ply/yacc.py index e9f5c65755..843138b448 100644 --- a/other-licenses/ply/ply/yacc.py +++ b/other-licenses/ply/ply/yacc.py @@ -1533,7 +1533,7 @@ class Grammar(object): # Then propagate termination until no change: while 1: some_change = 0 - for (n,pl) in self.Prodnames.items(): + for (n,pl) in list(self.Prodnames.items()): # Nonterminal n terminates iff any of its productions terminates. for p in pl: # Production p terminates iff all of its rhs symbols terminate. @@ -1561,7 +1561,7 @@ class Grammar(object): break infinite = [] - for (s,term) in terminates.items(): + for (s,term) in list(terminates.items()): if not term: if not s in self.Prodnames and not s in self.Terminals and s != 'error': # s is used-but-not-defined, and we've already warned of that, @@ -1598,7 +1598,7 @@ class Grammar(object): # ----------------------------------------------------------------------------- def unused_terminals(self): unused_tok = [] - for s,v in self.Terminals.items(): + for s,v in list(self.Terminals.items()): if s != 'error' and not v: unused_tok.append(s) @@ -1613,7 +1613,7 @@ class Grammar(object): def unused_rules(self): unused_prod = [] - for s,v in self.Nonterminals.items(): + for s,v in list(self.Nonterminals.items()): if not v: p = self.Prodnames[s][0] unused_prod.append(p) @@ -2319,7 +2319,7 @@ class LRGeneratedTable(LRTable): # ----------------------------------------------------------------------------- def add_lookaheads(self,lookbacks,followset): - for trans,lb in lookbacks.items(): + for trans,lb in list(lookbacks.items()): # Loop over productions in lookback for state,p in lb: if not state in p.lookaheads: @@ -2565,8 +2565,8 @@ _lr_signature = %r if smaller: items = { } - for s,nd in self.lr_action.items(): - for name,v in nd.items(): + for s,nd in list(self.lr_action.items()): + for name,v in list(nd.items()): i = items.get(name) if not i: i = ([],[]) @@ -2575,7 +2575,7 @@ _lr_signature = %r i[1].append(v) f.write("\n_lr_action_items = {") - for k,v in items.items(): + for k,v in list(items.items()): f.write("%r:([" % k) for i in v[0]: f.write("%r," % i) @@ -2597,7 +2597,7 @@ del _lr_action_items else: f.write("\n_lr_action = { "); - for k,v in self.lr_action.items(): + for k,v in list(self.lr_action.items()): f.write("(%r,%r):%r," % (k[0],k[1],v)) f.write("}\n"); @@ -2605,8 +2605,8 @@ del _lr_action_items # Factor out names to try and make smaller items = { } - for s,nd in self.lr_goto.items(): - for name,v in nd.items(): + for s,nd in list(self.lr_goto.items()): + for name,v in list(nd.items()): i = items.get(name) if not i: i = ([],[]) @@ -2615,7 +2615,7 @@ del _lr_action_items i[1].append(v) f.write("\n_lr_goto_items = {") - for k,v in items.items(): + for k,v in list(items.items()): f.write("%r:([" % k) for i in v[0]: f.write("%r," % i) @@ -2636,7 +2636,7 @@ del _lr_goto_items """) else: f.write("\n_lr_goto = { "); - for k,v in self.lr_goto.items(): + for k,v in list(self.lr_goto.items()): f.write("(%r,%r):%r," % (k[0],k[1],v)) f.write("}\n"); @@ -2828,7 +2828,7 @@ class ParserReflect(object): # Match def p_funcname( fre = re.compile(r'\s*def\s+(p_[a-zA-Z_0-9]*)\(') - for filename in self.files.keys(): + for filename in list(self.files.keys()): base,ext = os.path.splitext(filename) if ext != '.py': return 1 # No idea. Assume it's okay. @@ -2957,7 +2957,7 @@ class ParserReflect(object): # Get all p_functions from the grammar def get_pfunctions(self): p_functions = [] - for name, item in self.pdict.items(): + for name, item in list(self.pdict.items()): if name[:2] != 'p_': continue if name == 'p_error': continue if isinstance(item,(types.FunctionType,types.MethodType)): @@ -3010,7 +3010,7 @@ class ParserReflect(object): # Secondary validation step that looks for p_ definitions that are not functions # or functions that look like they might be grammar rules. - for n,v in self.pdict.items(): + for n,v in list(self.pdict.items()): if n[0:2] == 'p_' and isinstance(v, (types.FunctionType, types.MethodType)): continue if n[0:2] == 't_': continue if n[0:2] == 'p_' and n != 'p_error': diff --git a/python/PyECC/ecc/performance.py b/python/PyECC/ecc/performance.py index 63a53aefc8..b4fa23e16d 100644 --- a/python/PyECC/ecc/performance.py +++ b/python/PyECC/ecc/performance.py @@ -38,7 +38,7 @@ def test_verification_perf(n = 100): def print_dict(title, d): print(title) print('-' * len(title)) - for k, v in d.items(): + for k, v in list(d.items()): print(k, '\t', v) print() diff --git a/python/altgraph/altgraph/GraphAlgo.py b/python/altgraph/altgraph/GraphAlgo.py index 9e6fff2b17..2cd4a4ee18 100644 --- a/python/altgraph/altgraph/GraphAlgo.py +++ b/python/altgraph/altgraph/GraphAlgo.py @@ -127,7 +127,7 @@ class _priorityDictionary(dict): dict.__setitem__(self,key,val) heap = self.__heap if len(heap) > 2 * len(self): - self.__heap = [(v,k) for k,v in self.iteritems()] + self.__heap = [(v,k) for k,v in self.items()] self.__heap.sort() # builtin sort probably faster than O(n)-time heapify else: newPair = (val,key) diff --git a/python/altgraph/altgraph_tests/test_graphutil.py b/python/altgraph/altgraph_tests/test_graphutil.py index c1166237c1..4561410ba1 100644 --- a/python/altgraph/altgraph_tests/test_graphutil.py +++ b/python/altgraph/altgraph_tests/test_graphutil.py @@ -67,7 +67,7 @@ class TestGraphUtil (unittest.TestCase): total_counts = sum(counts.values()) P = {} - for degree, count in counts.items(): + for degree, count in list(counts.items()): P[degree] = count * 1.0 / total_counts # XXX: use algoritm diff --git a/python/altgraph/setup.py b/python/altgraph/setup.py index 8939d2953b..9d5503dc47 100644 --- a/python/altgraph/setup.py +++ b/python/altgraph/setup.py @@ -64,7 +64,7 @@ def eval_marker(value): class M: def __init__(self, **kwds): - for k, v in kwds.items(): + for k, v in list(kwds.items()): setattr(self, k, v) variables = { @@ -634,7 +634,7 @@ else: sep_boundary = '\n--' + boundary end_boundary = sep_boundary + '--' body = StringIO.StringIO() - for key, value in data.items(): + for key, value in list(data.items()): if not isinstance(value, list): value = [value] diff --git a/python/compare-locales/compare_locales/checks.py b/python/compare-locales/compare_locales/checks.py index 69ce3421a6..810de8519e 100644 --- a/python/compare-locales/compare_locales/checks.py +++ b/python/compare-locales/compare_locales/checks.py @@ -342,7 +342,7 @@ class DTDChecker(Checker): if u != ru: msgs.append("units for %s don't match " "(%s != %s)" % (s, u, ru)) - for s in refMap.iterkeys(): + for s in refMap.keys(): msgs.insert(0, '%s only in reference' % s) if msgs: yield ('warning', 0, ', '.join(msgs), 'css') diff --git a/python/compare-locales/compare_locales/compare.py b/python/compare-locales/compare_locales/compare.py index 6271624b4d..b2700d8384 100644 --- a/python/compare-locales/compare_locales/compare.py +++ b/python/compare-locales/compare_locales/compare.py @@ -42,7 +42,7 @@ class Tree(object): old = None new = tuple(parts) t = self - for k, v in self.branches.iteritems(): + for k, v in self.branches.items(): for i, part in enumerate(zip(k, parts)): if part[0] != part[1]: i -= 1 @@ -79,7 +79,7 @@ class Tree(object): If flag is 'value', key_or_value is a value object, otherwise (flag is 'key') it's a key string. ''' - keys = self.branches.keys() + keys = list(self.branches.keys()) keys.sort() if self.value is not None: yield (depth, 'value', self.value) @@ -94,7 +94,7 @@ class Tree(object): Only the values need to take care that they're JSON-able. ''' json = {} - keys = self.branches.keys() + keys = list(self.branches.keys()) keys.sort() if self.value is not None: json['value'] = self.value @@ -203,14 +203,14 @@ class Observer(object): self.summary = defaultdict(intdict) if 'summary' in state: - for loc, stats in state['summary'].iteritems(): + for loc, stats in state['summary'].items(): self.summary[loc].update(stats) self.details = state['details'] self.filter = None def getSummary(self): plaindict = {} - for k, v in self.summary.iteritems(): + for k, v in self.summary.items(): plaindict[k] = dict(v) return plaindict @@ -261,7 +261,7 @@ class Observer(object): def toExhibit(self): items = [] - for locale in sorted(self.summary.iterkeys()): + for locale in sorted(self.summary.keys()): summary = self.summary[locale] if locale is not None: item = {'id': 'xxx/' + locale, @@ -339,10 +339,10 @@ class Observer(object): return '\n'.join(o) out = [] - for locale, summary in sorted(self.summary.iteritems()): + for locale, summary in sorted(self.summary.items()): if locale is not None: out.append(locale + ':') - out += [k + ': ' + str(v) for k, v in sorted(summary.iteritems())] + out += [k + ': ' + str(v) for k, v in sorted(summary.items())] total = sum([summary[k] for k in ['changed', 'unchanged', 'report', 'missing', 'missingInFiles'] @@ -453,7 +453,7 @@ class ContentComparer: return self.reference[ref_file] = p.parse() ref = self.reference[ref_file] - ref_list = ref[1].keys() + ref_list = list(ref[1].keys()) ref_list.sort() try: p.readContents(l10n.getContents()) @@ -473,7 +473,7 @@ class ContentComparer: return (i, offset - lines[i - 1]) return (1, offset) - l10n_list = l10n_map.keys() + l10n_list = list(l10n_map.keys()) l10n_list.sort() ar = AddRemove() ar.set_left(ref_list) diff --git a/python/compare-locales/compare_locales/parser.py b/python/compare-locales/compare_locales/parser.py index 290b87e18b..10fd32d942 100644 --- a/python/compare-locales/compare_locales/parser.py +++ b/python/compare-locales/compare_locales/parser.py @@ -499,7 +499,7 @@ class BookmarksParser(Parser): t = tks[i] if t._type == START: k.append(t.tag) - keys = t.attrs.keys() + keys = list(t.attrs.keys()) keys.sort() for attrname in keys: yield self.BMEntity('.'.join(k) + '.@' + attrname, diff --git a/python/compare-locales/compare_locales/paths.py b/python/compare-locales/compare_locales/paths.py index f72b3a2e72..e49e5600c7 100644 --- a/python/compare-locales/compare_locales/paths.py +++ b/python/compare-locales/compare_locales/paths.py @@ -355,7 +355,7 @@ class EnumerateApp(object): code and an directory enumerator will be given. ''' dirmap = dict(self.config.directories()) - mods = dirmap.keys() + mods = list(dirmap.keys()) mods.sort() for mod in mods: if self.reference == 'en-US': diff --git a/python/compare-locales/compare_locales/tests/test_webapps.py b/python/compare-locales/compare_locales/tests/test_webapps.py index 2f12236490..4ae47dc1f0 100644 --- a/python/compare-locales/compare_locales/tests/test_webapps.py +++ b/python/compare-locales/compare_locales/tests/test_webapps.py @@ -22,7 +22,7 @@ class TestFileComparison(unittest.TestCase): filecomp = self.mock_FileComparison(_listdir) filecomp.files() self.assertEqual(filecomp.locales(), []) - self.assertEqual(filecomp._reference.keys(), ['my_app']) + self.assertEqual(list(filecomp._reference.keys()), ['my_app']) file_ = filecomp._reference['my_app'] self.assertEqual(file_.file, 'locales/my_app.en-US.properties') @@ -36,6 +36,6 @@ class TestFileComparison(unittest.TestCase): filecomp.files() self.assertEqual(filecomp.locales(), ['ar', 'sr-Latn', 'sv-SE']) - self.assertEqual(filecomp._files['ar'].keys(), ['my_app']) + self.assertEqual(list(filecomp._files['ar'].keys()), ['my_app']) file_ = filecomp._files['ar']['my_app'] self.assertEqual(file_.file, 'locales/my_app.ar.properties') diff --git a/python/compare-locales/compare_locales/webapps.py b/python/compare-locales/compare_locales/webapps.py index 42f5b56578..5cc4d638d9 100644 --- a/python/compare-locales/compare_locales/webapps.py +++ b/python/compare-locales/compare_locales/webapps.py @@ -96,11 +96,11 @@ class Manifest(object): rv = defaultdict(dict) localizable = manifest_fragment.pop('locales', {}) if localizable: - for locale, keyvalue in localizable.iteritems(): - for key, value in keyvalue.iteritems(): + for locale, keyvalue in localizable.items(): + for key, value in keyvalue.items(): key = '.'.join(['locales', 'AB_CD', key]) rv[locale][key] = value - for key, sub_manifest in manifest_fragment.iteritems(): + for key, sub_manifest in manifest_fragment.items(): if not isinstance(sub_manifest, dict): continue subdict = self.extract_manifest_strings(sub_manifest) @@ -108,7 +108,7 @@ class Manifest(object): for locale, keyvalue in subdict: rv[locale].update((key + '.' + subkey, value) for subkey, value - in keyvalue.iteritems()) + in keyvalue.items()) return rv def compare(self, locales): @@ -166,7 +166,7 @@ class FileComparison(object): '''Get the locales present in the webapp ''' self.files() - locales = self._files.keys() + locales = list(self._files.keys()) locales.sort() return locales diff --git a/python/configobj/configobj.py b/python/configobj/configobj.py index 89e2d2e485..bc049a0ae8 100644 --- a/python/configobj/configobj.py +++ b/python/configobj/configobj.py @@ -518,7 +518,7 @@ class Section(dict): self._initialise() # we do this explicitly so that __setitem__ is used properly # (rather than just passing to ``dict.__init__``) - for entry, value in indict.iteritems(): + for entry, value in indict.items(): self[entry] = value @@ -721,7 +721,7 @@ class Section(dict): def items(self): """D.items() -> list of D's (key, value) pairs, as 2-tuples""" - return list(zip((self.scalars + self.sections), self.values())) + return list(zip((self.scalars + self.sections), list(self.values()))) def keys(self): @@ -736,7 +736,7 @@ class Section(dict): def iteritems(self): """D.iteritems() -> an iterator over the (key, value) items of D""" - return iter(self.items()) + return iter(list(self.items())) def iterkeys(self): @@ -748,7 +748,7 @@ class Section(dict): def itervalues(self): """D.itervalues() -> an iterator over the values of D""" - return iter(self.values()) + return iter(list(self.values())) def __repr__(self): @@ -814,7 +814,7 @@ class Section(dict): >>> c2 ConfigObj({'section1': {'option1': 'False', 'subsection': {'more_options': 'False'}}}) """ - for key, val in indict.items(): + for key, val in list(indict.items()): if (key in self and isinstance(self[key], dict) and isinstance(val, dict)): self[key].merge(val) @@ -1224,7 +1224,7 @@ class ConfigObj(Section): for entry in options: if entry not in OPTION_DEFAULTS: raise TypeError('Unrecognised option "%s".' % entry) - for entry, value in OPTION_DEFAULTS.items(): + for entry, value in list(OPTION_DEFAULTS.items()): if entry not in options: options[entry] = value keyword_value = _options[entry] @@ -1423,7 +1423,7 @@ class ConfigObj(Section): enc = BOM_LIST[self.encoding.lower()] if enc == 'utf_16': # For UTF16 we try big endian and little endian - for BOM, (encoding, final_encoding) in BOMS.items(): + for BOM, (encoding, final_encoding) in list(BOMS.items()): if not final_encoding: # skip UTF8 continue @@ -1453,7 +1453,7 @@ class ConfigObj(Section): return self._decode(infile, self.encoding) # No encoding specified - so we need to check for UTF8/UTF16 - for BOM, (encoding, final_encoding) in BOMS.items(): + for BOM, (encoding, final_encoding) in list(BOMS.items()): if not line.startswith(BOM): continue else: @@ -2422,7 +2422,7 @@ def flatten_errors(cfg, res, levels=None, results=None): if levels: levels.pop() return results - for (key, val) in res.items(): + for (key, val) in list(res.items()): if val == True: continue if isinstance(cfg.get(key), dict): diff --git a/python/configobj/validate.py b/python/configobj/validate.py index 73dbdb891b..4f587e7ae0 100644 --- a/python/configobj/validate.py +++ b/python/configobj/validate.py @@ -615,7 +615,7 @@ class Validator(object): fun_kwargs = dict(fun_kwargs) else: fun_name, fun_args, fun_kwargs, default = self._parse_check(check) - fun_kwargs = dict([(str(key), value) for (key, value) in fun_kwargs.items()]) + fun_kwargs = dict([(str(key), value) for (key, value) in list(fun_kwargs.items())]) self._cache[check] = fun_name, list(fun_args), dict(fun_kwargs), default return fun_name, fun_args, fun_kwargs, default diff --git a/python/eme/gen-eme-voucher.py b/python/eme/gen-eme-voucher.py index e7ddee20eb..e2f9ff62bb 100644 --- a/python/eme/gen-eme-voucher.py +++ b/python/eme/gen-eme-voucher.py @@ -105,7 +105,7 @@ class ApplicationDigest(univ.Sequence): def meets_requirements(items, requirements): for r in requirements: - for n, v in r.items(): + for n, v in list(r.items()): if n not in items or items[n] != v: return False return True diff --git a/python/mach/mach/base.py b/python/mach/mach/base.py index 3556dc6e57..b7a4d758a9 100644 --- a/python/mach/mach/base.py +++ b/python/mach/mach/base.py @@ -14,7 +14,7 @@ class CommandContext(object): self.log_manager = log_manager self.commands = commands - for k,v in kwargs.items(): + for k,v in list(kwargs.items()): setattr(self, k, v) diff --git a/python/mach/mach/commands/commandinfo.py b/python/mach/mach/commands/commandinfo.py index cce85f859d..1c2b79464b 100644 --- a/python/mach/mach/commands/commandinfo.py +++ b/python/mach/mach/commands/commandinfo.py @@ -19,7 +19,7 @@ class BuiltinCommands(object): @property def command_keys(self): # NOTE 'REMOVED' is a function in testing/mochitest/mach_commands.py - return (k for k, v in self.context.commands.command_handlers.items() + return (k for k, v in list(self.context.commands.command_handlers.items()) if not v.conditions or v.conditions[0].__name__ != 'REMOVED') @Command('mach-commands', category='misc', diff --git a/python/mach/mach/config.py b/python/mach/mach/config.py index 26c9a4482c..b2fd5f5ae2 100644 --- a/python/mach/mach/config.py +++ b/python/mach/mach/config.py @@ -397,10 +397,10 @@ class ConfigSettings(collections.Mapping): meta = self._format_metadata(provider, section, option, *setting[1:]) config_settings[section][option] = meta - for section_name, settings in config_settings.items(): + for section_name, settings in list(config_settings.items()): section = self._settings.get(section_name, {}) - for k, v in settings.items(): + for k, v in list(settings.items()): if k in section: raise ConfigException('Setting already registered: %s.%s' % section_name, k) @@ -432,7 +432,7 @@ class ConfigSettings(collections.Mapping): if self._finalized: return - for section, settings in self._settings.items(): + for section, settings in list(self._settings.items()): s = ConfigSettings.ConfigSection(self._config, section, settings) self._sections[section] = s @@ -445,7 +445,7 @@ class ConfigSettings(collections.Mapping): def __iter__(self): self._finalize() - return iter(self._sections.keys()) + return iter(list(self._sections.keys())) def __contains__(self, k): return k in self._settings diff --git a/python/mach/mach/dispatcher.py b/python/mach/mach/dispatcher.py index 5604d981d7..f5fd0c7185 100644 --- a/python/mach/mach/dispatcher.py +++ b/python/mach/mach/dispatcher.py @@ -243,7 +243,7 @@ class CommandAction(argparse.Action): r = self._mach_registrar disabled_commands = [] - cats = [(k, v[2]) for k, v in r.categories.items()] + cats = [(k, v[2]) for k, v in list(r.categories.items())] sorted_cats = sorted(cats, key=itemgetter(1), reverse=True) for category, priority in sorted_cats: group = None @@ -375,7 +375,7 @@ class CommandAction(argparse.Action): ' subcommand [subcommand arguments]' group = parser.add_argument_group('Sub Commands') - for subcommand, subhandler in sorted(handler.subcommand_handlers.iteritems()): + for subcommand, subhandler in sorted(handler.subcommand_handlers.items()): group.add_argument(subcommand, help=subhandler.description, action='store_true') @@ -406,7 +406,7 @@ class CommandAction(argparse.Action): def _suggest_command(self, command): # Make sure we don't suggest any deprecated commands. - names = [h.name for h in self._mach_registrar.command_handlers.values() + names = [h.name for h in list(self._mach_registrar.command_handlers.values()) if h.cls.__name__ != 'DeprecatedCommands'] # We first try to look for a valid command that is very similar to the given command. suggested_commands = difflib.get_close_matches(command, names, cutoff=0.8) diff --git a/python/mach/mach/mixin/process.py b/python/mach/mach/mixin/process.py index b8f0eac029..548b59dd32 100644 --- a/python/mach/mach/mixin/process.py +++ b/python/mach/mach/mixin/process.py @@ -108,7 +108,7 @@ class ProcessExecutionMixin(LoggingMixin): # binary. utf-8 is our globally assumed default. If the caller doesn't # want UTF-8, they shouldn't pass in a unicode instance. normalized_env = {} - for k, v in use_env.items(): + for k, v in list(use_env.items()): if isinstance(k, unicode): k = k.encode('utf-8', 'strict') diff --git a/python/macholib/macholib/itergraphreport.py b/python/macholib/macholib/itergraphreport.py index 453c96e2ac..8a4824986c 100644 --- a/python/macholib/macholib/itergraphreport.py +++ b/python/macholib/macholib/itergraphreport.py @@ -27,7 +27,7 @@ def itergraphreport(nodes, describe_edge, name='G'): yield 'digraph %s {\n' % (name,) attr = dict(rankdir='LR', concentrate='true') cpatt = '%s="%s"' - for item in attr.iteritems(): + for item in attr.items(): yield '\t%s;\n' % (cpatt % item,) # find all packages (subgraphs) @@ -45,7 +45,7 @@ def itergraphreport(nodes, describe_edge, name='G'): node, ','.join([ (cpatt % item) for item in - nodevisitor(node, data, outgoing, incoming).iteritems() + nodevisitor(node, data, outgoing, incoming).items() ]), ) @@ -64,7 +64,7 @@ def itergraphreport(nodes, describe_edge, name='G'): yield edgestr % ( head, tail, - ','.join([(cpatt % item) for item in attribs.iteritems()]), + ','.join([(cpatt % item) for item in attribs.items()]), ) for s in do_graph(graph, '\t'): diff --git a/python/macholib/macholib/ptypes.py b/python/macholib/macholib/ptypes.py index f1457c91bb..47c9413d0e 100644 --- a/python/macholib/macholib/ptypes.py +++ b/python/macholib/macholib/ptypes.py @@ -183,7 +183,7 @@ def _make(): kwargs = args[0]._objects_ args = () self._objects_ = {} - iargs = chain(izip(self._names_, args), kwargs.items()) + iargs = chain(izip(self._names_, args), list(kwargs.items())) for key, value in iargs: if key not in self._names_ and key != "_endian_": raise TypeError diff --git a/python/macholib/setup.py b/python/macholib/setup.py index 8939d2953b..9d5503dc47 100644 --- a/python/macholib/setup.py +++ b/python/macholib/setup.py @@ -64,7 +64,7 @@ def eval_marker(value): class M: def __init__(self, **kwds): - for k, v in kwds.items(): + for k, v in list(kwds.items()): setattr(self, k, v) variables = { @@ -634,7 +634,7 @@ else: sep_boundary = '\n--' + boundary end_boundary = sep_boundary + '--' body = StringIO.StringIO() - for key, value in data.items(): + for key, value in list(data.items()): if not isinstance(value, list): value = [value] diff --git a/python/mock-1.0.0/mock.py b/python/mock-1.0.0/mock.py index 1be4e6e458..2005543b58 100644 --- a/python/mock-1.0.0/mock.py +++ b/python/mock-1.0.0/mock.py @@ -607,7 +607,7 @@ class NonCallableMock(Base): self.call_args_list = _CallList() self.method_calls = _CallList() - for child in self._mock_children.values(): + for child in list(self._mock_children.values()): if isinstance(child, _SpecState): continue child.reset_mock() @@ -626,7 +626,7 @@ class NonCallableMock(Base): >>> attrs = {'method.return_value': 3, 'other.side_effect': KeyError} >>> mock.configure_mock(**attrs)""" - for arg, val in sorted(kwargs.items(), + for arg, val in sorted(list(kwargs.items()), # we sort on the number of dots so that # attributes are set before we set attributes on # attributes @@ -1942,7 +1942,7 @@ def _format_call_signature(name, args, kwargs): formatted_args = '' args_string = ', '.join([repr(arg) for arg in args]) kwargs_string = ', '.join([ - '%s=%r' % (key, value) for key, value in kwargs.items() + '%s=%r' % (key, value) for key, value in list(kwargs.items()) ]) if args_string: formatted_args = args_string diff --git a/python/mozbuild/dumbmake/dumbmake.py b/python/mozbuild/dumbmake/dumbmake.py index 5457c8b0a0..cd81c14e12 100644 --- a/python/mozbuild/dumbmake/dumbmake.py +++ b/python/mozbuild/dumbmake/dumbmake.py @@ -68,7 +68,7 @@ def all_dependencies(*targets, **kwargs): del all_targets[dependency] all_targets[dependency] = True - return all_targets.keys() + return list(all_targets.keys()) def get_components(path): """Take a path and return all the components of the path.""" @@ -114,7 +114,7 @@ def add_extra_dependencies(target_pairs, dependency_map): make_dirs[make_dir] = True all_components = [] - for make_dir in make_dirs.iterkeys(): + for make_dir in make_dirs.keys(): all_components.extend(get_components(make_dir)) for i in all_dependencies(*all_components, dependency_map=dependency_map): diff --git a/python/mozbuild/mozbuild/action/dump_env.py b/python/mozbuild/mozbuild/action/dump_env.py index 6aea194d81..aceb696ed0 100644 --- a/python/mozbuild/mozbuild/action/dump_env.py +++ b/python/mozbuild/mozbuild/action/dump_env.py @@ -12,5 +12,5 @@ sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from shellutil import quote -for key, value in os.environ.items(): +for key, value in list(os.environ.items()): print(('%s=%s' % (key, quote(value)))) diff --git a/python/mozbuild/mozbuild/action/generate_browsersearch.py b/python/mozbuild/mozbuild/action/generate_browsersearch.py index 231abe9be3..c343e3cc68 100644 --- a/python/mozbuild/mozbuild/action/generate_browsersearch.py +++ b/python/mozbuild/mozbuild/action/generate_browsersearch.py @@ -97,7 +97,7 @@ def main(args): regions = properties.get_dict('browser.search.defaultenginename') browsersearch['regions'] = {} - for region in regions.keys(): + for region in list(regions.keys()): region_default = regions[region] region_engines = properties.get_list('browser.search.order.{region}'.format(region=region)) diff --git a/python/mozbuild/mozbuild/action/process_define_files.py b/python/mozbuild/mozbuild/action/process_define_files.py index f6d0c1695a..6bd3440d14 100644 --- a/python/mozbuild/mozbuild/action/process_define_files.py +++ b/python/mozbuild/mozbuild/action/process_define_files.py @@ -55,7 +55,7 @@ def process_define_file(output, input): 'CONFIGURE_DEFINE_FILE') defines = '\n'.join(sorted( '#define %s %s' % (name, val) - for name, val in config.defines.iteritems() + for name, val in config.defines.items() if name not in config.non_global_defines)) l = l[:m.start('cmd') - 1] \ + defines + l[m.end('name'):] diff --git a/python/mozbuild/mozbuild/action/test_archive.py b/python/mozbuild/mozbuild/action/test_archive.py index 8ec4dd2a90..62602b15ed 100644 --- a/python/mozbuild/mozbuild/action/test_archive.py +++ b/python/mozbuild/mozbuild/action/test_archive.py @@ -433,7 +433,7 @@ ARCHIVE_FILES = { # "common" is our catch all archive and it ignores things from other archives. # Verify nothing sneaks into ARCHIVE_FILES without a corresponding exclusion # rule in the "common" archive. -for k, v in ARCHIVE_FILES.items(): +for k, v in list(ARCHIVE_FILES.items()): # Skip mozharness because it isn't staged. if k in ('common', 'mozharness'): continue diff --git a/python/mozbuild/mozbuild/action/xpidl-process.py b/python/mozbuild/mozbuild/action/xpidl-process.py index 07ea3cf967..331228f114 100755 --- a/python/mozbuild/mozbuild/action/xpidl-process.py +++ b/python/mozbuild/mozbuild/action/xpidl-process.py @@ -58,7 +58,7 @@ def process(input_dir, inc_paths, cache_dir, header_dir, xpt_dir, deps_dir, modu # TODO use FileAvoidWrite once it supports binary mode. xpt_path = os.path.join(xpt_dir, '%s.xpt' % module) - xpt_link(xpts.values()).write(xpt_path) + xpt_link(list(xpts.values())).write(xpt_path) rule.add_targets([xpt_path]) if deps_dir: diff --git a/python/mozbuild/mozbuild/artifacts.py b/python/mozbuild/mozbuild/artifacts.py index 76b5a07f03..ac517c5c47 100644 --- a/python/mozbuild/mozbuild/artifacts.py +++ b/python/mozbuild/mozbuild/artifacts.py @@ -183,7 +183,7 @@ class ArtifactJob(object): with JarWriter(file=processed_filename, optimize=False, compress_level=5) as writer: reader = JarReader(filename) - for filename, entry in reader.entries.iteritems(): + for filename, entry in reader.entries.items(): for pattern, (src_prefix, dest_prefix) in self.test_artifact_patterns: if not mozpath.match(filename, pattern): continue @@ -552,7 +552,7 @@ class CacheManager(object): def print_cache(self): with self: - for item in self._cache.items(): + for item in list(self._cache.items()): self.log(logging.INFO, 'artifact', {'item': item}, '{item}') @@ -565,7 +565,7 @@ class CacheManager(object): # We use the persisted LRU caches to our advantage. The first item is # most recent. with self: - item = next(self._cache.items(), None) + item = next(list(self._cache.items()), None) if item is not None: (name, args, sorted_kwargs), result = item self.print_last_item(args, sorted_kwargs, result) @@ -596,7 +596,7 @@ class PushheadCache(CacheManager): if req.status_code not in list(range(200, 300)): raise ValueError result = req.json() - [found_pushid] = result['pushes'].keys() + [found_pushid] = list(result['pushes'].keys()) return int(found_pushid) @cachedmethod(operator.attrgetter('_cache')) @@ -609,7 +609,7 @@ class PushheadCache(CacheManager): headers={'Accept': 'application/json'}) result = req.json() return [ - p['changesets'][-1] for p in result['pushes'].values() + p['changesets'][-1] for p in list(result['pushes'].values()) ] class TaskCache(CacheManager): @@ -847,7 +847,7 @@ class Artifacts(object): candidate_pushheads = collections.defaultdict(list) - for tree, pushid in found_pushids.iteritems(): + for tree, pushid in found_pushids.items(): end = pushid start = pushid - NUM_PUSHHEADS_TO_QUERY_PER_PARENT diff --git a/python/mozbuild/mozbuild/backend/base.py b/python/mozbuild/mozbuild/backend/base.py index 7ec5fe43d2..ddbd8839c2 100644 --- a/python/mozbuild/mozbuild/backend/base.py +++ b/python/mozbuild/mozbuild/backend/base.py @@ -252,7 +252,7 @@ class BuildBackend(LoggingMixin): srcdir = mozpath.dirname(obj.input_path) pp.context.update({ k: ' '.join(v) if isinstance(v, list) else v - for k, v in obj.config.substs.iteritems() + for k, v in obj.config.substs.items() }) pp.context.update( top_srcdir=obj.topsrcdir, diff --git a/python/mozbuild/mozbuild/backend/common.py b/python/mozbuild/mozbuild/backend/common.py index 351c6dbc81..a1eea3fbe2 100644 --- a/python/mozbuild/mozbuild/backend/common.py +++ b/python/mozbuild/mozbuild/backend/common.py @@ -195,11 +195,11 @@ class TestManager(object): def add_defaults(self, manifest): if not hasattr(manifest, 'manifest_defaults'): return - for sub_manifest, defaults in manifest.manifest_defaults.items(): + for sub_manifest, defaults in list(manifest.manifest_defaults.items()): self.manifest_defaults[sub_manifest] = defaults def add_installs(self, obj, topsrcdir): - for src, (dest, _) in obj.installs.iteritems(): + for src, (dest, _) in obj.installs.items(): key = src[len(topsrcdir)+1:] self.installs_by_path[key].append((src, dest)) for src, pat, dest in obj.pattern_installs: @@ -366,7 +366,7 @@ class CommonBackend(BuildBackend): path = mozpath.join(self.environment.topobjdir, 'test-installs.pkl') with self._write_file(path, mode='rb') as fh: - pickle.dump({k: v for k, v in self._test_manager.installs_by_path.items() + pickle.dump({k: v for k, v in list(self._test_manager.installs_by_path.items()) if k in self._test_manager.deferred_installs}, fh, protocol=2) diff --git a/python/mozbuild/mozbuild/backend/configenvironment.py b/python/mozbuild/mozbuild/backend/configenvironment.py index 0edcf53660..f1a637d1c3 100644 --- a/python/mozbuild/mozbuild/backend/configenvironment.py +++ b/python/mozbuild/mozbuild/backend/configenvironment.py @@ -176,7 +176,7 @@ class ConfigEnvironment(object): except UnicodeDecodeError: return v.decode('utf-8', 'replace') - for k, v in self.substs.items(): + for k, v in list(self.substs.items()): if not isinstance(v, StringTypes): if isinstance(v, Iterable): type(v)(decode(i) for i in v) diff --git a/python/mozbuild/mozbuild/backend/fastermake.py b/python/mozbuild/mozbuild/backend/fastermake.py index 0ca385187b..9a2332cd1d 100644 --- a/python/mozbuild/mozbuild/backend/fastermake.py +++ b/python/mozbuild/mozbuild/backend/fastermake.py @@ -130,12 +130,12 @@ class FasterMakeBackend(CommonBackend, PartialBackend): if value is not None: mk.add_statement('%s = %s' % (var, value)) - install_manifests_bases = self._install_manifests.keys() + install_manifests_bases = list(self._install_manifests.keys()) # Add information for chrome manifest generation manifest_targets = [] - for target, entries in self._manifest_entries.iteritems(): + for target, entries in self._manifest_entries.items(): manifest_targets.append(target) install_target = mozpath.basedir(target, install_manifests_bases) self._install_manifests[install_target].add_content( @@ -144,16 +144,16 @@ class FasterMakeBackend(CommonBackend, PartialBackend): # Add information for install manifests. mk.add_statement('INSTALL_MANIFESTS = %s' - % ' '.join(self._install_manifests.keys())) + % ' '.join(list(self._install_manifests.keys()))) # Add dependencies we infered: - for target, deps in self._dependencies.iteritems(): + for target, deps in self._dependencies.items(): mk.create_rule([target]).add_dependencies( '$(TOPOBJDIR)/%s' % d for d in deps) mk.add_statement('include $(TOPSRCDIR)/config/faster/rules.mk') - for base, install_manifest in self._install_manifests.iteritems(): + for base, install_manifest in self._install_manifests.items(): with self._write_file( mozpath.join(self.environment.topobjdir, 'faster', 'install_%s' % base.replace('/', '_'))) as fh: diff --git a/python/mozbuild/mozbuild/backend/recursivemake.py b/python/mozbuild/mozbuild/backend/recursivemake.py index c9b167d420..75a5d43da8 100644 --- a/python/mozbuild/mozbuild/backend/recursivemake.py +++ b/python/mozbuild/mozbuild/backend/recursivemake.py @@ -596,7 +596,7 @@ class RecursiveMakeBackend(CommonBackend): convenience variables, and the other dependency definitions for a hopefully proper directory traversal. """ - for tier, no_skip in self._no_skip.items(): + for tier, no_skip in list(self._no_skip.items()): self.log(logging.DEBUG, 'fill_root_mk', { 'number': len(no_skip), 'tier': tier }, 'Using {number} directories during {tier}') @@ -642,7 +642,7 @@ class RecursiveMakeBackend(CommonBackend): for tier, filter in filters: main, all_deps = \ self._traversal.compute_dependencies(filter) - for dir, deps in all_deps.items(): + for dir, deps in list(all_deps.items()): if deps is not None or (dir in self._idl_dirs \ and tier == 'export'): rule = root_deps_mk.create_rule(['%s/%s' % (dir, tier)]) @@ -655,7 +655,7 @@ class RecursiveMakeBackend(CommonBackend): rule.add_dependencies('%s/%s' % (d, tier) for d in main) all_compile_deps = reduce(lambda x,y: x|y, - self._compile_graph.values()) if self._compile_graph else set() + list(self._compile_graph.values())) if self._compile_graph else set() compile_roots = set(self._compile_graph.keys()) - all_compile_deps rule = root_deps_mk.create_rule(['recurse_compile']) @@ -797,7 +797,7 @@ class RecursiveMakeBackend(CommonBackend): self._fill_root_mk() # Make the master test manifest files. - for flavor, t in self._test_manifests.items(): + for flavor, t in list(self._test_manifests.items()): install_prefix, manifests = t manifest_stem = mozpath.join(install_prefix, '%s.ini' % flavor) self._write_master_test_manifest(mozpath.join( @@ -903,7 +903,7 @@ class RecursiveMakeBackend(CommonBackend): for p in ('Makefile', 'backend.mk', '.deps/.mkdir.done'): build_files.add_optional_exists(p) - for idl in manager.idls.values(): + for idl in list(manager.idls.values()): self._install_manifests['dist_idl'].add_symlink(idl['source'], idl['basename']) self._install_manifests['dist_include'].add_optional_exists('%s.h' @@ -950,7 +950,7 @@ class RecursiveMakeBackend(CommonBackend): interfaces_manifests = [] dist_dir = mozpath.join(self.environment.topobjdir, 'dist') - for manifest, entries in manager.interface_manifests.items(): + for manifest, entries in list(manager.interface_manifests.items()): interfaces_manifests.append(mozpath.join('$(DEPTH)', manifest)) for xpt in sorted(entries): registered_xpt_files.add(mozpath.join( @@ -1010,7 +1010,7 @@ class RecursiveMakeBackend(CommonBackend): # Don't allow files to be defined multiple times unless it is allowed. # We currently allow duplicates for non-test files or test files if # the manifest is listed as a duplicate. - for source, (dest, is_test) in obj.installs.items(): + for source, (dest, is_test) in list(obj.installs.items()): try: self._install_manifests['_test_files'].add_symlink(source, dest) except ValueError: @@ -1291,7 +1291,7 @@ class RecursiveMakeBackend(CommonBackend): man_dir = mozpath.join(self.environment.topobjdir, '_build_manifests', dest) - for k, manifest in manifests.items(): + for k, manifest in list(manifests.items()): with self._write_file(mozpath.join(man_dir, k)) as fh: manifest.write(fileobj=fh) diff --git a/python/mozbuild/mozbuild/backend/tup.py b/python/mozbuild/mozbuild/backend/tup.py index b148532c89..6b5bebfc59 100644 --- a/python/mozbuild/mozbuild/backend/tup.py +++ b/python/mozbuild/mozbuild/backend/tup.py @@ -253,7 +253,7 @@ class TupOnly(CommonBackend, PartialBackend): backend_file = self._get_backend_file('xpcom/xpidl') backend_file.export_shell() - for module, data in sorted(manager.modules.iteritems()): + for module, data in sorted(manager.modules.items()): dest, idls = data cmd = [ '$(PYTHON_PATH)', diff --git a/python/mozbuild/mozbuild/compilation/database.py b/python/mozbuild/mozbuild/compilation/database.py index 20b09df488..d7c1b9fea2 100644 --- a/python/mozbuild/mozbuild/compilation/database.py +++ b/python/mozbuild/mozbuild/compilation/database.py @@ -118,7 +118,7 @@ class CompileDBBackend(CommonBackend): db = [] - for (directory, filename), cmd in self._db.iteritems(): + for (directory, filename), cmd in self._db.items(): env = self._envs[directory] cmd = list(cmd) cmd.append(filename) diff --git a/python/mozbuild/mozbuild/compilation/warnings.py b/python/mozbuild/mozbuild/compilation/warnings.py index 8fb20ccbff..abe5425f8f 100644 --- a/python/mozbuild/mozbuild/compilation/warnings.py +++ b/python/mozbuild/mozbuild/compilation/warnings.py @@ -123,18 +123,18 @@ class WarningsDatabase(object): def __len__(self): i = 0 - for value in self._files.values(): + for value in list(self._files.values()): i += len(value['warnings']) return i def __iter__(self): - for value in self._files.values(): + for value in list(self._files.values()): for warning in value['warnings']: yield warning def __contains__(self, item): - for value in self._files.values(): + for value in list(self._files.values()): for warning in value['warnings']: if warning == item: return True @@ -144,7 +144,7 @@ class WarningsDatabase(object): @property def warnings(self): """All the CompilerWarning instances in this database.""" - for value in self._files.values(): + for value in list(self._files.values()): for w in value['warnings']: yield w @@ -152,7 +152,7 @@ class WarningsDatabase(object): """Returns a mapping of warning types to their counts.""" types = {} - for value in self._files.values(): + for value in list(self._files.values()): for warning in value['warnings']: if dirpath and not mozpath.normsep(warning['filename']).startswith(dirpath): continue @@ -210,7 +210,7 @@ class WarningsDatabase(object): """ # Need to calculate up front since we are mutating original object. - filenames = self._files.keys() + filenames = list(self._files.keys()) for filename in filenames: if not os.path.exists(filename): del self._files[filename] @@ -229,10 +229,10 @@ class WarningsDatabase(object): obj = {'files': {}} # All this hackery because JSON can't handle sets. - for k, v in self._files.iteritems(): + for k, v in self._files.items(): obj['files'][k] = {} - for k2, v2 in v.iteritems(): + for k2, v2 in v.items(): normalized = v2 if k2 == 'warnings': @@ -249,8 +249,8 @@ class WarningsDatabase(object): self._files = obj['files'] # Normalize data types. - for filename, value in self._files.iteritems(): - for k, v in value.iteritems(): + for filename, value in self._files.items(): + for k, v in value.items(): if k != 'warnings': continue diff --git a/python/mozbuild/mozbuild/configure/__init__.py b/python/mozbuild/mozbuild/configure/__init__.py index a59876fcae..49da5cd7e5 100644 --- a/python/mozbuild/mozbuild/configure/__init__.py +++ b/python/mozbuild/mozbuild/configure/__init__.py @@ -334,7 +334,7 @@ class ConfigureSandbox(dict): if path: self.include_file(path) - for option in self._options.itervalues(): + for option in self._options.values(): # All options must be referenced by some @depends function if option not in self._seen: raise ConfigureError( @@ -542,7 +542,7 @@ class ConfigureSandbox(dict): ''' when = self._normalize_when(kwargs.get('when'), 'option') args = [self._resolve(arg) for arg in args] - kwargs = {k: self._resolve(v) for k, v in kwargs.iteritems() + kwargs = {k: self._resolve(v) for k, v in kwargs.items() if k != 'when'} option = Option(*args, **kwargs) if when: @@ -641,7 +641,7 @@ class ConfigureSandbox(dict): (k[:-len('_impl')], getattr(self, k)) for k in dir(self) if k.endswith('_impl') and k != 'template_impl' ) - glob.update((k, v) for k, v in self.iteritems() if k not in glob) + glob.update((k, v) for k, v in self.items() if k not in glob) # Any function argument to the template must be prepared to be sandboxed. # If the template itself returns a function (in which case, it's very @@ -665,7 +665,7 @@ class ConfigureSandbox(dict): def wrapper(*args, **kwargs): args = [maybe_prepare_function(arg) for arg in args] kwargs = {k: maybe_prepare_function(v) - for k, v in kwargs.iteritems()} + for k, v in kwargs.items()} ret = template(*args, **kwargs) if isfunction(ret): # We can't expect the sandboxed code to think about all the @@ -888,7 +888,7 @@ class ConfigureSandbox(dict): return func, func.func_globals glob = SandboxedGlobal( - (k, v) for k, v in func.func_globals.iteritems() + (k, v) for k, v in func.func_globals.items() if (inspect.isfunction(v) and v not in self._templates) or ( inspect.isclass(v) and issubclass(v, Exception)) ) diff --git a/python/mozbuild/mozbuild/configure/constants.py b/python/mozbuild/mozbuild/configure/constants.py index 9e30dd8418..8cc2559ca3 100644 --- a/python/mozbuild/mozbuild/configure/constants.py +++ b/python/mozbuild/mozbuild/configure/constants.py @@ -58,7 +58,7 @@ CPU_bitness = { 'x86_64': 64, } -CPU = EnumString.subclass(*CPU_bitness.keys()) +CPU = EnumString.subclass(*list(CPU_bitness.keys())) Endianness = EnumString.subclass( 'big', diff --git a/python/mozbuild/mozbuild/configure/options.py b/python/mozbuild/mozbuild/configure/options.py index 4310c8627b..da571b3c0f 100644 --- a/python/mozbuild/mozbuild/configure/options.py +++ b/python/mozbuild/mozbuild/configure/options.py @@ -96,7 +96,7 @@ class ConflictingOptionError(InvalidOptionError): if format_data: message = message.format(**format_data) super(ConflictingOptionError, self).__init__(message) - for k, v in format_data.iteritems(): + for k, v in format_data.items(): setattr(self, k, v) @@ -481,5 +481,5 @@ class CommandLineHelper(object): def __iter__(self): for d in (self._args, self._extra_args): - for arg, pos in d.itervalues(): + for arg, pos in d.values(): yield arg diff --git a/python/mozbuild/mozbuild/controller/building.py b/python/mozbuild/mozbuild/controller/building.py index 45ad97d7e8..3d1a52a2f7 100644 --- a/python/mozbuild/mozbuild/controller/building.py +++ b/python/mozbuild/mozbuild/controller/building.py @@ -108,7 +108,7 @@ class TierStatus(object): """ o = [] - for tier, state in self.tiers.items(): + for tier, state in list(self.tiers.items()): t_entry = dict( name=tier, start=state['begin_time'], @@ -644,7 +644,7 @@ class CCacheStats(object): return '\n'.join(lines) def __nonzero__(self): - relative_values = [v for k, v in self._values.items() + relative_values = [v for k, v in list(self._values.items()) if k not in self.ABSOLUTE_KEYS] return (all(v >= 0 for v in relative_values) and any(v > 0 for v in relative_values)) diff --git a/python/mozbuild/mozbuild/dotproperties.py b/python/mozbuild/mozbuild/dotproperties.py index 972ff23299..d01cd02d60 100644 --- a/python/mozbuild/mozbuild/dotproperties.py +++ b/python/mozbuild/mozbuild/dotproperties.py @@ -52,7 +52,7 @@ class DotProperties: if not prefix.endswith('.'): prefix = prefix + '.' indexes = [] - for k, v in self._properties.iteritems(): + for k, v in self._properties.items(): if not k.startswith(prefix): continue key = k[len(prefix):] @@ -73,7 +73,7 @@ class DotProperties: if not prefix.endswith('.'): prefix = prefix + '.' - D = dict((k[len(prefix):], v) for k, v in self._properties.iteritems() + D = dict((k[len(prefix):], v) for k, v in self._properties.items() if k.startswith(prefix) and '.' not in k[len(prefix):]) for required_key in required_keys: diff --git a/python/mozbuild/mozbuild/frontend/context.py b/python/mozbuild/mozbuild/frontend/context.py index 46f6d12cb5..de83dac017 100644 --- a/python/mozbuild/mozbuild/frontend/context.py +++ b/python/mozbuild/mozbuild/frontend/context.py @@ -234,15 +234,15 @@ class Context(KeyedDefaultDict): This function is transactional: if setitem fails for one of the values, the context is not updated at all.""" if isinstance(iterable, dict): - iterable = iterable.items() + iterable = list(iterable.items()) update = {} - for key, value in itertools.chain(iterable, kwargs.items()): + for key, value in itertools.chain(iterable, list(kwargs.items())): stored_type = self._validate(key, value) # Don't create an instance of stored_type if coercion is needed, # until all values are validated. update[key] = (value, stored_type) - for key, (value, stored_type) in update.items(): + for key, (value, stored_type) in list(update.items()): if not isinstance(value, stored_type): update[key] = stored_type(value) else: @@ -544,7 +544,7 @@ def ContextDerivedTypedRecord(*fields): __slots__ = tuple([name for name, _ in fields]) def __init__(self, context): - for fname, ftype in self._fields.items(): + for fname, ftype in list(self._fields.items()): if issubclass(ftype, ContextDerivedValue): setattr(self, fname, self._fields[fname](context)) else: @@ -764,7 +764,7 @@ class Files(SubContext): self.test_tags |= other.test_tags self.test_flavors |= other.test_flavors - for k, v in other.items(): + for k, v in list(other.items()): if k == 'IMPACTED_TESTS': self.test_files |= set(mozpath.relpath(e.full_path, e.context.config.topsrcdir) for e in v.files) @@ -818,7 +818,7 @@ class Files(SubContext): bug_components = Counter() - for f in files.values(): + for f in list(files.values()): bug_component = f.get('BUG_COMPONENT') if bug_component: bug_components[bug_component] += 1 @@ -1758,7 +1758,7 @@ VARIABLES = { } # Sanity check: we don't want any variable above to have a list as storage type. -for name, (storage_type, input_types, docs) in VARIABLES.items(): +for name, (storage_type, input_types, docs) in list(VARIABLES.items()): if storage_type == list: raise RuntimeError('%s has a "list" storage type. Use "List" instead.' % name) diff --git a/python/mozbuild/mozbuild/frontend/data.py b/python/mozbuild/mozbuild/frontend/data.py index c6ed4f65ef..1757f84677 100644 --- a/python/mozbuild/mozbuild/frontend/data.py +++ b/python/mozbuild/mozbuild/frontend/data.py @@ -186,7 +186,7 @@ class BaseDefines(ContextDerived): self.defines = defines def get_defines(self): - for define, value in self.defines.iteritems(): + for define, value in self.defines.items(): if value is True: yield('-D%s' % define) elif value is False: diff --git a/python/mozbuild/mozbuild/frontend/emitter.py b/python/mozbuild/mozbuild/frontend/emitter.py index faa41786ac..7c75468bbb 100644 --- a/python/mozbuild/mozbuild/frontend/emitter.py +++ b/python/mozbuild/mozbuild/frontend/emitter.py @@ -116,7 +116,7 @@ class TreeMetadataEmitter(LoggingMixin): # arguments. This gross hack works around the problem until we # rid ourselves of 2.6. self.info = {} - for k, v in mozinfo.info.items(): + for k, v in list(mozinfo.info.items()): if isinstance(k, unicode): k = k.encode('ascii') self.info[k] = v @@ -190,7 +190,7 @@ class TreeMetadataEmitter(LoggingMixin): def _emit_libs_derived(self, contexts): # First do FINAL_LIBRARY linkage. - for lib in (l for libs in self._libs.values() for l in libs): + for lib in (l for libs in list(self._libs.values()) for l in libs): if not isinstance(lib, StaticLibrary) or not lib.link_into: continue if lib.link_into not in self._libs: @@ -250,12 +250,12 @@ class TreeMetadataEmitter(LoggingMixin): lib.link_into == outerlib.basename): propagate_defines(lib, defines) - for lib in (l for libs in self._libs.values() for l in libs): + for lib in (l for libs in list(self._libs.values()) for l in libs): if isinstance(lib, Library): propagate_defines(lib, lib.lib_defines) yield lib - for obj in self._binaries.values(): + for obj in list(self._binaries.values()): yield obj LIBRARY_NAME_VAR = { @@ -314,7 +314,7 @@ class TreeMetadataEmitter(LoggingMixin): libs[key] = l if key not in libs: libs[key] = l - candidates = libs.values() + candidates = list(libs.values()) if force_static and not candidates: if dir: raise SandboxValidationError( @@ -376,7 +376,7 @@ class TreeMetadataEmitter(LoggingMixin): def _verify_deps(self, context, crate_dir, crate_name, dependencies, description='Dependency'): """Verify that a crate's dependencies all specify local paths.""" - for dep_crate_name, values in dependencies.iteritems(): + for dep_crate_name, values in dependencies.items(): # A simple version number. if isinstance(values, (str, unicode)): raise SandboxValidationError( @@ -667,7 +667,7 @@ class TreeMetadataEmitter(LoggingMixin): assert not gen_sources['UNIFIED_SOURCES'] no_pgo = context.get('NO_PGO') - no_pgo_sources = [f for f, flags in all_flags.iteritems() + no_pgo_sources = [f for f, flags in all_flags.items() if flags.no_pgo] if no_pgo: if no_pgo_sources: @@ -694,7 +694,7 @@ class TreeMetadataEmitter(LoggingMixin): # The inverse of the above, mapping suffixes to their canonical suffix. canonicalized_suffix_map = {} - for suffix, alternatives in suffix_map.iteritems(): + for suffix, alternatives in suffix_map.items(): alternatives.add(suffix) for a in alternatives: canonicalized_suffix_map[a] = suffix @@ -715,7 +715,7 @@ class TreeMetadataEmitter(LoggingMixin): # a directory with mixed C and C++ source, but it's not that important. cxx_sources = defaultdict(bool) - for variable, (klass, gen_klass, suffixes) in varmap.items(): + for variable, (klass, gen_klass, suffixes) in list(varmap.items()): allowed_suffixes = set().union(*[suffix_map[s] for s in suffixes]) # First ensure that we haven't been given filetypes that we don't @@ -741,7 +741,7 @@ class TreeMetadataEmitter(LoggingMixin): obj = cls(*arglist) yield obj - for f, flags in all_flags.iteritems(): + for f, flags in all_flags.items(): if flags.flags: ext = mozpath.splitext(f)[1] yield PerSourceFlag(context, f, flags.flags) @@ -885,7 +885,7 @@ class TreeMetadataEmitter(LoggingMixin): for obj in self._handle_linkables(context, passthru, generated_files): yield obj - generated_files.update(['%s%s' % (k, self.config.substs.get('BIN_SUFFIX', '')) for k in self._binaries.keys()]) + generated_files.update(['%s%s' % (k, self.config.substs.get('BIN_SUFFIX', '')) for k in list(self._binaries.keys())]) components = [] for var, cls in ( @@ -982,7 +982,7 @@ class TreeMetadataEmitter(LoggingMixin): for obj in self._process_jar_manifests(context): yield obj - for name, jar in context.get('JAVA_JAR_TARGETS', {}).items(): + for name, jar in list(context.get('JAVA_JAR_TARGETS', {}).items()): yield ContextWrapped(context, jar) if context.get('USE_YASM') is True: @@ -1076,7 +1076,7 @@ class TreeMetadataEmitter(LoggingMixin): yield GeneratedFile(context, script, method, outputs, inputs) def _process_test_manifests(self, context): - for prefix, info in TEST_MANIFESTS.items(): + for prefix, info in list(TEST_MANIFESTS.items()): for path, manifest in context.get('%s_MANIFESTS' % prefix, []): for obj in self._process_test_manifest(context, info, path, manifest): yield obj @@ -1167,7 +1167,7 @@ class TreeMetadataEmitter(LoggingMixin): process_support_files(test) - for path, m_defaults in mpmanifest.manifest_defaults.items(): + for path, m_defaults in list(mpmanifest.manifest_defaults.items()): process_support_files(m_defaults) # We also copy manifests into the output directory, diff --git a/python/mozbuild/mozbuild/frontend/gyp_reader.py b/python/mozbuild/mozbuild/frontend/gyp_reader.py index e6d2607032..f0ae008ad3 100644 --- a/python/mozbuild/mozbuild/frontend/gyp_reader.py +++ b/python/mozbuild/mozbuild/frontend/gyp_reader.py @@ -122,7 +122,7 @@ def read_from_gyp(config, path, output, vars, no_chromium, no_unified, action_ov # gyp expects plain str instead of unicode. The frontend code gives us # unicode strings, so convert them. path = encode(path) - str_vars = dict((name, encode(value)) for name, value in vars.items()) + str_vars = dict((name, encode(value)) for name, value in list(vars.items())) if is_msvc: # This isn't actually used anywhere in this generator, but it's needed # to override the registry detection of VC++ in gyp. diff --git a/python/mozbuild/mozbuild/frontend/mach_commands.py b/python/mozbuild/mozbuild/frontend/mach_commands.py index cbecc11375..e9bbf113bb 100644 --- a/python/mozbuild/mozbuild/frontend/mach_commands.py +++ b/python/mozbuild/mozbuild/frontend/mach_commands.py @@ -105,13 +105,13 @@ class MozbuildFileCommands(MachCommandBase): """ components = defaultdict(set) try: - for p, m in self._get_files_info(paths, rev=rev).items(): + for p, m in list(self._get_files_info(paths, rev=rev).items()): components[m.get('BUG_COMPONENT')].add(p) except InvalidPathException as e: print(e.message) return 1 - for component, files in sorted(components.items(), key=lambda x: (x is None, x)): + for component, files in sorted(list(components.items()), key=lambda x: (x is None, x)): print('%s :: %s' % (component.product, component.component) if component else 'UNKNOWN') for f in sorted(files): print(' %s' % f) @@ -139,7 +139,7 @@ class MozbuildFileCommands(MachCommandBase): help='Paths whose data to query') def file_info_test_deps(self, paths, rev=None): try: - for p, m in self._get_files_info(paths, rev=rev).items(): + for p, m in list(self._get_files_info(paths, rev=rev).items()): print('%s:' % mozpath.relpath(p, self.topsrcdir)) if m.test_files: print('\tTest file patterns:') diff --git a/python/mozbuild/mozbuild/frontend/reader.py b/python/mozbuild/mozbuild/frontend/reader.py index 165a8b7119..04a0a1735b 100644 --- a/python/mozbuild/mozbuild/frontend/reader.py +++ b/python/mozbuild/mozbuild/frontend/reader.py @@ -125,7 +125,7 @@ class EmptyConfig(object): b'JS_STANDALONE': b'1', }) udict = {} - for k, v in self.substs.items(): + for k, v in list(self.substs.items()): if isinstance(v, str): udict[k.decode('utf-8')] = v.decode('utf-8') else: @@ -388,7 +388,7 @@ class MozbuildSandbox(Sandbox): klass = self._context.__class__ self._context.__class__ = TemplateContext # The sandbox will do all the necessary checks for these merges. - for key, value in context.items(): + for key, value in list(context.items()): if isinstance(value, dict): self[key].update(value) elif isinstance(value, (list, HierarchicalStringList)): @@ -765,7 +765,7 @@ class BuildReaderError(Exception): s.write(' %s\n' % inner.args[2]) s.write('\n') close_matches = difflib.get_close_matches(inner.args[2], - VARIABLES.keys(), 2) + list(VARIABLES.keys()), 2) if close_matches: s.write('Maybe you meant %s?\n' % ' or '.join(close_matches)) s.write('\n') @@ -1129,7 +1129,7 @@ class BuildReader(object): context) non_unified_sources.add(source) action_overrides = {} - for action, script in gyp_dir.action_overrides.iteritems(): + for action, script in gyp_dir.action_overrides.items(): action_overrides[action] = SourcePath(context, script) time_start = time.time() for gyp_context in read_from_gyp(context.config, @@ -1173,7 +1173,7 @@ class BuildReader(object): recurse_info[d][key] = dict(sandbox.metadata[key]) - for path, child_metadata in recurse_info.items(): + for path, child_metadata in list(recurse_info.items()): child_path = path.join('moz.build').full_path # Ensure we don't break out of the topsrcdir. We don't do realpath @@ -1265,7 +1265,7 @@ class BuildReader(object): # There is room to improve this code (and the code in # _find_relevant_mozbuilds) to better handle multiple files in the same # directory. Bug 1136966 tracks. - for path, mbpaths in relevants.items(): + for path, mbpaths in list(relevants.items()): path_mozbuilds[path] = [mozpath.join(topsrcdir, p) for p in mbpaths] for i, mbpath in enumerate(mbpaths[0:-1]): @@ -1302,7 +1302,7 @@ class BuildReader(object): all_contexts.append(context) result = {} - for path, paths in path_mozbuilds.items(): + for path, paths in list(path_mozbuilds.items()): result[path] = reduce(lambda x, y: x + y, (contexts[p] for p in paths), []) return result, all_contexts @@ -1329,7 +1329,7 @@ class BuildReader(object): r = {} - for path, ctxs in paths.items(): + for path, ctxs in list(paths.items()): flags = Files(Context()) for ctx in ctxs: diff --git a/python/mozbuild/mozbuild/frontend/sandbox.py b/python/mozbuild/mozbuild/frontend/sandbox.py index 3638ec807c..dc220cb543 100644 --- a/python/mozbuild/mozbuild/frontend/sandbox.py +++ b/python/mozbuild/mozbuild/frontend/sandbox.py @@ -116,9 +116,9 @@ class Sandbox(dict): """Initialize a Sandbox ready for execution. """ self._builtins = ReadOnlyDict( - (builtins or self.BUILTINS).viewitems() | + (builtins or self.BUILTINS).items() | {b: __builtins__[b] for b in ('__build_class__',) - if b in __builtins__}.viewitems()) + if b in __builtins__}.items()) dict.__setitem__(self, '__builtins__', self._builtins) assert isinstance(self._builtins, ReadOnlyDict) diff --git a/python/mozbuild/mozbuild/jar.py b/python/mozbuild/mozbuild/jar.py index 7d607fd45d..f38b066059 100644 --- a/python/mozbuild/mozbuild/jar.py +++ b/python/mozbuild/mozbuild/jar.py @@ -304,7 +304,7 @@ class JarMaker(object): ''' myregister = dict.fromkeys([s.replace('%', chromebasepath) for s in register]) - addEntriesToListFile(manifestPath, myregister.iterkeys()) + addEntriesToListFile(manifestPath, iter(myregister.keys())) def makeJar(self, infile, jardir): '''makeJar is the main entry point to JarMaker. diff --git a/python/mozbuild/mozbuild/mach_commands.py b/python/mozbuild/mozbuild/mach_commands.py index 3a81b03be2..7e771674f0 100644 --- a/python/mozbuild/mozbuild/mach_commands.py +++ b/python/mozbuild/mozbuild/mach_commands.py @@ -136,7 +136,7 @@ class BuildProgressFooter(object): # terminal is a blessings.Terminal. self._t = terminal self._fh = sys.stdout - self.tiers = monitor.tiers.tier_status.viewitems() + self.tiers = monitor.tiers.tier_status.items() def clear(self): """Removes the footer from the current terminal.""" @@ -835,7 +835,7 @@ class Warnings(MachCommandBase): dirpath = None type_counts = database.type_counts(dirpath) - sorted_counts = sorted(type_counts.iteritems(), + sorted_counts = sorted(iter(type_counts.items()), key=operator.itemgetter(1)) total = 0 @@ -992,7 +992,7 @@ class GTestCommands(MachCommandBase): processes[i].run() exit_code = 0 - for process in processes.values(): + for process in list(processes.values()): status = process.wait() if status: exit_code = status diff --git a/python/mozbuild/mozbuild/mozconfig.py b/python/mozbuild/mozbuild/mozconfig.py index b2d91561e8..38adcb2109 100644 --- a/python/mozbuild/mozbuild/mozconfig.py +++ b/python/mozbuild/mozbuild/mozconfig.py @@ -311,7 +311,7 @@ class MozconfigLoader(object): # Environment variables also appear as shell variables, but that's # uninteresting duplication of information. Filter them out. - filt = lambda x, y: {k: v for k, v in x.items() if k not in y} + filt = lambda x, y: {k: v for k, v in list(x.items()) if k not in y} result['vars'] = diff_vars( filt(parsed['vars_before'], parsed['env_before']), filt(parsed['vars_after'], parsed['env_after']) diff --git a/python/mozbuild/mozbuild/preprocessor.py b/python/mozbuild/mozbuild/preprocessor.py index 2e7eed1ca6..fe9990fa8c 100644 --- a/python/mozbuild/mozbuild/preprocessor.py +++ b/python/mozbuild/mozbuild/preprocessor.py @@ -278,7 +278,7 @@ class Preprocessor: self.context = Context() for k,v in {'FILE': '', 'LINE': 0, - 'DIRECTORY': os.path.abspath('.')}.iteritems(): + 'DIRECTORY': os.path.abspath('.')}.items(): self.context[k] = v self.actionLevel = 0 self.disableLevel = 0 @@ -306,7 +306,7 @@ class Preprocessor: 'unfilter': 0, 'include': 0, 'includesubst': 0, - 'error': 0}.iteritems(): + 'error': 0}.items(): self.cmds[cmd] = (level, getattr(self, 'do_' + cmd)) self.out = sys.stdout self.setMarker(marker) @@ -677,7 +677,7 @@ class Preprocessor: current = dict(self.filters) for f in filters: current[f] = getattr(self, 'filter_' + f) - filterNames = current.keys() + filterNames = list(current.keys()) filterNames.sort() self.filters = [(fn, current[fn]) for fn in filterNames] return @@ -687,7 +687,7 @@ class Preprocessor: for f in filters: if f in current: del current[f] - filterNames = current.keys() + filterNames = list(current.keys()) filterNames.sort() self.filters = [(fn, current[fn]) for fn in filterNames] return diff --git a/python/mozbuild/mozbuild/pythonutil.py b/python/mozbuild/mozbuild/pythonutil.py index 3dba256915..e191536db5 100644 --- a/python/mozbuild/mozbuild/pythonutil.py +++ b/python/mozbuild/mozbuild/pythonutil.py @@ -11,7 +11,7 @@ import sys def iter_modules_in_path(*paths): paths = [os.path.abspath(os.path.normcase(p)) + os.sep for p in paths] - for name, module in sys.modules.items(): + for name, module in list(sys.modules.items()): if not hasattr(module, '__file__'): continue diff --git a/python/mozbuild/mozbuild/shellutil.py b/python/mozbuild/mozbuild/shellutil.py index 185a970ee5..c0c15f8f24 100644 --- a/python/mozbuild/mozbuild/shellutil.py +++ b/python/mozbuild/mozbuild/shellutil.py @@ -15,7 +15,7 @@ def _tokens2re(**tokens): # which matches the pattern and captures it in a named match group. # The group names and patterns are given as arguments. all_tokens = '|'.join('(?P<%s>%s)' % (name, value) - for name, value in tokens.iteritems()) + for name, value in tokens.items()) nonescaped = r'(? 0) + return set(k for k, v in list(self._required_directories.items()) if v > 0) class FileRegistrySubtree(object): diff --git a/python/mozbuild/mozpack/files.py b/python/mozbuild/mozpack/files.py index 6848e5ccc0..30ec630d29 100644 --- a/python/mozbuild/mozpack/files.py +++ b/python/mozbuild/mozpack/files.py @@ -1016,7 +1016,7 @@ class ComposedFinder(BaseFinder): from mozpack.copier import FileRegistry self.files = FileRegistry() - for base, finder in sorted(finders.iteritems()): + for base, finder in sorted(finders.items()): if self.files.contains(base): self.files.remove(base) for p, f in finder.find(''): diff --git a/python/mozbuild/mozpack/mozjar.py b/python/mozbuild/mozpack/mozjar.py index ddab2b4716..a94ca45b54 100644 --- a/python/mozbuild/mozpack/mozjar.py +++ b/python/mozbuild/mozpack/mozjar.py @@ -71,7 +71,7 @@ class JarStruct(object): an instance with empty fields. ''' assert self.MAGIC and isinstance(self.STRUCT, OrderedDict) - self.size_fields = set(t for t in self.STRUCT.itervalues() + self.size_fields = set(t for t in self.STRUCT.values() if not t in JarStruct.TYPE_MAPPING) self._values = {} if data: @@ -93,7 +93,7 @@ class JarStruct(object): # For all fields used as other fields sizes, keep track of their value # separately. sizes = dict((t, 0) for t in self.size_fields) - for name, t in self.STRUCT.iteritems(): + for name, t in self.STRUCT.items(): if t in JarStruct.TYPE_MAPPING: value, size = JarStruct.get_data(t, data[offset:]) else: @@ -112,7 +112,7 @@ class JarStruct(object): Initialize an instance with empty fields. ''' self.signature = self.MAGIC - for name, t in self.STRUCT.iteritems(): + for name, t in self.STRUCT.items(): if name in self.size_fields: continue self._values[name] = 0 if t in JarStruct.TYPE_MAPPING else '' @@ -137,9 +137,9 @@ class JarStruct(object): from self.STRUCT. ''' serialized = struct.pack('" % (self.__class__.__name__, @@ -373,7 +373,7 @@ class JarReader(object): entries = self.entries if not entries: return JAR_STORED - return max(f['compression'] for f in entries.itervalues()) + return max(f['compression'] for f in entries.values()) @property def entries(self): @@ -451,7 +451,7 @@ class JarReader(object): for file in jarReader: ... ''' - for entry in self.entries.itervalues(): + for entry in self.entries.values(): yield self._getreader(entry) def __getitem__(self, name): @@ -546,7 +546,7 @@ class JarWriter(object): headers = {} preload_size = 0 # Prepare central directory entries - for entry, content in self._contents.itervalues(): + for entry, content in self._contents.values(): header = JarLocalFileHeader() for name in entry.STRUCT: if name in header: @@ -561,7 +561,7 @@ class JarWriter(object): end['disk_entries'] = len(self._contents) end['cdir_entries'] = end['disk_entries'] end['cdir_size'] = reduce(lambda x, y: x + y[0].size, - self._contents.values(), 0) + list(self._contents.values()), 0) # On optimized archives, store the preloaded size and the central # directory entries, followed by the first end of central directory. if self._optimize: @@ -570,18 +570,18 @@ class JarWriter(object): if preload_size: preload_size += offset self._data.write(struct.pack('= self.maxentries: # evict according to entry's weight items = [(entry.weight, key) - for key, entry in self._dict.items()] + for key, entry in list(self._dict.items())] items.sort() index = numentries - self.prunenum if index > 0: diff --git a/python/py/py/_path/common.py b/python/py/py/_path/common.py index d407434cb2..7b5f1d25fe 100644 --- a/python/py/py/_path/common.py +++ b/python/py/py/_path/common.py @@ -45,7 +45,7 @@ class Checkers: return str(self.path).endswith(arg) def _evaluate(self, kw): - for name, value in kw.items(): + for name, value in list(kw.items()): invert = False meth = None try: diff --git a/python/py/py/_path/svnwc.py b/python/py/py/_path/svnwc.py index 4f20a75512..1581b0c8fc 100644 --- a/python/py/py/_path/svnwc.py +++ b/python/py/py/_path/svnwc.py @@ -913,7 +913,7 @@ class WCStatus: if name not in kw or kw[name]: for path in getattr(self, name): d[path] = 1 - l = d.keys() + l = list(d.keys()) if sort: l.sort() return l diff --git a/python/py/py/_xmlgen.py b/python/py/py/_xmlgen.py index 2ffcaa14b8..553747bb5d 100644 --- a/python/py/py/_xmlgen.py +++ b/python/py/py/_xmlgen.py @@ -88,7 +88,7 @@ class html(Namespace): class Style(object): def __init__(self, **kw): - for x, y in kw.items(): + for x, y in list(kw.items()): x = x.replace('_', '-') setattr(self, x, y) @@ -196,7 +196,7 @@ class SimpleUnicodeVisitor(object): except AttributeError: return [] else: - stylelist = [x+': ' + y for x,y in styledict.items()] + stylelist = [x+': ' + y for x,y in list(styledict.items())] return [u(' style="%s"') % u('; ').join(stylelist)] def _issingleton(self, tagname): @@ -237,7 +237,7 @@ class _escape: u('"') : u('"'), u('<') : u('<'), u('>') : u('>'), u('&') : u('&'), u("'") : u('''), } - self.charef_rex = re.compile(u("|").join(self.escape.keys())) + self.charef_rex = re.compile(u("|").join(list(self.escape.keys()))) def _replacer(self, match): return self.escape[match.group(0)] diff --git a/python/pyasn1/pyasn1/codec/ber/decoder.py b/python/pyasn1/pyasn1/codec/ber/decoder.py index be0cf49074..a5a51c050c 100644 --- a/python/pyasn1/pyasn1/codec/ber/decoder.py +++ b/python/pyasn1/pyasn1/codec/ber/decoder.py @@ -721,11 +721,11 @@ class Decoder: __chosenSpec = None if debug.logger and debug.logger & debug.flagDecoder: debug.logger('candidate ASN.1 spec is a map of:') - for t, v in asn1Spec.getPosMap().items(): + for t, v in list(asn1Spec.getPosMap().items()): debug.logger(' %r -> %s' % (t, v.__class__.__name__)) if asn1Spec.getNegMap(): debug.logger('but neither of: ') - for i in asn1Spec.getNegMap().items(): + for i in list(asn1Spec.getNegMap().items()): debug.logger(' %r -> %s' % (t, v.__class__.__name__)) debug.logger('new candidate ASN.1 spec is %s, chosen by %r' % (__chosenSpec is None and '' or __chosenSpec.__class__.__name__, tagSet)) else: diff --git a/python/pylru/pylru.py b/python/pylru/pylru.py index e69cadb76c..736e31e85f 100644 --- a/python/pylru/pylru.py +++ b/python/pylru/pylru.py @@ -354,16 +354,16 @@ class WriteThroughCacheManager(object): pass def __iter__(self): - return self.keys() + return list(self.keys()) def keys(self): - return self.store.keys() + return list(self.store.keys()) def values(self): - return self.store.values() + return list(self.store.values()) def items(self): - return self.store.items() + return list(self.store.items()) @@ -454,10 +454,10 @@ class WriteBackCacheManager(object): def __iter__(self): - return self.keys() + return list(self.keys()) def keys(self): - for key in self.store.keys(): + for key in list(self.store.keys()): if key not in self.dirty: yield key @@ -466,12 +466,12 @@ class WriteBackCacheManager(object): def values(self): - for key, value in self.items(): + for key, value in list(self.items()): yield value def items(self): - for key, value in self.store.items(): + for key, value in list(self.store.items()): if key not in self.dirty: yield (key, value) diff --git a/python/pylru/test.py b/python/pylru/test.py index 7a4842fb52..be8b6467c1 100644 --- a/python/pylru/test.py +++ b/python/pylru/test.py @@ -112,7 +112,7 @@ def testcache(): q2.append((x, y)) assert list(a.items()) == q2 - assert list(zip(a.keys(), a.values())) == q2 + assert list(zip(list(a.keys()), list(a.values()))) == q2 assert list(a.keys()) == list(a) @@ -141,7 +141,7 @@ def wraptest(): def verify(p, x): assert p == x.store - for key, value in x.cache.items(): + for key, value in list(x.cache.items()): assert x.store[key] == value tmp = list(x.items()) @@ -163,14 +163,14 @@ def wraptest(): def wraptest2(): def verify(p, x): - for key, value in x.store.items(): + for key, value in list(x.store.items()): if key not in x.dirty: assert p[key] == value for key in x.dirty: assert x.cache.peek(key) == p[key] - for key, value in x.cache.items(): + for key, value in list(x.cache.items()): if key not in x.dirty: assert x.store[key] == p[key] == value @@ -194,14 +194,14 @@ def wraptest2(): def wraptest3(): def verify(p, x): - for key, value in x.store.items(): + for key, value in list(x.store.items()): if key not in x.dirty: assert p[key] == value for key in x.dirty: assert x.cache.peek(key) == p[key] - for key, value in x.cache.items(): + for key, value in list(x.cache.items()): if key not in x.dirty: assert x.store[key] == p[key] == value diff --git a/python/pytest/_pytest/assertion/rewrite.py b/python/pytest/_pytest/assertion/rewrite.py index 668ab1ee6b..3bce4fb637 100644 --- a/python/pytest/_pytest/assertion/rewrite.py +++ b/python/pytest/_pytest/assertion/rewrite.py @@ -650,7 +650,7 @@ class AssertionRewriter(ast.NodeVisitor): current = self.stack.pop() if self.stack: self.explanation_specifiers = self.stack[-1] - keys = [ast.Str(key) for key in current.keys()] + keys = [ast.Str(key) for key in list(current.keys())] format_dict = ast.Dict(keys, list(current.values())) form = ast.BinOp(expl_expr, ast.Mod(), format_dict) name = "@py_format" + str(next(self.variable_counter)) diff --git a/python/pytest/_pytest/config.py b/python/pytest/_pytest/config.py index ffce11cca2..7952321fc7 100644 --- a/python/pytest/_pytest/config.py +++ b/python/pytest/_pytest/config.py @@ -325,7 +325,7 @@ class PytestPluginManager(PluginManager): self._conftestpath2mod[conftestpath] = mod dirpath = conftestpath.dirpath() if dirpath in self._path2confmods: - for path, mods in self._path2confmods.items(): + for path, mods in list(self._path2confmods.items()): if path and path.relto(dirpath) or path == dirpath: assert mod not in mods mods.append(mod) @@ -485,7 +485,7 @@ class Parser: def parse_setoption(self, args, option, namespace=None): parsedoption = self.parse(args, namespace=namespace) - for name, value in parsedoption.__dict__.items(): + for name, value in list(parsedoption.__dict__.items()): setattr(option, name, value) return getattr(parsedoption, FILE_OR_DIR) @@ -1142,7 +1142,7 @@ def determine_setup(inifile, args): def setns(obj, dic): import pytest - for name, value in dic.items(): + for name, value in list(dic.items()): if isinstance(value, dict): mod = getattr(obj, name, None) if mod is None: diff --git a/python/pytest/_pytest/mark.py b/python/pytest/_pytest/mark.py index d8b60def36..5b20f3afbb 100644 --- a/python/pytest/_pytest/mark.py +++ b/python/pytest/_pytest/mark.py @@ -96,7 +96,7 @@ class MarkMapping: resolves to True if the marker is present. """ def __init__(self, keywords): mymarks = set() - for key, value in keywords.items(): + for key, value in list(keywords.items()): if isinstance(value, MarkInfo) or isinstance(value, MarkDecorator): mymarks.add(key) self._mymarks = mymarks diff --git a/python/pytest/_pytest/python.py b/python/pytest/_pytest/python.py index 0c62c1cb9e..503cb7e325 100644 --- a/python/pytest/_pytest/python.py +++ b/python/pytest/_pytest/python.py @@ -517,7 +517,7 @@ def add_funcarg_pseudo_fixture_def(collector, metafunc, fixturemanager): arg2params = {} arg2scope = {} for callspec in metafunc._calls: - for argname, argvalue in callspec.funcargs.items(): + for argname, argvalue in list(callspec.funcargs.items()): assert argname not in callspec.params callspec.params[argname] = argvalue arg2params_list = arg2params.setdefault(argname, []) @@ -532,7 +532,7 @@ def add_funcarg_pseudo_fixture_def(collector, metafunc, fixturemanager): # register artificial FixtureDef's so that later at test execution # time we can rely on a proper FixtureDef to exist for fixture setup. arg2fixturedefs = metafunc._arg2fixturedefs - for argname, valuelist in arg2params.items(): + for argname, valuelist in list(arg2params.items()): # if we have a scope that is higher than function we need # to make sure we only ever create an according fixturedef on # a per-scope basis. We thus store and cache the fixturedef on the @@ -1164,7 +1164,7 @@ def _showfixtures_main(config, session): fm = session._fixturemanager available = [] - for argname, fixturedefs in fm._arg2fixturedefs.items(): + for argname, fixturedefs in list(fm._arg2fixturedefs.items()): assert fixturedefs is not None if not fixturedefs: continue @@ -1786,7 +1786,7 @@ class FixtureLookupError(LookupError): if msg is None: fm = self.request._fixturemanager available = [] - for name, fixturedef in fm._arg2fixturedefs.items(): + for name, fixturedef in list(fm._arg2fixturedefs.items()): parentid = self.request._pyfuncitem.parent.nodeid faclist = list(fm._matchfactories(fixturedef, parentid)) if faclist: @@ -2257,7 +2257,7 @@ def get_parametrized_fixture_keys(item, scopenum): # cs.indictes.items() is random order of argnames but # then again different functions (items) can change order of # arguments so it doesn't matter much probably - for argname, param_index in cs.indices.items(): + for argname, param_index in list(cs.indices.items()): if cs._arg2scopenum[argname] != scopenum: continue if scopenum == 0: # session diff --git a/python/pytest/_pytest/runner.py b/python/pytest/_pytest/runner.py index cde94c8c89..8b1bef3a72 100644 --- a/python/pytest/_pytest/runner.py +++ b/python/pytest/_pytest/runner.py @@ -31,7 +31,7 @@ def pytest_terminal_summary(terminalreporter): return tr = terminalreporter dlist = [] - for replist in tr.stats.values(): + for replist in list(tr.stats.values()): for rep in replist: if hasattr(rep, 'duration'): dlist.append(rep) diff --git a/python/pytest/_pytest/skipping.py b/python/pytest/_pytest/skipping.py index 18e038d2c8..8a3c8171e8 100644 --- a/python/pytest/_pytest/skipping.py +++ b/python/pytest/_pytest/skipping.py @@ -338,7 +338,7 @@ def folded_skips(skipped): assert len(key) == 3, (event, key) d.setdefault(key, []).append(event) l = [] - for key, events in d.items(): + for key, events in list(d.items()): l.append((len(events),) + key) return l diff --git a/python/pytest/_pytest/terminal.py b/python/pytest/_pytest/terminal.py index 825f553ef2..620365acec 100644 --- a/python/pytest/_pytest/terminal.py +++ b/python/pytest/_pytest/terminal.py @@ -549,7 +549,7 @@ def build_summary_stats_line(stats): "xfailed xpassed warnings error").split() key_translation = {'warnings': 'pytest-warnings'} unknown_key_seen = False - for key in stats.keys(): + for key in list(stats.keys()): if key not in keys: if key: # setup/teardown reports have an empty key, ignore them keys.append(key) diff --git a/python/pytest/_pytest/vendored_packages/pluggy.py b/python/pytest/_pytest/vendored_packages/pluggy.py index 2f848b23d3..7d94134571 100644 --- a/python/pytest/_pytest/vendored_packages/pluggy.py +++ b/python/pytest/_pytest/vendored_packages/pluggy.py @@ -189,7 +189,7 @@ class _TagTracer: "%s%s [%s]\n" % (indent, content, ":".join(tags)) ] - for name, value in extra.items(): + for name, value in list(extra.items()): lines.append("%s %s: %s\n" % (indent, name, value)) return lines @@ -457,7 +457,7 @@ class PluginManager(object): def get_name(self, plugin): """ Return name for registered plugin or None if not registered. """ - for name, val in self._name2plugin.items(): + for name, val in list(self._name2plugin.items()): if plugin == val: return name diff --git a/python/pytoml/pytoml/writer.py b/python/pytoml/pytoml/writer.py index 2c9f7c69d9..7fb44901a5 100644 --- a/python/pytoml/pytoml/writer.py +++ b/python/pytoml/pytoml/writer.py @@ -102,7 +102,7 @@ def dump(fout, obj, sort_keys=False): else: fout.write('[{0}]\n'.format(section_name)) - table_keys = sorted(table.keys()) if sort_keys else table.keys() + table_keys = sorted(table.keys()) if sort_keys else list(table.keys()) for k in table_keys: v = table[k] if isinstance(v, dict): diff --git a/python/pyyaml/lib/yaml/constructor.py b/python/pyyaml/lib/yaml/constructor.py index 635faac3e6..e30a04586a 100644 --- a/python/pyyaml/lib/yaml/constructor.py +++ b/python/pyyaml/lib/yaml/constructor.py @@ -559,7 +559,7 @@ class Constructor(SafeConstructor): instance.__dict__.update(state) elif state: slotstate.update(state) - for key, value in slotstate.items(): + for key, value in list(slotstate.items()): setattr(object, key, value) def construct_python_object(self, suffix, node): diff --git a/python/pyyaml/lib/yaml/emitter.py b/python/pyyaml/lib/yaml/emitter.py index e5bcdcccbb..8d23a9ec8c 100644 --- a/python/pyyaml/lib/yaml/emitter.py +++ b/python/pyyaml/lib/yaml/emitter.py @@ -185,7 +185,7 @@ class Emitter(object): self.write_version_directive(version_text) self.tag_prefixes = self.DEFAULT_TAG_PREFIXES.copy() if self.event.tags: - handles = self.event.tags.keys() + handles = list(self.event.tags.keys()) handles.sort() for handle in handles: prefix = self.event.tags[handle] @@ -586,7 +586,7 @@ class Emitter(object): return tag handle = None suffix = tag - prefixes = self.tag_prefixes.keys() + prefixes = list(self.tag_prefixes.keys()) prefixes.sort() for prefix in prefixes: if tag.startswith(prefix) \ diff --git a/python/pyyaml/lib/yaml/representer.py b/python/pyyaml/lib/yaml/representer.py index 5f4fc70dbc..be747c4931 100644 --- a/python/pyyaml/lib/yaml/representer.py +++ b/python/pyyaml/lib/yaml/representer.py @@ -116,7 +116,7 @@ class BaseRepresenter(object): self.represented_objects[self.alias_key] = node best_style = True if hasattr(mapping, 'items'): - mapping = mapping.items() + mapping = list(mapping.items()) mapping.sort() for item_key, item_value in mapping: node_key = self.represent_data(item_key) diff --git a/python/pyyaml/lib/yaml/scanner.py b/python/pyyaml/lib/yaml/scanner.py index 5228fad65c..53042fca67 100644 --- a/python/pyyaml/lib/yaml/scanner.py +++ b/python/pyyaml/lib/yaml/scanner.py @@ -280,7 +280,7 @@ class Scanner(object): # - should be no longer than 1024 characters. # Disabling this procedure will allow simple keys of any length and # height (may cause problems if indentation is broken though). - for level in self.possible_simple_keys.keys(): + for level in list(self.possible_simple_keys.keys()): key = self.possible_simple_keys[level] if key.line != self.line \ or self.index-key.index > 1024: diff --git a/python/pyyaml/lib3/yaml/constructor.py b/python/pyyaml/lib3/yaml/constructor.py index 981543aebb..e0452f0949 100644 --- a/python/pyyaml/lib3/yaml/constructor.py +++ b/python/pyyaml/lib3/yaml/constructor.py @@ -566,7 +566,7 @@ class Constructor(SafeConstructor): instance.__dict__.update(state) elif state: slotstate.update(state) - for key, value in slotstate.items(): + for key, value in list(slotstate.items()): setattr(object, key, value) def construct_python_object(self, suffix, node): diff --git a/python/requests/requests/adapters.py b/python/requests/requests/adapters.py index 6266d5be30..9ee1407584 100644 --- a/python/requests/requests/adapters.py +++ b/python/requests/requests/adapters.py @@ -112,7 +112,7 @@ class HTTPAdapter(BaseAdapter): self.proxy_manager = {} self.config = {} - for attr, value in state.items(): + for attr, value in list(state.items()): setattr(self, attr, value) self.init_poolmanager(self._pool_connections, self._pool_maxsize, @@ -388,7 +388,7 @@ class HTTPAdapter(BaseAdapter): url, skip_accept_encoding=True) - for header, value in request.headers.items(): + for header, value in list(request.headers.items()): low_conn.putheader(header, value) low_conn.endheaders() diff --git a/python/requests/requests/cookies.py b/python/requests/requests/cookies.py index b85fd2b626..6a15fe5990 100644 --- a/python/requests/requests/cookies.py +++ b/python/requests/requests/cookies.py @@ -214,7 +214,7 @@ class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping): def keys(self): """Dict-like keys() that returns a list of names of cookies from the jar. See values() and items().""" - return list(self.iterkeys()) + return list(self.keys()) def itervalues(self): """Dict-like itervalues() that returns an iterator of values of cookies @@ -225,7 +225,7 @@ class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping): def values(self): """Dict-like values() that returns a list of values of cookies from the jar. See keys() and items().""" - return list(self.itervalues()) + return list(self.values()) def iteritems(self): """Dict-like iteritems() that returns an iterator of name-value tuples @@ -238,7 +238,7 @@ class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping): jar. See keys() and values(). Allows client-code to call ``dict(RequestsCookieJar)`` and get a vanilla python dict of key value pairs.""" - return list(self.iteritems()) + return list(self.items()) def list_domains(self): """Utility method to list all the domains in the jar.""" diff --git a/python/requests/requests/models.py b/python/requests/requests/models.py index 4bcbc5484a..66a6d94194 100644 --- a/python/requests/requests/models.py +++ b/python/requests/requests/models.py @@ -402,7 +402,7 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin): """Prepares the given HTTP headers.""" if headers: - self.headers = CaseInsensitiveDict((to_native_string(name), value) for name, value in headers.items()) + self.headers = CaseInsensitiveDict((to_native_string(name), value) for name, value in list(headers.items())) else: self.headers = CaseInsensitiveDict() @@ -595,7 +595,7 @@ class Response(object): ) def __setstate__(self, state): - for name, value in state.items(): + for name, value in list(state.items()): setattr(self, name, value) # pickled objects do not have .raw diff --git a/python/requests/requests/packages/urllib3/_collections.py b/python/requests/requests/packages/urllib3/_collections.py index 67f3ce994d..4b3bf70171 100644 --- a/python/requests/requests/packages/urllib3/_collections.py +++ b/python/requests/requests/packages/urllib3/_collections.py @@ -179,7 +179,7 @@ class HTTPHeaderDict(MutableMapping): def __iter__(self): # Only provide the originally cased names - for vals in self._container.values(): + for vals in list(self._container.values()): yield vals[0] def pop(self, key, default=__marker): @@ -239,19 +239,19 @@ class HTTPHeaderDict(MutableMapping): other = args[0] if len(args) >= 1 else () if isinstance(other, HTTPHeaderDict): - for key, val in other.iteritems(): + for key, val in other.items(): self.add(key, val) elif isinstance(other, Mapping): for key in other: self.add(key, other[key]) elif hasattr(other, "keys"): - for key in other.keys(): + for key in list(other.keys()): self.add(key, other[key]) else: for key, value in other: self.add(key, value) - for key, value in kwargs.items(): + for key, value in list(kwargs.items()): self.add(key, value) def getlist(self, key): @@ -302,7 +302,7 @@ class HTTPHeaderDict(MutableMapping): yield val[0], ', '.join(val[1:]) def items(self): - return list(self.iteritems()) + return list(self.items()) @classmethod def from_httplib(cls, message): # Python 2 diff --git a/python/requests/requests/packages/urllib3/fields.py b/python/requests/requests/packages/urllib3/fields.py index c7d48113bd..6275547eb7 100644 --- a/python/requests/requests/packages/urllib3/fields.py +++ b/python/requests/requests/packages/urllib3/fields.py @@ -127,7 +127,7 @@ class RequestField(object): parts = [] iterable = header_parts if isinstance(header_parts, dict): - iterable = header_parts.items() + iterable = list(header_parts.items()) for name, value in iterable: if value: @@ -146,7 +146,7 @@ class RequestField(object): if self.headers.get(sort_key, False): lines.append('%s: %s' % (sort_key, self.headers[sort_key])) - for header_name, header_value in self.headers.items(): + for header_name, header_value in list(self.headers.items()): if header_name not in sort_keys: if header_value: lines.append('%s: %s' % (header_name, header_value)) diff --git a/python/requests/requests/packages/urllib3/packages/ordered_dict.py b/python/requests/requests/packages/urllib3/packages/ordered_dict.py index 4479363cc4..b92636db7d 100644 --- a/python/requests/requests/packages/urllib3/packages/ordered_dict.py +++ b/python/requests/requests/packages/urllib3/packages/ordered_dict.py @@ -79,7 +79,7 @@ class OrderedDict(dict): def clear(self): 'od.clear() -> None. Remove all items from od.' try: - for node in self.__map.itervalues(): + for node in self.__map.values(): del node[:] root = self.__root root[:] = [root, root, None] @@ -162,12 +162,12 @@ class OrderedDict(dict): for key in other: self[key] = other[key] elif hasattr(other, 'keys'): - for key in other.keys(): + for key in list(other.keys()): self[key] = other[key] else: for key, value in other: self[key] = value - for key, value in kwds.items(): + for key, value in list(kwds.items()): self[key] = value __update = update # let subclasses override update without breaking __init__ @@ -203,7 +203,7 @@ class OrderedDict(dict): try: if not self: return '%s()' % (self.__class__.__name__,) - return '%s(%r)' % (self.__class__.__name__, self.items()) + return '%s(%r)' % (self.__class__.__name__, list(self.items())) finally: del _repr_running[call_key] @@ -238,7 +238,7 @@ class OrderedDict(dict): ''' if isinstance(other, OrderedDict): - return len(self)==len(other) and self.items() == other.items() + return len(self)==len(other) and list(self.items()) == list(other.items()) return dict.__eq__(self, other) def __ne__(self, other): diff --git a/python/requests/requests/packages/urllib3/response.py b/python/requests/requests/packages/urllib3/response.py index 8f2a1b5c29..e88ee7ac43 100644 --- a/python/requests/requests/packages/urllib3/response.py +++ b/python/requests/requests/packages/urllib3/response.py @@ -359,7 +359,7 @@ class HTTPResponse(io.IOBase): if not isinstance(headers, HTTPHeaderDict): if PY3: # Python 3 - headers = HTTPHeaderDict(headers.items()) + headers = HTTPHeaderDict(list(headers.items())) else: # Python 2 headers = HTTPHeaderDict.from_httplib(headers) diff --git a/python/requests/requests/sessions.py b/python/requests/requests/sessions.py index 9eaa36ae43..ce72e617b9 100644 --- a/python/requests/requests/sessions.py +++ b/python/requests/requests/sessions.py @@ -64,7 +64,7 @@ def merge_setting(request_setting, session_setting, dict_class=OrderedDict): # Remove keys that are set to None. Extract keys first to avoid altering # the dictionary during iteration. - none_keys = [k for (k, v) in merged_setting.items() if v is None] + none_keys = [k for (k, v) in list(merged_setting.items()) if v is None] for key in none_keys: del merged_setting[key] @@ -615,7 +615,7 @@ class Session(SessionRedirectMixin): if self.trust_env: # Set environment's proxies. env_proxies = get_environ_proxies(url) or {} - for (k, v) in env_proxies.items(): + for (k, v) in list(env_proxies.items()): proxies.setdefault(k, v) # Look for requests environment configuration and be compatible @@ -635,7 +635,7 @@ class Session(SessionRedirectMixin): def get_adapter(self, url): """Returns the appropriate connection adapter for the given URL.""" - for (prefix, adapter) in self.adapters.items(): + for (prefix, adapter) in list(self.adapters.items()): if url.lower().startswith(prefix): return adapter @@ -645,7 +645,7 @@ class Session(SessionRedirectMixin): def close(self): """Closes all adapters and as such the session""" - for v in self.adapters.values(): + for v in list(self.adapters.values()): v.close() def mount(self, prefix, adapter): @@ -666,11 +666,11 @@ class Session(SessionRedirectMixin): def __setstate__(self, state): redirect_cache = state.pop('redirect_cache', {}) - for attr, value in state.items(): + for attr, value in list(state.items()): setattr(self, attr, value) self.redirect_cache = RecentlyUsedContainer(REDIRECT_CACHE_SIZE) - for redirect, to in redirect_cache.items(): + for redirect, to in list(redirect_cache.items()): self.redirect_cache[redirect] = to diff --git a/python/requests/requests/status_codes.py b/python/requests/requests/status_codes.py index a852574a45..84394b1cea 100644 --- a/python/requests/requests/status_codes.py +++ b/python/requests/requests/status_codes.py @@ -83,7 +83,7 @@ _codes = { codes = LookupDict(name='status_codes') -for code, titles in _codes.items(): +for code, titles in list(_codes.items()): for title in titles: setattr(codes, title, code) if not title.startswith('\\'): diff --git a/python/requests/requests/structures.py b/python/requests/requests/structures.py index 3e5f2faa2e..f228ceb761 100644 --- a/python/requests/requests/structures.py +++ b/python/requests/requests/structures.py @@ -57,7 +57,7 @@ class CaseInsensitiveDict(collections.MutableMapping): del self._store[key.lower()] def __iter__(self): - return (casedkey for casedkey, mappedvalue in self._store.values()) + return (casedkey for casedkey, mappedvalue in list(self._store.values())) def __len__(self): return len(self._store) @@ -67,7 +67,7 @@ class CaseInsensitiveDict(collections.MutableMapping): return ( (lowerkey, keyval[1]) for (lowerkey, keyval) - in self._store.items() + in list(self._store.items()) ) def __eq__(self, other): @@ -80,10 +80,10 @@ class CaseInsensitiveDict(collections.MutableMapping): # Copy is required def copy(self): - return CaseInsensitiveDict(self._store.values()) + return CaseInsensitiveDict(list(self._store.values())) def __repr__(self): - return str(dict(self.items())) + return str(dict(list(self.items()))) class LookupDict(dict): """Dictionary lookup object.""" diff --git a/python/requests/requests/utils.py b/python/requests/requests/utils.py index c5c3fd01d9..0b0f930dcd 100644 --- a/python/requests/requests/utils.py +++ b/python/requests/requests/utils.py @@ -42,7 +42,7 @@ def dict_to_sequence(d): """Returns an internal sequence dictionary update.""" if hasattr(d, 'items'): - d = d.items() + d = list(d.items()) return d @@ -190,7 +190,7 @@ def to_key_val_list(value): raise ValueError('cannot encode objects that are not 2-tuples') if isinstance(value, collections.Mapping): - value = value.items() + value = list(value.items()) return list(value) diff --git a/python/requests/test_requests.py b/python/requests/test_requests.py index 0795241867..e9689b8bd1 100755 --- a/python/requests/test_requests.py +++ b/python/requests/test_requests.py @@ -719,8 +719,8 @@ class TestRequests(object): jar.set(key1, value1) d1 = dict(jar) - d2 = dict(jar.iteritems()) - d3 = dict(jar.items()) + d2 = dict(iter(jar.items())) + d3 = dict(list(jar.items())) assert len(jar) == 2 assert len(d1) == 2 @@ -739,8 +739,8 @@ class TestRequests(object): jar.set(key1, value1) d1 = dict(jar) - d2 = dict(jar.iteritems()) - d3 = dict(jar.items()) + d2 = dict(iter(jar.items())) + d3 = dict(list(jar.items())) assert d1['some_cookie'] == 'some_value' assert d2['some_cookie'] == 'some_value' @@ -757,7 +757,7 @@ class TestRequests(object): jar.set(key, value) jar.set(key1, value1) - keys = jar.keys() + keys = list(jar.keys()) assert keys == list(keys) # make sure one can use keys multiple times assert list(keys) == list(keys) @@ -773,7 +773,7 @@ class TestRequests(object): jar.set(key, value) jar.set(key1, value1) - values = jar.values() + values = list(jar.values()) assert values == list(values) # make sure one can use values multiple times assert list(values) == list(values) @@ -789,7 +789,7 @@ class TestRequests(object): jar.set(key, value) jar.set(key1, value1) - items = jar.items() + items = list(jar.items()) assert items == list(items) # make sure one can use items multiple times assert list(items) == list(items) @@ -977,8 +977,8 @@ class TestRequests(object): # This is testing that they are builtin strings. A bit weird, but there # we go. - assert 'unicode' in p.headers.keys() - assert 'byte' in p.headers.keys() + assert 'unicode' in list(p.headers.keys()) + assert 'byte' in list(p.headers.keys()) def test_can_send_nonstring_objects_with_files(self, httpbin): data = {'a': 0.0} @@ -1305,8 +1305,8 @@ class TestCaseInsensitiveDict(unittest.TestCase): 'user-Agent': 'requests', }) keyset = frozenset(['Accept', 'user-Agent']) - assert frozenset(i[0] for i in cid.items()) == keyset - assert frozenset(cid.keys()) == keyset + assert frozenset(i[0] for i in list(cid.items())) == keyset + assert frozenset(list(cid.keys())) == keyset assert frozenset(cid) == keyset def test_preserve_last_key_case(self): @@ -1317,8 +1317,8 @@ class TestCaseInsensitiveDict(unittest.TestCase): cid.update({'ACCEPT': 'application/json'}) cid['USER-AGENT'] = 'requests' keyset = frozenset(['ACCEPT', 'USER-AGENT']) - assert frozenset(i[0] for i in cid.items()) == keyset - assert frozenset(cid.keys()) == keyset + assert frozenset(i[0] for i in list(cid.items())) == keyset + assert frozenset(list(cid.keys())) == keyset assert frozenset(cid) == keyset def test_copy(self): diff --git a/python/rsa/rsa/pkcs1.py b/python/rsa/rsa/pkcs1.py index 9d26ba7b13..0979d506a1 100644 --- a/python/rsa/rsa/pkcs1.py +++ b/python/rsa/rsa/pkcs1.py @@ -364,7 +364,7 @@ def _find_method_hash(method_hash): ''' - for (hashname, asn1code) in HASH_ASN1.items(): + for (hashname, asn1code) in list(HASH_ASN1.items()): if not method_hash.startswith(asn1code): continue diff --git a/python/slugid/test.py b/python/slugid/test.py index 55103453a3..b09513f6ed 100644 --- a/python/slugid/test.py +++ b/python/slugid/test.py @@ -154,7 +154,7 @@ def spreadTest(generator, expected): actual = [] for j in range(0, len(k)): actual.append('') - for a in k[j].keys(): + for a in list(k[j].keys()): if k[j][a] > 0: actual[j] += a # sort for easy comparison diff --git a/python/virtualenv/site.py b/python/virtualenv/site.py index 04af3ed698..ad07af9e21 100644 --- a/python/virtualenv/site.py +++ b/python/virtualenv/site.py @@ -104,7 +104,7 @@ def makepath(*paths): def abs__file__(): """Set all module' __file__ attribute to an absolute path""" - for m in sys.modules.values(): + for m in list(sys.modules.values()): if ((_is_jython and not isinstance(m, ModuleType)) or hasattr(m, '__loader__')): # only modules need the abspath in Jython. and don't mess diff --git a/python/virtualenv/virtualenv.py b/python/virtualenv/virtualenv.py index 54928099a8..c6e38d156c 100755 --- a/python/virtualenv/virtualenv.py +++ b/python/virtualenv/virtualenv.py @@ -457,7 +457,7 @@ class ConfigOptionParser(optparse.OptionParser): # 2. environmental variables config.update(dict(self.get_environ_vars())) # Then set the options with those values - for key, val in config.items(): + for key, val in list(config.items()): key = key.replace('_', '-') if not key.startswith('--'): key = '--%s' % key # only prefer long opts @@ -496,7 +496,7 @@ class ConfigOptionParser(optparse.OptionParser): """ Returns a generator with all environmental vars with prefix VIRTUALENV """ - for key, val in os.environ.items(): + for key, val in list(os.environ.items()): if key.startswith(prefix): yield (key.replace(prefix, '').lower(), val) @@ -1468,7 +1468,7 @@ def install_files(home_dir, bin_dir, prompt, files): if hasattr(home_dir, 'decode'): home_dir = home_dir.decode(sys.getfilesystemencoding()) vname = os.path.basename(home_dir) - for name, content in files.items(): + for name, content in list(files.items()): content = content.replace('__VIRTUAL_PROMPT__', prompt or '') content = content.replace('__VIRTUAL_WINPROMPT__', prompt or '(%s)' % vname) content = content.replace('__VIRTUAL_ENV__', home_dir) @@ -1482,7 +1482,7 @@ def install_python_config(home_dir, bin_dir, prompt=None): else: files = {'python-config': PYTHON_CONFIG} install_files(home_dir, bin_dir, prompt, files) - for name, content in files.items(): + for name, content in list(files.items()): make_exe(os.path.join(bin_dir, name)) def install_distutils(home_dir): @@ -1528,7 +1528,7 @@ def fix_lib64(lib_dir, symlink=True): logger.debug('PyPy detected, skipping lib64 symlinking') return # Check we have a lib64 library path - if not [p for p in distutils.sysconfig.get_config_vars().values() + if not [p for p in list(distutils.sysconfig.get_config_vars().values()) if isinstance(p, basestring) and 'lib64' in p]: return diff --git a/python/virtualenv/virtualenv_embedded/site.py b/python/virtualenv/virtualenv_embedded/site.py index bda518f65f..867f7026f2 100644 --- a/python/virtualenv/virtualenv_embedded/site.py +++ b/python/virtualenv/virtualenv_embedded/site.py @@ -99,7 +99,7 @@ def makepath(*paths): def abs__file__(): """Set all module' __file__ attribute to an absolute path""" - for m in sys.modules.values(): + for m in list(sys.modules.values()): if ((_is_jython and not isinstance(m, ModuleType)) or hasattr(m, '__loader__')): # only modules need the abspath in Jython. and don't mess diff --git a/python/voluptuous/voluptuous.py b/python/voluptuous/voluptuous.py index 132c3c476f..1ad99a6914 100644 --- a/python/voluptuous/voluptuous.py +++ b/python/voluptuous/voluptuous.py @@ -99,11 +99,11 @@ if sys.version_info >= (3,): unicode = str basestring = str ifilter = filter - iteritems = lambda d: d.items() + iteritems = lambda d: list(d.items()) else: from itertools import ifilter import urlparse - iteritems = lambda d: d.iteritems() + iteritems = lambda d: iter(d.items()) __author__ = 'Alec Thomas ' @@ -619,7 +619,7 @@ class Schema(object): raise DictInvalid('expected a dictionary', path) errors = [] - for label, group in groups_of_exclusion.items(): + for label, group in list(groups_of_exclusion.items()): exists = False for exclusive in group: if exclusive.schema in data: @@ -634,7 +634,7 @@ class Schema(object): if errors: raise MultipleInvalid(errors) - for label, group in groups_of_inclusion.items(): + for label, group in list(groups_of_inclusion.items()): included = [node.schema in data for node in group] if any(included) and not all(included): msg = "some but not all values in the same group of inclusion '%s'" % label diff --git a/python/which/build.py b/python/which/build.py index 0337df7b90..7d6de66db8 100644 --- a/python/which/build.py +++ b/python/which/build.py @@ -179,7 +179,7 @@ def _setup_logging(): def _getTargets(): """Find all targets and return a dict of targetName:targetFunc items.""" targets = {} - for name, attr in sys.modules[__name__].__dict__.items(): + for name, attr in list(sys.modules[__name__].__dict__.items()): if name.startswith('target_'): targets[ name[len('target_'):] ] = attr return targets @@ -188,7 +188,7 @@ def _listTargets(targets): """Pretty print a list of targets.""" width = 77 nameWidth = 15 # min width - for name in targets.keys(): + for name in list(targets.keys()): nameWidth = max(nameWidth, len(name)) nameWidth += 2 # space btwn name and doc format = "%%-%ds%%s" % nameWidth diff --git a/security/manager/ssl/tests/unit/test_cert_version/generate.py b/security/manager/ssl/tests/unit/test_cert_version/generate.py index b99cbefe2c..39f69f7a07 100755 --- a/security/manager/ssl/tests/unit/test_cert_version/generate.py +++ b/security/manager/ssl/tests/unit/test_cert_version/generate.py @@ -58,10 +58,10 @@ basicConstraintsCA = 'extension:basicConstraints:cA,' writeCertspec('ca', 'ca', [keyUsage, basicConstraintsCA]) -for versionStr, versionVal in versions.iteritems(): +for versionStr, versionVal in versions.items(): # intermediates versionText = 'version:%s' % versionVal - for basicConstraintsType, basicConstraintsExtension in basicConstraintsTypes.iteritems(): + for basicConstraintsType, basicConstraintsExtension in basicConstraintsTypes.items(): intermediateName = 'int-%s-%s' % (versionStr, basicConstraintsType) writeCertspec('ca', intermediateName, [keyUsage, versionText, basicConstraintsExtension]) @@ -69,13 +69,13 @@ for versionStr, versionVal in versions.iteritems(): # end-entities versionText = 'version:%s' % versionVal - for basicConstraintsType, basicConstraintsExtension in basicConstraintsTypes.iteritems(): + for basicConstraintsType, basicConstraintsExtension in basicConstraintsTypes.items(): writeCertspec('ca', 'ee-%s-%s' % (versionStr, basicConstraintsType), [versionText, basicConstraintsExtension]) # self-signed certificates versionText = 'version:%s' % versionVal - for basicConstraintsType, basicConstraintsExtension in basicConstraintsTypes.iteritems(): + for basicConstraintsType, basicConstraintsExtension in basicConstraintsTypes.items(): selfSignedName = 'ss-%s-%s' % (versionStr, basicConstraintsType) writeCertspec(selfSignedName, selfSignedName, [versionText, basicConstraintsExtension]) diff --git a/security/nss/gtests/google_test/gtest/scripts/upload.py b/security/nss/gtests/google_test/gtest/scripts/upload.py index a204b55aa3..30e07b5a91 100755 --- a/security/nss/gtests/google_test/gtest/scripts/upload.py +++ b/security/nss/gtests/google_test/gtest/scripts/upload.py @@ -180,7 +180,7 @@ class AbstractRpcServer(object): req = urllib2.Request(url, data=data) if self.host_override: req.add_header("Host", self.host_override) - for key, value in self.extra_headers.iteritems(): + for key, value in self.extra_headers.items(): req.add_header(key, value) return req @@ -713,7 +713,7 @@ class VersionControlSystem(object): patches = dict() [patches.setdefault(v, k) for k, v in patch_list] - for filename in patches.keys(): + for filename in list(patches.keys()): base_content, new_content, is_binary, status = files[filename] file_id_str = patches.get(filename) if file_id_str.find("nobase") != -1: @@ -1339,7 +1339,7 @@ def RealMain(argv, data=None): # Send a hash of all the base file so the server can determine if a copy # already exists in an earlier patchset. base_hashes = "" - for file, info in files.iteritems(): + for file, info in files.items(): if not info[0] is None: checksum = md5.new(info[0]).hexdigest() if base_hashes: diff --git a/security/nss/gtests/google_test/gtest/test/gtest_json_test_utils.py b/security/nss/gtests/google_test/gtest/test/gtest_json_test_utils.py index 62bbfc288f..ca26bf7c4f 100644 --- a/security/nss/gtests/google_test/gtest/test/gtest_json_test_utils.py +++ b/security/nss/gtests/google_test/gtest/test/gtest_json_test_utils.py @@ -53,7 +53,7 @@ def normalize(obj): else: return normalize(value) if isinstance(obj, dict): - return {k: _normalize(k, v) for k, v in obj.items()} + return {k: _normalize(k, v) for k, v in list(obj.items())} if isinstance(obj, list): return [normalize(x) for x in obj] else: diff --git a/security/nss/gtests/google_test/gtest/test/gtest_test_utils.py b/security/nss/gtests/google_test/gtest/test/gtest_test_utils.py index c7f25aa932..9850c8eb05 100755 --- a/security/nss/gtests/google_test/gtest/test/gtest_test_utils.py +++ b/security/nss/gtests/google_test/gtest/test/gtest_test_utils.py @@ -251,7 +251,7 @@ class Subprocess: # Changes made by os.environ.clear are not inheritable by child # processes until Python 2.6. To produce inheritable changes we have # to delete environment items with the del statement. - for key in dest.keys(): + for key in list(dest.keys()): del dest[key] dest.update(src) diff --git a/security/nss/gtests/google_test/gtest/test/gtest_xml_test_utils.py b/security/nss/gtests/google_test/gtest/test/gtest_xml_test_utils.py index ec42c62c3b..018a849d91 100755 --- a/security/nss/gtests/google_test/gtest/test/gtest_xml_test_utils.py +++ b/security/nss/gtests/google_test/gtest/test/gtest_xml_test_utils.py @@ -74,8 +74,8 @@ class GTestXMLTestCase(gtest_test_utils.TestCase): self.assertEquals( expected_attributes.length, actual_attributes.length, 'attribute numbers differ in element %s:\nExpected: %r\nActual: %r' % ( - actual_node.tagName, expected_attributes.keys(), - actual_attributes.keys())) + actual_node.tagName, list(expected_attributes.keys()), + list(actual_attributes.keys()))) for i in range(expected_attributes.length): expected_attr = expected_attributes.item(i) actual_attr = actual_attributes.get(expected_attr.name) @@ -94,7 +94,7 @@ class GTestXMLTestCase(gtest_test_utils.TestCase): self.assertEquals( len(expected_children), len(actual_children), 'number of child elements differ in element ' + actual_node.tagName) - for child_id, child in expected_children.items(): + for child_id, child in list(expected_children.items()): self.assert_(child_id in actual_children, '<%s> is not in <%s> (in element %s)' % (child_id, actual_children, actual_node.tagName)) diff --git a/taskcluster/taskgraph/create.py b/taskcluster/taskgraph/create.py index f577f88731..e41d89fbdf 100644 --- a/taskcluster/taskgraph/create.py +++ b/taskcluster/taskgraph/create.py @@ -24,7 +24,7 @@ CONCURRENCY = 50 def create_tasks(taskgraph, label_to_taskid, params): - taskid_to_label = {t: l for l, t in label_to_taskid.iteritems()} + taskid_to_label = {t: l for l, t in label_to_taskid.items()} session = requests.Session() @@ -85,7 +85,7 @@ def create_tasks(taskgraph, label_to_taskid, params): taskid_to_label[task_id], task_def) # Wait for all futures to complete. - for f in futures.as_completed(fs.values()): + for f in futures.as_completed(list(fs.values())): f.result() @@ -113,10 +113,10 @@ def resolve_timestamps(now, task_def): if isinstance(val, list): return [recurse(v) for v in val] elif isinstance(val, dict): - if val.keys() == ['relative-datestamp']: + if list(val.keys()) == ['relative-datestamp']: return json_time_from_now(val['relative-datestamp'], now) else: - return {k: recurse(v) for k, v in val.iteritems()} + return {k: recurse(v) for k, v in val.items()} else: return val return recurse(task_def) diff --git a/taskcluster/taskgraph/decision.py b/taskcluster/taskgraph/decision.py index d6460390fb..caba3442c7 100644 --- a/taskcluster/taskgraph/decision.py +++ b/taskcluster/taskgraph/decision.py @@ -95,7 +95,7 @@ def taskgraph_decision(options): _, _ = TaskGraph.from_json(full_task_json) # write out the target task set to allow reproducing this as input - write_artifact('target-tasks.json', tgg.target_task_set.tasks.keys()) + write_artifact('target-tasks.json', list(tgg.target_task_set.tasks.keys())) # write out the optimized task graph to describe what will actually happen, # and the map of labels to taskids diff --git a/taskcluster/taskgraph/docker.py b/taskcluster/taskgraph/docker.py index 8159fd5a4a..5a435e6897 100644 --- a/taskcluster/taskgraph/docker.py +++ b/taskcluster/taskgraph/docker.py @@ -51,8 +51,8 @@ def load_image_by_task_id(task_id): print("Determining image name") tf = tarfile.open(filename) repositories = json.load(tf.extractfile('repositories')) - name = repositories.keys()[0] - tag = repositories[name].keys()[0] + name = list(repositories.keys())[0] + tag = list(repositories[name].keys())[0] name = '{}:{}'.format(name, tag) print("Image name:", name) diff --git a/taskcluster/taskgraph/generator.py b/taskcluster/taskgraph/generator.py index 809ed1f5c0..20ee6e707f 100644 --- a/taskcluster/taskgraph/generator.py +++ b/taskcluster/taskgraph/generator.py @@ -155,7 +155,7 @@ class TaskGraphGenerator(object): # in post-order kinds = {kind.name: kind for kind in self._load_kinds()} edges = set() - for kind in kinds.itervalues(): + for kind in kinds.values(): for dep in kind.config.get('kind-dependencies', []): edges.add((kind.name, dep, 'kind-dependency')) kind_graph = Graph(set(kinds), edges) diff --git a/taskcluster/taskgraph/optimize.py b/taskcluster/taskgraph/optimize.py index 120e6807ba..b420de98b0 100644 --- a/taskcluster/taskgraph/optimize.py +++ b/taskcluster/taskgraph/optimize.py @@ -51,10 +51,10 @@ def resolve_task_references(label, task_def, taskid_for_edge_name): if isinstance(val, list): return [recurse(v) for v in val] elif isinstance(val, dict): - if val.keys() == ['task-reference']: + if list(val.keys()) == ['task-reference']: return TASK_REFERENCE_PATTERN.sub(repl, val['task-reference']) else: - return {k: recurse(v) for k, v in val.iteritems()} + return {k: recurse(v) for k, v in val.items()} else: return val return recurse(task_def) @@ -78,7 +78,7 @@ def annotate_task_graph(target_task_graph, params, do_not_optimize, named_task_dependencies = named_links_dict.get(label, {}) # check whether any dependencies have been optimized away - dependencies = [target_task_graph.tasks[l] for l in named_task_dependencies.itervalues()] + dependencies = [target_task_graph.tasks[l] for l in named_task_dependencies.values()] for t in dependencies: if t.optimized and not t.task_id: raise Exception( @@ -134,9 +134,9 @@ def get_subgraph(annotated_task_graph, named_links_dict, label_to_taskid): task.task_id = label_to_taskid[label] = slugid() named_task_dependencies = { name: label_to_taskid[label] - for name, label in named_links_dict.get(label, {}).iteritems()} + for name, label in named_links_dict.get(label, {}).items()} task.task = resolve_task_references(task.label, task.task, named_task_dependencies) - task.task.setdefault('dependencies', []).extend(named_task_dependencies.itervalues()) + task.task.setdefault('dependencies', []).extend(iter(named_task_dependencies.values())) tasks_by_taskid[task.task_id] = task # resolve edges to taskIds diff --git a/taskcluster/taskgraph/target_tasks.py b/taskcluster/taskgraph/target_tasks.py index bada65ed49..08a3f9c4ce 100644 --- a/taskcluster/taskgraph/target_tasks.py +++ b/taskcluster/taskgraph/target_tasks.py @@ -40,7 +40,7 @@ def target_tasks_try_option_syntax(full_task_graph, parameters): """Generate a list of target tasks based on try syntax in parameters['message'] and, for context, the full task graph.""" options = try_option_syntax.TryOptionSyntax(parameters['message'], full_task_graph) - target_tasks_labels = [t.label for t in full_task_graph.tasks.itervalues() + target_tasks_labels = [t.label for t in full_task_graph.tasks.values() if options.task_matches(t.attributes)] # If the developer wants test jobs to be rebuilt N times we add that value here @@ -80,7 +80,7 @@ def target_tasks_default(full_task_graph, parameters): if project in RELEASE_PROJECTS: return True return project in run_on_projects - return [l for l, t in full_task_graph.tasks.iteritems() if list(filter(t))] + return [l for l, t in full_task_graph.tasks.items() if list(filter(t))] @_target_task('ash_tasks') @@ -102,7 +102,7 @@ def target_tasks_ash(full_task_graph, parameters): if task.attributes['kind'] == 'upload-symbols': return False return True - return [l for l, t in full_task_graph.tasks.iteritems() if list(filter(t))] + return [l for l, t in full_task_graph.tasks.items() if list(filter(t))] @_target_task('cedar_tasks') @@ -118,4 +118,4 @@ def target_tasks_cedar(full_task_graph, parameters): or 'xpcshell' in task.attributes['unittest_suite']): return False return True - return [l for l, t in full_task_graph.tasks.iteritems() if list(filter(t))] + return [l for l, t in full_task_graph.tasks.items() if list(filter(t))] diff --git a/taskcluster/taskgraph/task/docker_image.py b/taskcluster/taskgraph/task/docker_image.py index fd67c48328..60ec810ce8 100644 --- a/taskcluster/taskgraph/task/docker_image.py +++ b/taskcluster/taskgraph/task/docker_image.py @@ -58,7 +58,7 @@ class DockerImageTask(base.Task): tasks = [] templates = Templates(path) - for image_name, image_symbol in config['images'].iteritems(): + for image_name, image_symbol in config['images'].items(): context_path = os.path.join('testing', 'docker', image_name) context_hash = generate_context_hash(GECKO, context_path, image_name) diff --git a/taskcluster/taskgraph/task/signing.py b/taskcluster/taskgraph/task/signing.py index a2a9ae3d66..6eff2ab751 100644 --- a/taskcluster/taskgraph/task/signing.py +++ b/taskcluster/taskgraph/task/signing.py @@ -33,7 +33,7 @@ class SigningTask(base.Task): templates = Templates(root) jobs = templates.load(filename, {}) - for name, job in jobs.iteritems(): + for name, job in jobs.items(): for artifact in job['unsigned-task']['artifacts']: url = ARTIFACT_URL.format('<{}>'.format('unsigned-artifact'), artifact) job['task']['payload']['unsignedArtifacts'].append({ diff --git a/taskcluster/taskgraph/task/test.py b/taskcluster/taskgraph/task/test.py index 928f32a5a5..1309edcfbd 100644 --- a/taskcluster/taskgraph/task/test.py +++ b/taskcluster/taskgraph/task/test.py @@ -41,7 +41,7 @@ class TestTask(transform.TransformTask): test_descriptions = load_yaml(path, 'tests.yml') # generate all tests for all test platforms - for test_platform_name, test_platform in test_platforms.iteritems(): + for test_platform_name, test_platform in test_platforms.items(): for test_name in test_platform['test-names']: test = copy.deepcopy(test_descriptions[test_name]) test['build-platform'] = test_platform['build-platform'] @@ -79,7 +79,7 @@ class TestTask(transform.TransformTask): based on the available build platforms. Returns a dictionary mapping test platform to {test-set, build-platform, build-label}.""" test_platforms = {} - for test_platform, cfg in test_platforms_cfg.iteritems(): + for test_platform, cfg in test_platforms_cfg.items(): build_platform = cfg['build-platform'] if build_platform not in builds_by_platform: logger.warning( @@ -100,7 +100,7 @@ class TestTask(transform.TransformTask): `test-names` key for each test platform, containing a set of test names.""" rv = {} - for test_platform, cfg in test_platforms.iteritems(): + for test_platform, cfg in test_platforms.items(): test_set = cfg['test-set'] if test_set not in test_sets_cfg: raise Exception( diff --git a/taskcluster/taskgraph/task/transform.py b/taskcluster/taskgraph/task/transform.py index 8183254a07..081a07ca4f 100644 --- a/taskcluster/taskgraph/task/transform.py +++ b/taskcluster/taskgraph/task/transform.py @@ -48,9 +48,9 @@ class TransformTask(base.Task): """ def jobs(): defaults = config.get('job-defaults') - jobs = config.get('jobs', {}).iteritems() + jobs = iter(config.get('jobs', {}).items()) jobs_from = itertools.chain.from_iterable( - load_yaml(path, filename).iteritems() + iter(load_yaml(path, filename).items()) for filename in config.get('jobs-from', {})) for name, job in itertools.chain(jobs, jobs_from): if defaults: @@ -83,7 +83,7 @@ class TransformTask(base.Task): task['attributes'], task['task']) def get_dependencies(self, taskgraph): - return [(label, name) for name, label in self.dependencies.items()] + return [(label, name) for name, label in list(self.dependencies.items())] def optimize(self, params): if 'files-changed' in self.when: diff --git a/taskcluster/taskgraph/taskgraph.py b/taskcluster/taskgraph/taskgraph.py index 7736745ef5..358df10d7d 100644 --- a/taskcluster/taskgraph/taskgraph.py +++ b/taskcluster/taskgraph/taskgraph.py @@ -52,7 +52,7 @@ class TaskGraph(object): def __iter__(self): "Iterate over tasks in undefined order" - return self.tasks.itervalues() + return iter(self.tasks.values()) def __repr__(self): return "".format(self.graph, self.tasks) @@ -68,7 +68,7 @@ class TaskGraph(object): """ tasks = {} edges = set() - for key, value in tasks_dict.iteritems(): + for key, value in tasks_dict.items(): # We get the implementation from JSON implementation = value['kind_implementation'] # Loading the module and creating a Task from a dictionary @@ -76,7 +76,7 @@ class TaskGraph(object): tasks[key] = task_kind.from_json(value) if 'task_id' in value: tasks[key].task_id = value['task_id'] - for depname, dep in value['dependencies'].iteritems(): + for depname, dep in value['dependencies'].items(): edges.add((key, dep, depname)) task_graph = cls(tasks, Graph(set(tasks), edges)) return tasks, task_graph diff --git a/taskcluster/taskgraph/test/test_create.py b/taskcluster/taskgraph/test/test_create.py index b8da3aec0c..56ffee86f8 100644 --- a/taskcluster/taskgraph/test/test_create.py +++ b/taskcluster/taskgraph/test/test_create.py @@ -46,7 +46,7 @@ class TestCreate(unittest.TestCase): create.create_tasks(taskgraph, label_to_taskid, {'level': '4'}) - for tid, task in self.created_tasks.iteritems(): + for tid, task in self.created_tasks.items(): self.assertEqual(task['payload'], 'hello world') self.assertEqual(task['schedulerId'], 'gecko-level-4') # make sure the dependencies exist, at least @@ -68,7 +68,7 @@ class TestCreate(unittest.TestCase): create.create_tasks(taskgraph, label_to_taskid, {'level': '4'}) - for tid, task in self.created_tasks.iteritems(): + for tid, task in self.created_tasks.items(): self.assertEqual(task.get('dependencies'), [os.environ['TASK_ID']]) diff --git a/taskcluster/taskgraph/test/test_generator.py b/taskcluster/taskgraph/test/test_generator.py index f1b466e4dd..4c1fea0ef1 100644 --- a/taskcluster/taskgraph/test/test_generator.py +++ b/taskcluster/taskgraph/test/test_generator.py @@ -102,7 +102,7 @@ class TestGenerator(unittest.TestCase): self.tgg = self.maketgg(['fake-t-1']) self.assertEqual(self.tgg.target_task_set.graph, graph.Graph({'fake-t-1'}, set())) - self.assertEqual(self.tgg.target_task_set.tasks.keys(), + self.assertEqual(list(self.tgg.target_task_set.tasks.keys()), ['fake-t-1']) def test_target_task_graph(self): diff --git a/taskcluster/taskgraph/test/test_optimize.py b/taskcluster/taskgraph/test/test_optimize.py index 8d2ddf2478..702469b9df 100644 --- a/taskcluster/taskgraph/test/test_optimize.py +++ b/taskcluster/taskgraph/test/test_optimize.py @@ -79,7 +79,7 @@ class TestOptimize(unittest.TestCase): def repl(task_id): return 'SLUGID' if task_id and len(task_id) == 22 else task_id got_annotations = { - t.label: (t.optimized, repl(t.task_id)) for t in graph.tasks.itervalues() + t.label: (t.optimized, repl(t.task_id)) for t in graph.tasks.values() } self.assertEqual(got_annotations, annotations) diff --git a/taskcluster/taskgraph/test/test_try_option_syntax.py b/taskcluster/taskgraph/test/test_try_option_syntax.py index 29aa2d5a90..aea68e2e95 100644 --- a/taskcluster/taskgraph/test/test_try_option_syntax.py +++ b/taskcluster/taskgraph/test/test_try_option_syntax.py @@ -40,9 +40,9 @@ tasks = {k: v for k, v in [ unittest_task('gtest', 'linux64'), talos_task('dromaeojs', 'linux64'), ]} -unittest_tasks = {k: v for k, v in tasks.iteritems() +unittest_tasks = {k: v for k, v in tasks.items() if 'unittest_try_name' in v.attributes} -talos_tasks = {k: v for k, v in tasks.iteritems() +talos_tasks = {k: v for k, v in tasks.items() if 'talos_try_name' in v.attributes} graph_with_jobs = TaskGraph(tasks, Graph(set(tasks), set())) @@ -139,7 +139,7 @@ class TestTryOptionSyntax(unittest.TestCase): tos = TryOptionSyntax('try: -p linux,linux64', empty_graph) ridealongs = list(task for task in itertools.chain.from_iterable( - RIDEALONG_BUILDS.itervalues() + iter(RIDEALONG_BUILDS.values()) ) if 'android' not in task) # Don't include android-l10n self.assertEqual(sorted(tos.platforms), sorted(['linux', 'linux64'] + ridealongs)) diff --git a/taskcluster/taskgraph/transforms/base.py b/taskcluster/taskgraph/transforms/base.py index aab1392521..63e07396fd 100644 --- a/taskcluster/taskgraph/transforms/base.py +++ b/taskcluster/taskgraph/transforms/base.py @@ -102,13 +102,13 @@ def get_keyed_by(item, field, item_name, subfield=None): return value assert len(value) == 1, "Invalid attribute {} in {}".format(field, item_name) - keyed_by = value.keys()[0] + keyed_by = list(value.keys())[0] values = value[keyed_by] if keyed_by.startswith('by-'): keyed_by = keyed_by[3:] # extract just the keyed-by field name if item[keyed_by] in values: return values[item[keyed_by]] - for k in values.keys(): + for k in list(values.keys()): if re.match(k, item[keyed_by]): return values[k] if 'default' in values: diff --git a/taskcluster/taskgraph/transforms/job/__init__.py b/taskcluster/taskgraph/transforms/job/__init__.py index a0860c0324..3d4c55e333 100644 --- a/taskcluster/taskgraph/transforms/job/__init__.py +++ b/taskcluster/taskgraph/transforms/job/__init__.py @@ -28,7 +28,7 @@ logger = logging.getLogger(__name__) # Voluptuous uses marker objects as dictionary *keys*, but they are not # comparable, so we cast all of the keys back to regular strings -task_description_schema = {str(k): v for k, v in task_description_schema.schema.iteritems()} +task_description_schema = {str(k): v for k, v in task_description_schema.schema.items()} # Schema for a build description job_description_schema = Schema({ diff --git a/taskcluster/taskgraph/try_option_syntax.py b/taskcluster/taskgraph/try_option_syntax.py index bf285365c6..609a7c0d23 100644 --- a/taskcluster/taskgraph/try_option_syntax.py +++ b/taskcluster/taskgraph/try_option_syntax.py @@ -294,7 +294,7 @@ class TryOptionSyntax(object): return [] all_platforms = set(t.attributes['test_platform'] - for t in full_task_graph.tasks.itervalues() + for t in full_task_graph.tasks.values() if 'test_platform' in t.attributes) tests = self.parse_test_opts(test_arg, all_platforms) @@ -303,7 +303,7 @@ class TryOptionSyntax(object): return [] all_tests = set(t.attributes[attr_name] - for t in full_task_graph.tasks.itervalues() + for t in full_task_graph.tasks.values() if attr_name in t.attributes) # Special case where tests is 'all' and must be expanded @@ -455,12 +455,12 @@ class TryOptionSyntax(object): results.extend(self.handle_alias(test, all_tests)) # uniquify the results over the test names - results = {test['test']: test for test in results}.values() + results = list({test['test']: test for test in results}.values()) return results def find_all_attribute_suffixes(self, graph, prefix): rv = set() - for t in graph.tasks.itervalues(): + for t in graph.tasks.values(): for a in t.attributes: if a.startswith(prefix): rv.add(a[len(prefix):]) diff --git a/taskcluster/taskgraph/util/attributes.py b/taskcluster/taskgraph/util/attributes.py index b44a3364f1..8a37392d63 100644 --- a/taskcluster/taskgraph/util/attributes.py +++ b/taskcluster/taskgraph/util/attributes.py @@ -11,7 +11,7 @@ def attrmatch(attributes, **kwargs): must be in the set. A callable is called with the attribute value. If an attribute is specified as a keyword argument but not present in the attributes, the result is False.""" - for kwkey, kwval in kwargs.iteritems(): + for kwkey, kwval in kwargs.items(): if kwkey not in attributes: return False attval = attributes[kwkey] diff --git a/taskcluster/taskgraph/util/seta.py b/taskcluster/taskgraph/util/seta.py index a0cd30675a..f18083790d 100644 --- a/taskcluster/taskgraph/util/seta.py +++ b/taskcluster/taskgraph/util/seta.py @@ -43,7 +43,7 @@ class SETA(object): kwargs={'timeout': 5, 'headers': headers}) task_list = json.loads(response.content).get('jobtypes', '') if len(task_list) > 0: - low_value_tasks = task_list.values()[0] + low_value_tasks = list(task_list.values())[0] # Bug 1315145, disable SETA for tier-1 platforms until backfill is implemented. low_value_tasks = [x for x in low_value_tasks if x.find('debug') == -1] diff --git a/taskcluster/taskgraph/util/templates.py b/taskcluster/taskgraph/util/templates.py index 97620fa75b..4d740cb558 100644 --- a/taskcluster/taskgraph/util/templates.py +++ b/taskcluster/taskgraph/util/templates.py @@ -25,7 +25,7 @@ def merge_to(source, dest): :param dict dest: to copy to (modified in place) ''' - for key, value in source.items(): + for key, value in list(source.items()): # Override mismatching or empty types if type(value) != type(dest.get(key)): # noqa dest[key] = source[key] diff --git a/testing/docker/recipes/tooltool.py b/testing/docker/recipes/tooltool.py index 3e932d82a4..7175ca47a9 100755 --- a/testing/docker/recipes/tooltool.py +++ b/testing/docker/recipes/tooltool.py @@ -855,7 +855,7 @@ def upload(manifest, message, base_urls, auth_file, region): # Upload the files, each in a thread. This allows us to start all of the # uploads before any of the URLs expire. threads = {} - for filename, file in files.iteritems(): + for filename, file in files.items(): if 'put_url' in file: log.info("%s: starting upload" % (filename,)) thd = threading.Thread(target=_s3_upload, @@ -869,7 +869,7 @@ def upload(manifest, message, base_urls, auth_file, region): # re-join all of those threads as they exit success = True while threads: - for filename, thread in threads.items(): + for filename, thread in list(threads.items()): if not thread.is_alive(): # _s3_upload has annotated file with result information file = files[filename] @@ -885,7 +885,7 @@ def upload(manifest, message, base_urls, auth_file, region): # notify the server that the uploads are completed. If the notification # fails, we don't consider that an error (the server will notice # eventually) - for filename, file in files.iteritems(): + for filename, file in files.items(): if 'put_url' in file and file['upload_ok']: log.info("notifying server of upload completion for %s" % (filename,)) _notify_upload_complete(base_urls[0], auth_file, file) diff --git a/testing/docker/rust-build/tcbuild.py b/testing/docker/rust-build/tcbuild.py index d55c6f3a75..fe99fc1a4f 100644 --- a/testing/docker/rust-build/tcbuild.py +++ b/testing/docker/rust-build/tcbuild.py @@ -34,7 +34,7 @@ def read_tc_auth(tc_auth_file): return json.load(open(tc_auth_file, 'rb')) def fill_template_dict(d, keys): - for key, val in d.items(): + for key, val in list(d.items()): if isinstance(val, basestring) and '{' in val: d[key] = val.format(**keys) elif isinstance(val, dict): diff --git a/testing/mach_commands.py b/testing/mach_commands.py index a744b0c44f..92de61689d 100644 --- a/testing/mach_commands.py +++ b/testing/mach_commands.py @@ -217,7 +217,7 @@ class Test(MachCommandBase): run_suites.add(entry) continue suitefound = False - for suite, v in TEST_SUITES.items(): + for suite, v in list(TEST_SUITES.items()): if entry in v.get('aliases', []): run_suites.add(suite) suitefound = True @@ -252,7 +252,7 @@ class Test(MachCommandBase): files_info = reader.files_info(changed_files) paths, tags, flavors = set(), set(), set() - for info in files_info.values(): + for info in list(files_info.values()): paths |= info.test_files tags |= info.test_tags flavors |= info.test_flavors @@ -482,13 +482,13 @@ class PushToTry(MachCommandBase): rv = defaultdict(list) for item in items: parsed = parse_arg(item) - for key, values in parsed.iteritems(): + for key, values in parsed.items(): rv[key].extend(values) if not allow_subitems: - if not all(item == [] for item in rv.itervalues()): + if not all(item == [] for item in rv.values()): raise ValueError("Unexpected subitems in argument") - return rv.keys() + return list(rv.keys()) else: return rv @@ -544,8 +544,8 @@ class PushToTry(MachCommandBase): print("Error parsing --tags argument:\n%s" % e.message) sys.exit(1) - extra_values = {k['dest'] for k in AutoTry.pass_through_arguments.values()} - extra_args = {k: v for k, v in kwargs.items() + extra_values = {k['dest'] for k in list(AutoTry.pass_through_arguments.values())} + extra_args = {k: v for k, v in list(kwargs.items()) if k in extra_values and v} return kwargs["builds"], platforms, tests, talos, paths, tags, extra_args @@ -616,7 +616,7 @@ class PushToTry(MachCommandBase): print("No saved configuration called %s found in autotry.ini" % kwargs["load"], file=sys.stderr) - for key, value in kwargs.iteritems(): + for key, value in kwargs.items(): if value in (None, []) and key in defaults: kwargs[key] = defaults[key] @@ -653,7 +653,7 @@ class PushToTry(MachCommandBase): if kwargs["verbose"] and paths_by_flavor: print('The following tests will be selected: ') - for flavor, paths in paths_by_flavor.iteritems(): + for flavor, paths in paths_by_flavor.items(): print("%s: %s" % (flavor, ",".join(paths))) if kwargs["verbose"] or not kwargs["push"]: diff --git a/testing/mochitest/bisection.py b/testing/mochitest/bisection.py index 66203e56a9..76807d631a 100644 --- a/testing/mochitest/bisection.py +++ b/testing/mochitest/bisection.py @@ -162,7 +162,7 @@ class Bisect(object): # passed. if len(self.expectedError) == 0: return -1 - options.bisectChunk = self.expectedError.keys()[0] + options.bisectChunk = list(self.expectedError.keys())[0] self.summary.append( "\tFound Error in test: %s" % options.bisectChunk) diff --git a/testing/mochitest/mach_commands.py b/testing/mochitest/mach_commands.py index b2f7bc1a38..0e78b0ffa6 100644 --- a/testing/mochitest/mach_commands.py +++ b/testing/mochitest/mach_commands.py @@ -120,8 +120,8 @@ ALL_FLAVORS = { } SUPPORTED_APPS = ['firefox', 'android'] -SUPPORTED_FLAVORS = list(chain.from_iterable([f['aliases'] for f in ALL_FLAVORS.values()])) -CANONICAL_FLAVORS = sorted([f['aliases'][0] for f in ALL_FLAVORS.values()]) +SUPPORTED_FLAVORS = list(chain.from_iterable([f['aliases'] for f in list(ALL_FLAVORS.values())])) +CANONICAL_FLAVORS = sorted([f['aliases'][0] for f in list(ALL_FLAVORS.values())]) parser = None @@ -305,14 +305,14 @@ class MachCommands(MachCommandBase): flavors = None if flavor: - for fname, fobj in ALL_FLAVORS.iteritems(): + for fname, fobj in ALL_FLAVORS.items(): if flavor in fobj['aliases']: if buildapp not in fobj['enabled_apps']: continue flavors = [fname] break else: - flavors = [f for f, v in ALL_FLAVORS.iteritems() if buildapp in v['enabled_apps']] + flavors = [f for f, v in ALL_FLAVORS.items() if buildapp in v['enabled_apps']] from mozbuild.controller.building import BuildDriver self._ensure_state_subdir_exists('.') diff --git a/testing/mochitest/mochitest_options.py b/testing/mochitest/mochitest_options.py index 796a29b0dc..aa8514760c 100644 --- a/testing/mochitest/mochitest_options.py +++ b/testing/mochitest/mochitest_options.py @@ -982,7 +982,7 @@ class MochitestArgumentParser(ArgumentParser): if self.app not in container_map: self.error("Unrecognized app '{}'! Must be one of: {}".format( - self.app, ', '.join(container_map.keys()))) + self.app, ', '.join(list(container_map.keys())))) defaults = {} for container in self.containers: diff --git a/testing/mochitest/pywebsocket/mod_pywebsocket/mux.py b/testing/mochitest/pywebsocket/mod_pywebsocket/mux.py index 76334685b3..02528b645c 100644 --- a/testing/mochitest/pywebsocket/mod_pywebsocket/mux.py +++ b/testing/mochitest/pywebsocket/mod_pywebsocket/mux.py @@ -1389,7 +1389,7 @@ class _HandshakeDeltaBase(object): headers = copy.copy(self._headers) if delta: - for key, value in delta.items(): + for key, value in list(delta.items()): # The spec requires that a header with an empty value is # removed from the delta base. if len(value) == 0 and headers.has_key(key): @@ -1807,7 +1807,7 @@ class _MuxHandler(object): 'Termiating all logical connections waiting for incoming data ' '...') self._logical_channels_condition.acquire() - for channel_data in self._logical_channels.values(): + for channel_data in list(self._logical_channels.values()): try: channel_data.request.connection.set_read_state( _LogicalConnection.STATE_TERMINATED) @@ -1824,7 +1824,7 @@ class _MuxHandler(object): 'Termiating all logical connections waiting for write ' 'completion ...') self._logical_channels_condition.acquire() - for channel_data in self._logical_channels.values(): + for channel_data in list(self._logical_channels.values()): try: channel_data.request.connection.on_writer_done() except Exception: diff --git a/testing/mochitest/runtests.py b/testing/mochitest/runtests.py index 64e55ce856..6e4da8d865 100644 --- a/testing/mochitest/runtests.py +++ b/testing/mochitest/runtests.py @@ -1447,7 +1447,7 @@ toolbar#nav-bar { options.hideResultsTable = True # strip certain unnecessary items to avoid serialization errors in json.dumps() - d = dict((k, v) for k, v in options.__dict__.items() if (v is None) or + d = dict((k, v) for k, v in list(options.__dict__.items()) if (v is None) or isinstance(v, (basestring, numbers.Number))) d['testRoot'] = self.testRoot if options.jscov_dir_prefix: @@ -2687,7 +2687,7 @@ def run_test_harness(parser, options): parser.validate(options) logger_options = { - key: value for key, value in vars(options).iteritems() + key: value for key, value in vars(options).items() if key.startswith('log') or key == 'valgrind'} runner = MochitestDesktop(logger_options, quiet=options.quiet) diff --git a/testing/mozbase/docs/_static/structured_example.py b/testing/mozbase/docs/_static/structured_example.py index 2bbc038103..18d66c08a4 100644 --- a/testing/mozbase/docs/_static/structured_example.py +++ b/testing/mozbase/docs/_static/structured_example.py @@ -48,7 +48,7 @@ class TestRunner(object): self.logger = get_default_logger(component='TestRunner') def gather_tests(self): - for item in globals().itervalues(): + for item in globals().values(): if isinstance(item, types.FunctionType) and item.__name__.startswith("test_"): yield item.__name__, item diff --git a/testing/mozbase/manifestparser/manifestparser/filters.py b/testing/mozbase/manifestparser/manifestparser/filters.py index e832c0da65..4506813bac 100644 --- a/testing/mozbase/manifestparser/manifestparser/filters.py +++ b/testing/mozbase/manifestparser/manifestparser/filters.py @@ -92,7 +92,7 @@ class InstanceFilter(object): def __init__(self, *args, **kwargs): self.fmt_args = ', '.join(itertools.chain( [str(a) for a in args], - ['{}={}'.format(k, v) for k, v in kwargs.iteritems()])) + ['{}={}'.format(k, v) for k, v in kwargs.items()])) def __eq__(self, other): if self.unique: @@ -249,7 +249,7 @@ class chunk_by_dir(InstanceFilter): # be yielded for reporting purposes. Put them all in chunk 1 for # simplicity. if self.this_chunk == 1: - disabled_dirs = [v for k, v in tests_by_dir.iteritems() + disabled_dirs = [v for k, v in tests_by_dir.items() if k not in ordered_dirs] for disabled_test in itertools.chain(*disabled_dirs): yield disabled_test diff --git a/testing/mozbase/manifestparser/manifestparser/ini.py b/testing/mozbase/manifestparser/manifestparser/ini.py index 5117dd1ae8..20fa31bb8c 100644 --- a/testing/mozbase/manifestparser/manifestparser/ini.py +++ b/testing/mozbase/manifestparser/manifestparser/ini.py @@ -131,7 +131,7 @@ def combine_fields(global_vars, local_vars): 'support-files': '%s %s', } final_mapping = global_vars.copy() - for field_name, value in local_vars.items(): + for field_name, value in list(local_vars.items()): if field_name not in field_patterns or field_name not in global_vars: final_mapping[field_name] = value continue diff --git a/testing/mozbase/manifestparser/manifestparser/manifestparser.py b/testing/mozbase/manifestparser/manifestparser/manifestparser.py index 557cf95e07..9b2c42c7aa 100644 --- a/testing/mozbase/manifestparser/manifestparser/manifestparser.py +++ b/testing/mozbase/manifestparser/manifestparser/manifestparser.py @@ -178,7 +178,7 @@ class ManifestParser(object): # otherwise an item # apply ancestor defaults, while maintaining current file priority - data = dict(self._ancestor_defaults.items() + data.items()) + data = dict(list(self._ancestor_defaults.items()) + list(data.items())) test = data test['name'] = section @@ -306,19 +306,19 @@ class ManifestParser(object): # make some check functions if inverse: def has_tags(test): - return not tags.intersection(test.keys()) + return not tags.intersection(list(test.keys())) def dict_query(test): - for key, value in kwargs.items(): + for key, value in list(kwargs.items()): if test.get(key) == value: return False return True else: def has_tags(test): - return tags.issubset(test.keys()) + return tags.issubset(list(test.keys())) def dict_query(test): - for key, value in kwargs.items(): + for key, value in list(kwargs.items()): if test.get(key) != value: return False return True @@ -340,7 +340,7 @@ class ManifestParser(object): """ if tests is None: # Make sure to return all the manifests, even ones without tests. - return self.manifest_defaults.keys() + return list(self.manifest_defaults.keys()) manifests = [] for test in tests: @@ -452,7 +452,7 @@ class ManifestParser(object): print('[DEFAULT]', file=fp) for tag in global_tags: print('%s =' % tag, file=fp) - for key, value in global_kwargs.items(): + for key, value in list(global_kwargs.items()): print('%s = %s' % (key, value), file=fp) print(file=fp) diff --git a/testing/mozbase/manifestparser/tests/test_chunking.py b/testing/mozbase/manifestparser/tests/test_chunking.py index 4fe1415fa5..82651bb633 100644 --- a/testing/mozbase/manifestparser/tests/test_chunking.py +++ b/testing/mozbase/manifestparser/tests/test_chunking.py @@ -85,7 +85,7 @@ class ChunkByDir(TestCase): { : } """ i = 0 - for d, num in dirs.iteritems(): + for d, num in dirs.items(): for j in range(num): i += 1 name = 'test%i' % i @@ -176,7 +176,7 @@ class ChunkByRuntime(TestCase): { : } """ i = 0 - for d, num in dirs.iteritems(): + for d, num in dirs.items(): for j in range(num): i += 1 name = 'test%i' % i diff --git a/testing/mozbase/manifestparser/tests/test_default_overrides.py b/testing/mozbase/manifestparser/tests/test_default_overrides.py index 3341c4bd82..7f1af6437c 100755 --- a/testing/mozbase/manifestparser/tests/test_default_overrides.py +++ b/testing/mozbase/manifestparser/tests/test_default_overrides.py @@ -87,10 +87,10 @@ class TestOmitDefaults(unittest.TestCase): "skip-if": "os == 'win' && debug # a pesky comment", }, } - for path, defaults in expected_defaults.items(): + for path, defaults in list(expected_defaults.items()): self.assertIn(path, parser.manifest_defaults) actual_defaults = parser.manifest_defaults[path] - for key, value in defaults.items(): + for key, value in list(defaults.items()): self.assertIn(key, actual_defaults) self.assertEqual(value, actual_defaults[key]) diff --git a/testing/mozbase/mozdevice/mozdevice/Zeroconf.py b/testing/mozbase/mozdevice/mozdevice/Zeroconf.py index bfbe57285e..8011e6d03d 100755 --- a/testing/mozbase/mozdevice/mozdevice/Zeroconf.py +++ b/testing/mozbase/mozdevice/mozdevice/Zeroconf.py @@ -819,7 +819,7 @@ class DNSCache(object): """Returns a list of all entries""" def add(x, y): return x+y try: - return reduce(add, self.cache.values()) + return reduce(add, list(self.cache.values())) except: return [] @@ -870,7 +870,7 @@ class Engine(threading.Thread): def getReaders(self): result = [] self.condition.acquire() - result = self.readers.keys() + result = list(self.readers.keys()) self.condition.release() return result @@ -1010,7 +1010,7 @@ class ServiceBrowser(threading.Thread): if self.nextTime <= now: out = DNSOutgoing(_FLAGS_QR_QUERY) out.addQuestion(DNSQuestion(self.type, _TYPE_PTR, _CLASS_IN)) - for record in self.services.values(): + for record in list(self.services.values()): if not record.isExpired(now): out.addAnswerAtTime(record, now) self.zeroconf.send(out) @@ -1387,7 +1387,7 @@ class Zeroconf(object): now = currentTimeMillis() continue out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA) - for info in self.services.values(): + for info in list(self.services.values()): out.addAnswerAtTime(DNSPointer(info.type, _TYPE_PTR, _CLASS_IN, 0, info.name), 0) out.addAnswerAtTime(DNSService(info.name, _TYPE_SRV, _CLASS_IN, 0, info.priority, info.weight, info.port, info.server), 0) out.addAnswerAtTime(DNSText(info.name, _TYPE_TXT, _CLASS_IN, 0, info.text), 0) @@ -1483,7 +1483,7 @@ class Zeroconf(object): for question in msg.questions: if question.type == _TYPE_PTR: - for service in self.services.values(): + for service in list(self.services.values()): if question.name == service.type: if out is None: out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA) @@ -1495,7 +1495,7 @@ class Zeroconf(object): # Answer A record queries for any service addresses we know if question.type == _TYPE_A or question.type == _TYPE_ANY: - for service in self.services.values(): + for service in list(self.services.values()): if service.server == question.name.lower(): out.addAnswer(msg, DNSAddress(question.name, _TYPE_A, _CLASS_IN | _CLASS_UNIQUE, _DNS_TTL, service.address)) diff --git a/testing/mozbase/mozdevice/mozdevice/adb.py b/testing/mozbase/mozdevice/mozdevice/adb.py index 538d5b9279..834b6ce4f6 100644 --- a/testing/mozbase/mozdevice/mozdevice/adb.py +++ b/testing/mozbase/mozdevice/mozdevice/adb.py @@ -1037,7 +1037,7 @@ class ADBDevice(ADBCommand): cmd = "cd %s && %s" % (cwd, cmd) if env: envstr = '&& '.join(['export %s=%s' % - (x[0], x[1]) for x in env.iteritems()]) + (x[0], x[1]) for x in env.items()]) cmd = envstr + "&& " + cmd cmd += "; echo rc=$?" @@ -1651,7 +1651,7 @@ class ADBDevice(ADBCommand): else: entry = line entries[entry] = 1 - entry_list = entries.keys() + entry_list = list(entries.keys()) entry_list.sort() return entry_list diff --git a/testing/mozbase/mozdevice/mozdevice/adb_android.py b/testing/mozbase/mozdevice/mozdevice/adb_android.py index bf5fffc0e5..f827386a51 100644 --- a/testing/mozbase/mozdevice/mozdevice/adb_android.py +++ b/testing/mozbase/mozdevice/mozdevice/adb_android.py @@ -339,7 +339,7 @@ class ADBAndroid(ADBDevice): acmd.extend(["-a", intent]) if extras: - for (key, val) in extras.iteritems(): + for (key, val) in extras.items(): if isinstance(val, int): extra_type_param = "--ei" elif isinstance(val, bool): @@ -389,7 +389,7 @@ class ADBAndroid(ADBDevice): if moz_env: # moz_env is expected to be a dictionary of environment variables: # Fennec itself will set them when launched - for (env_count, (env_key, env_val)) in enumerate(moz_env.iteritems()): + for (env_count, (env_key, env_val)) in enumerate(moz_env.items()): extras["env" + str(env_count)] = env_key + "=" + env_val # Additional command line arguments that fennec will read and use (e.g. diff --git a/testing/mozbase/mozdevice/mozdevice/devicemanagerADB.py b/testing/mozbase/mozdevice/mozdevice/devicemanagerADB.py index 0c91f0f828..a92a8a147c 100644 --- a/testing/mozbase/mozdevice/mozdevice/devicemanagerADB.py +++ b/testing/mozbase/mozdevice/mozdevice/devicemanagerADB.py @@ -140,7 +140,7 @@ class DeviceManagerADB(DeviceManager): if cwd: cmdline = "cd %s; %s" % (cwd, cmdline) if env: - envstr = '; '.join(['export %s=%s' % (x[0], x[1]) for x in env.iteritems()]) + envstr = '; '.join(['export %s=%s' % (x[0], x[1]) for x in env.items()]) cmdline = envstr + "; " + cmdline # all output should be in stdout @@ -444,7 +444,7 @@ class DeviceManagerADB(DeviceManager): if env != '' and env is not None: envCnt = 0 # env is expected to be a dict of environment variables - for envkey, envval in env.iteritems(): + for envkey, envval in env.items(): acmd.append("--es") acmd.append("env" + str(envCnt)) acmd.append(envkey + "=" + envval) diff --git a/testing/mozbase/mozdevice/mozdevice/devicemanagerSUT.py b/testing/mozbase/mozdevice/mozdevice/devicemanagerSUT.py index 9187f5d770..c0b1aa492b 100644 --- a/testing/mozbase/mozdevice/mozdevice/devicemanagerSUT.py +++ b/testing/mozbase/mozdevice/mozdevice/devicemanagerSUT.py @@ -832,7 +832,7 @@ class DeviceManagerSUT(DeviceManager): result[d] = data.split('\n') # Get rid of any 0 length members of the arrays - for k, v in result.iteritems(): + for k, v in result.items(): result[k] = [x for x in result[k] if x != ''] # Format the process output @@ -920,7 +920,7 @@ class DeviceManagerSUT(DeviceManager): if (env is None or env == ''): return '' - retVal = '"%s"' % ','.join(['%s=%s' % (x[0], x[1]) for x in env.iteritems()]) + retVal = '"%s"' % ','.join(['%s=%s' % (x[0], x[1]) for x in env.items()]) if (retVal == '""'): return '' diff --git a/testing/mozbase/mozdevice/mozdevice/dmcli.py b/testing/mozbase/mozdevice/mozdevice/dmcli.py index 45149f9455..ad663c3943 100644 --- a/testing/mozbase/mozdevice/mozdevice/dmcli.py +++ b/testing/mozbase/mozdevice/mozdevice/dmcli.py @@ -190,7 +190,7 @@ class DMCli(object): def add_commands(self, parser): subparsers = parser.add_subparsers(title="Commands", metavar="") - for (commandname, commandprops) in sorted(self.commands.iteritems()): + for (commandname, commandprops) in sorted(self.commands.items()): subparser = subparsers.add_parser(commandname, help=commandprops['help']) if commandprops.get('args'): for arg in commandprops['args']: @@ -199,7 +199,7 @@ class DMCli(object): # this package) # kwargs = { k: v for k,v in arg.items() if k is not 'name' } kwargs = {} - for (k, v) in arg.items(): + for (k, v) in list(arg.items()): if k is not 'name': kwargs[k] = v subparser.add_argument(arg['name'], **kwargs) @@ -292,7 +292,7 @@ class DMCli(object): def getinfo(self, args): info = self.dm.getInfo(directive=args.directive) - for (infokey, infoitem) in sorted(info.iteritems()): + for (infokey, infoitem) in sorted(info.items()): if infokey == "process": pass # skip process list: get that through ps elif args.directive is None: diff --git a/testing/mozbase/mozdevice/mozdevice/droid.py b/testing/mozbase/mozdevice/mozdevice/droid.py index 1da36143a4..081d2d4325 100644 --- a/testing/mozbase/mozdevice/mozdevice/droid.py +++ b/testing/mozbase/mozdevice/mozdevice/droid.py @@ -54,7 +54,7 @@ class DroidMixin(object): acmd.extend(["-a", intent]) if extras: - for (key, val) in extras.iteritems(): + for (key, val) in extras.items(): if type(val) is int: extraTypeParam = "--ei" elif type(val) is bool: @@ -96,7 +96,7 @@ class DroidMixin(object): if mozEnv: # mozEnv is expected to be a dictionary of environment variables: Fennec # itself will set them when launched - for (envCnt, (envkey, envval)) in enumerate(mozEnv.iteritems()): + for (envCnt, (envkey, envval)) in enumerate(mozEnv.items()): extras["env" + str(envCnt)] = envkey + "=" + envval # Additional command line arguments that fennec will read and use (e.g. diff --git a/testing/mozbase/mozdevice/mozdevice/sutini.py b/testing/mozbase/mozdevice/mozdevice/sutini.py index 71786f4ba2..9c763fc8e4 100644 --- a/testing/mozbase/mozdevice/mozdevice/sutini.py +++ b/testing/mozbase/mozdevice/mozdevice/sutini.py @@ -114,7 +114,7 @@ def main(): if not cfg.sections(): print('Empty or missing ini file.') changed_vals = False - for sect, opts in SCHEMA.iteritems(): + for sect, opts in SCHEMA.items(): changed_vals |= edit_sect(cfg, sect, opts) if changed_vals: put_cfg(d, cfg, ini_path) diff --git a/testing/mozbase/mozdevice/tests/sut_info.py b/testing/mozbase/mozdevice/tests/sut_info.py index 93f3d42581..471d156fc8 100644 --- a/testing/mozbase/mozdevice/tests/sut_info.py +++ b/testing/mozbase/mozdevice/tests/sut_info.py @@ -34,7 +34,7 @@ class TestGetInfo(unittest.TestCase): def test_getInfo(self): - for directive in self.commands.keys(): + for directive in list(self.commands.keys()): m = MockAgent(self, commands=[self.commands[directive]]) d = mozdevice.DroidSUT('127.0.0.1', port=m.port, logLevel=logging.DEBUG) diff --git a/testing/mozbase/mozhttpd/mozhttpd/mozhttpd.py b/testing/mozbase/mozhttpd/mozhttpd/mozhttpd.py index 80e44da347..a052b9283a 100755 --- a/testing/mozbase/mozhttpd/mozhttpd/mozhttpd.py +++ b/testing/mozbase/mozhttpd/mozhttpd/mozhttpd.py @@ -87,7 +87,7 @@ class RequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): (response_code, headerdict, data) = \ handler['function'](self.request, *m.groups()) self.send_response(response_code) - for (keyword, value) in headerdict.iteritems(): + for (keyword, value) in headerdict.items(): self.send_header(keyword, value) self.end_headers() self.wfile.write(data) @@ -101,7 +101,7 @@ class RequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): using self.path_mappings and self.docroot. Return (url_path, disk_path).""" path_components = [_f for _f in self.request.path.split('/') if _f] - for prefix, disk_path in self.path_mappings.iteritems(): + for prefix, disk_path in self.path_mappings.items(): prefix_components = [_f for _f in prefix.split('/') if _f] if len(path_components) < len(prefix_components): continue diff --git a/testing/mozbase/mozhttpd/tests/basic.py b/testing/mozbase/mozhttpd/tests/basic.py index 8d64b4332e..cec24fecca 100644 --- a/testing/mozbase/mozhttpd/tests/basic.py +++ b/testing/mozbase/mozhttpd/tests/basic.py @@ -18,7 +18,7 @@ class TestBasic(unittest.TestCase): # sizes is a dict of the form: name -> [size, binary_string, filepath] sizes = {'small': [128], 'large': [16384]} - for k in sizes.keys(): + for k in list(sizes.keys()): # Generate random binary string sizes[k].append(os.urandom(sizes[k][0])) @@ -35,7 +35,7 @@ class TestBasic(unittest.TestCase): server_url = server.get_url() # Retrieve file and check contents matchup - for k in sizes.keys(): + for k in list(sizes.keys()): retrieved_content = mozfile.load(server_url + k).read() self.assertEqual(retrieved_content, sizes[k][1]) diff --git a/testing/mozbase/mozinfo/mozinfo/mozinfo.py b/testing/mozbase/mozinfo/mozinfo/mozinfo.py index 5f0d3d182f..536c5cde9e 100755 --- a/testing/mozbase/mozinfo/mozinfo/mozinfo.py +++ b/testing/mozbase/mozinfo/mozinfo/mozinfo.py @@ -246,7 +246,7 @@ def output_to_file(path): update({}) # exports -__all__ = info.keys() +__all__ = list(info.keys()) __all__ += ['is' + os_name.title() for os_name in choices['os']] __all__ += [ 'info', @@ -284,7 +284,7 @@ def main(args=None): # print out choices if requested flag = False - for key, value in options.__dict__.items(): + for key, value in list(options.__dict__.items()): if value is True: print('%s choices: %s' % (key, ' '.join([str(choice) for choice in choices[key]]))) @@ -293,7 +293,7 @@ def main(args=None): return # otherwise, print out all info - for key, value in info.items(): + for key, value in list(info.items()): print('%s: %s' % (key, value)) if __name__ == '__main__': diff --git a/testing/mozbase/mozlog/mozlog/commandline.py b/testing/mozbase/mozlog/mozlog/commandline.py index 1077081548..a462cc119f 100644 --- a/testing/mozbase/mozlog/mozlog/commandline.py +++ b/testing/mozbase/mozlog/mozlog/commandline.py @@ -121,7 +121,7 @@ def add_logging_group(parser, include_formatters=None): "or '-' to write to stdout.") if include_formatters is None: - include_formatters = log_formatters.keys() + include_formatters = list(log_formatters.keys()) if isinstance(parser, optparse.OptionParser): group = optparse.OptionGroup(parser, @@ -136,12 +136,12 @@ def add_logging_group(parser, include_formatters=None): opt_log_type = log_file group_add = group.add_argument - for name, (cls, help_str) in log_formatters.iteritems(): + for name, (cls, help_str) in log_formatters.items(): if name in include_formatters: group_add("--log-" + name, action="append", type=opt_log_type, help=help_str) - for optname, (cls, help_str, formatters_, action) in fmt_options.iteritems(): + for optname, (cls, help_str, formatters_, action) in fmt_options.items(): for fmt in formatters_: # make sure fmt is in log_formatters and is accepted if fmt in log_formatters and fmt in include_formatters: @@ -165,12 +165,12 @@ def setup_handlers(logger, formatters, formatter_options, allow_unused_options=F list(unused_options)) raise ValueError(msg) - for fmt, streams in formatters.iteritems(): + for fmt, streams in formatters.items(): formatter_cls = log_formatters[fmt][0] formatter = formatter_cls() handler_wrappers_and_options = [] - for option, value in formatter_options[fmt].iteritems(): + for option, value in formatter_options[fmt].items(): wrapper, wrapper_args = None, () if option == "valgrind": wrapper = valgrind_handler_wrapper @@ -232,7 +232,7 @@ def setup_logging(logger, args, defaults=None, formatter_defaults=None, else: defaults = {"raw": sys.stdout} - for name, values in args.iteritems(): + for name, values in args.items(): parts = name.split('_') if len(parts) > 3: continue @@ -260,11 +260,11 @@ def setup_logging(logger, args, defaults=None, formatter_defaults=None, # If there is no user-specified logging, go with the default options if not found: - for name, value in defaults.iteritems(): + for name, value in defaults.items(): formatters[name].append(value) - elif not found_stdout_logger and sys.stdout in defaults.values(): - for name, value in defaults.iteritems(): + elif not found_stdout_logger and sys.stdout in list(defaults.values()): + for name, value in defaults.items(): if value == sys.stdout: formatters[name].append(value) diff --git a/testing/mozbase/mozlog/mozlog/formatters/html/html.py b/testing/mozbase/mozlog/mozlog/formatters/html/html.py index 0ec244aa6a..5d08c53535 100755 --- a/testing/mozbase/mozlog/mozlog/formatters/html/html.py +++ b/testing/mozbase/mozlog/mozlog/formatters/html/html.py @@ -148,7 +148,7 @@ class HTMLFormatter(base.BaseFormatter): html.a(html.img(src=screenshot), href="#"), class_='screenshot')) - for name, content in debug.items(): + for name, content in list(debug.items()): if name in ['screenshot', 'image1', 'image2']: if not content.startswith('data:image/png;base64,'): href = 'data:image/png;base64,%s' % content @@ -208,7 +208,7 @@ class HTMLFormatter(base.BaseFormatter): id='environment'), html.h2('Summary'), - html.p('%i tests ran in %.1f seconds.' % (sum(self.test_count.itervalues()), + html.p('%i tests ran in %.1f seconds.' % (sum(self.test_count.values()), (self.suite_times["end"] - self.suite_times["start"]) / 1000.), html.br(), diff --git a/testing/mozbase/mozlog/mozlog/formatters/html/xmlgen.py b/testing/mozbase/mozlog/mozlog/formatters/html/xmlgen.py index e5998cda33..eb3caca199 100644 --- a/testing/mozbase/mozlog/mozlog/formatters/html/xmlgen.py +++ b/testing/mozbase/mozlog/mozlog/formatters/html/xmlgen.py @@ -116,7 +116,7 @@ class html(Namespace): class Style(object): def __init__(self, **kw): - for x, y in kw.items(): + for x, y in list(kw.items()): x = x.replace('_', '-') setattr(self, x, y) @@ -227,7 +227,7 @@ class SimpleUnicodeVisitor(object): except AttributeError: return [] else: - stylelist = [x + ': ' + y for x, y in styledict.items()] + stylelist = [x + ': ' + y for x, y in list(styledict.items())] return [u(' style="%s"') % u('; ').join(stylelist)] def _issingleton(self, tagname): @@ -270,7 +270,7 @@ class _escape: u('"'): u('"'), u('<'): u('<'), u('>'): u('>'), u('&'): u('&'), u("'"): u('''), } - self.charef_rex = re.compile(u("|").join(self.escape.keys())) + self.charef_rex = re.compile(u("|").join(list(self.escape.keys()))) def _replacer(self, match): return self.escape[match.group(0)] diff --git a/testing/mozbase/mozlog/mozlog/logtypes.py b/testing/mozbase/mozlog/mozlog/logtypes.py index d5ebff93cc..6b750a5e5d 100644 --- a/testing/mozbase/mozlog/mozlog/logtypes.py +++ b/testing/mozbase/mozlog/mozlog/logtypes.py @@ -83,7 +83,7 @@ class log_action(object): if name not in values: values[name] = self.args[name].default - for key, value in values.iteritems(): + for key, value in values.items(): if key in self.args: out_value = self.args[key](value) if out_value is not missing: @@ -94,7 +94,7 @@ class log_action(object): return data def convert_known(self, **kwargs): - known_kwargs = {name: value for name, value in kwargs.iteritems() + known_kwargs = {name: value for name, value in kwargs.items() if name in self.args} return self.convert(**known_kwargs) diff --git a/testing/mozbase/mozlog/mozlog/pytest_mozlog/plugin.py b/testing/mozbase/mozlog/mozlog/pytest_mozlog/plugin.py index 811ee38e38..4d86868d8a 100644 --- a/testing/mozbase/mozlog/mozlog/pytest_mozlog/plugin.py +++ b/testing/mozbase/mozlog/mozlog/pytest_mozlog/plugin.py @@ -12,10 +12,10 @@ def pytest_addoption(parser): # Pytest's parser doesn't have the add_argument_group method Mozlog expects. group = parser.getgroup('mozlog') - for name, (_class, _help) in mozlog.commandline.log_formatters.iteritems(): + for name, (_class, _help) in mozlog.commandline.log_formatters.items(): group.addoption('--log-{0}'.format(name), action='append', help=_help) - formatter_options = mozlog.commandline.fmt_options.iteritems() + formatter_options = iter(mozlog.commandline.fmt_options.items()) for name, (_class, _help, formatters, action) in formatter_options: for formatter in formatters: if formatter in mozlog.commandline.log_formatters: diff --git a/testing/mozbase/mozlog/mozlog/scripts/__init__.py b/testing/mozbase/mozlog/mozlog/scripts/__init__.py index 53f9146c92..3a513ec75e 100644 --- a/testing/mozbase/mozlog/mozlog/scripts/__init__.py +++ b/testing/mozbase/mozlog/mozlog/scripts/__init__.py @@ -16,7 +16,7 @@ def get_parser(): sub_parser = parser.add_subparsers(title='Subcommands') - for command, (parser_func, main_func) in commands.iteritems(): + for command, (parser_func, main_func) in commands.items(): parent = parser_func(False) command_parser = sub_parser.add_parser(command, description=parent.description, diff --git a/testing/mozbase/mozlog/mozlog/scripts/format.py b/testing/mozbase/mozlog/mozlog/scripts/format.py index 1644e4b956..627ff104a4 100644 --- a/testing/mozbase/mozlog/mozlog/scripts/format.py +++ b/testing/mozbase/mozlog/mozlog/scripts/format.py @@ -12,7 +12,7 @@ def get_parser(add_help=True): help="Filename to read from, defaults to stdin") parser.add_argument("--output", action="store", default=None, help="Filename to write to, defaults to stdout") - parser.add_argument("format", choices=commandline.log_formatters.keys(), + parser.add_argument("format", choices=list(commandline.log_formatters.keys()), help="Format to use") return parser diff --git a/testing/mozbase/mozlog/mozlog/scripts/unstable.py b/testing/mozbase/mozlog/mozlog/scripts/unstable.py index 04c8640ab4..65259418f3 100644 --- a/testing/mozbase/mozlog/mozlog/scripts/unstable.py +++ b/testing/mozbase/mozlog/mozlog/scripts/unstable.py @@ -46,9 +46,9 @@ def _filter(results_cmp): def inner(statuses): rv = defaultdict(lambda: defaultdict(dict)) - for run_info, tests in statuses.iteritems(): - for test, subtests in tests.iteritems(): - for name, results in subtests.iteritems(): + for run_info, tests in statuses.items(): + for test, subtests in tests.items(): + for name, results in subtests.items(): if results_cmp(results): rv[run_info][test][name] = results @@ -62,16 +62,16 @@ filter_stable = _filter(lambda x: len(x) == 1) def group_results(data): rv = defaultdict(lambda: defaultdict(lambda: defaultdict(int))) - for run_info, tests in data.iteritems(): - for test, subtests in tests.iteritems(): - for name, results in subtests.iteritems(): - for status, number in results.iteritems(): + for run_info, tests in data.items(): + for test, subtests in tests.items(): + for name, results in subtests.items(): + for status, number in results.items(): rv[test][name][status] += number return rv def print_results(data): - for run_info, tests in data.iteritems(): + for run_info, tests in data.items(): run_str = " ".join("%s:%s" % (k, v) for k, v in run_info) if run_info else "No Run Info" print(run_str) print("=" * len(run_str)) @@ -82,9 +82,9 @@ def print_run(tests): for test, subtests in sorted(tests.items()): print("\n" + str(test)) print("-" * len(test)) - for name, results in subtests.iteritems(): + for name, results in subtests.items(): print("[%s]: %s" % (name if name is not None else "", - " ".join("%s (%i)" % (k, v) for k, v in results.iteritems()))) + " ".join("%s (%i)" % (k, v) for k, v in results.items()))) def get_parser(add_help=True): diff --git a/testing/mozbase/mozlog/mozlog/structuredlog.py b/testing/mozbase/mozlog/mozlog/structuredlog.py index d1d251d203..bd6a5ee8e8 100644 --- a/testing/mozbase/mozlog/mozlog/structuredlog.py +++ b/testing/mozbase/mozlog/mozlog/structuredlog.py @@ -185,7 +185,7 @@ class StructuredLogger(object): action = raw_data["action"] converted_data = convertor_registry[action].convert_known(**raw_data) - for k, v in raw_data.iteritems(): + for k, v in raw_data.items(): if k not in converted_data: converted_data[k] = v diff --git a/testing/mozbase/mozlog/tests/test_logger.py b/testing/mozbase/mozlog/tests/test_logger.py index 30f4eb5699..6a542c8e96 100644 --- a/testing/mozbase/mozlog/tests/test_logger.py +++ b/testing/mozbase/mozlog/tests/test_logger.py @@ -82,10 +82,10 @@ class TestStructuredLogging(unittest.TestCase): self.assertTrue(isinstance(actual['_time'], (int, long))) - for k, v in expected.items(): + for k, v in list(expected.items()): self.assertEqual(v, actual[k]) - for k in actual.keys(): + for k in list(actual.keys()): if k != '_time': self.assertTrue(expected.get(k) is not None) diff --git a/testing/mozbase/mozlog/tests/test_structured.py b/testing/mozbase/mozlog/tests/test_structured.py index ab4b5f5826..f82266892c 100644 --- a/testing/mozbase/mozlog/tests/test_structured.py +++ b/testing/mozbase/mozlog/tests/test_structured.py @@ -58,7 +58,7 @@ class BaseStructuredTest(unittest.TestCase): specials = set(["time"]) all_expected.update(expected) - for key, value in all_expected.iteritems(): + for key, value in all_expected.items(): self.assertEqual(actual[key], value) self.assertEquals(set(all_expected.keys()) | @@ -927,7 +927,7 @@ class TestBuffer(BaseStructuredTest): specials = set(["time"]) all_expected.update(expected) - for key, value in all_expected.iteritems(): + for key, value in all_expected.items(): self.assertEqual(actual[key], value) self.assertEquals(set(all_expected.keys()) | diff --git a/testing/mozbase/mozprocess/mozprocess/winprocess.py b/testing/mozbase/mozprocess/mozprocess/winprocess.py index 50de744463..4513cac4a5 100644 --- a/testing/mozbase/mozprocess/mozprocess/winprocess.py +++ b/testing/mozbase/mozprocess/mozprocess/winprocess.py @@ -151,7 +151,7 @@ class EnvironmentBlock: else: values = [] fs_encoding = sys.getfilesystemencoding() or 'mbcs' - for k, v in env.iteritems(): + for k, v in env.items(): if isinstance(k, bytes): k = k.decode(fs_encoding, 'replace') if isinstance(v, bytes): diff --git a/testing/mozbase/mozprocess/tests/proclaunch.py b/testing/mozbase/mozprocess/tests/proclaunch.py index e44c1cca55..d94347dbd4 100644 --- a/testing/mozbase/mozprocess/tests/proclaunch.py +++ b/testing/mozbase/mozprocess/tests/proclaunch.py @@ -154,7 +154,7 @@ class ProcessLauncher(object): :param proc_name: File name of the manifest as a string. :param level: Depth of the current process in the tree. """ - if proc_name not in self.children.keys(): + if proc_name not in list(self.children.keys()): raise IOError("%s is not a valid process" % proc_name) maxtime = self.children[proc_name].maxtime diff --git a/testing/mozbase/mozprofile/mozprofile/addons.py b/testing/mozbase/mozprofile/mozprofile/addons.py index e96fd6b36c..ad33156d7f 100644 --- a/testing/mozbase/mozprofile/mozprofile/addons.py +++ b/testing/mozbase/mozprofile/mozprofile/addons.py @@ -301,15 +301,15 @@ class AddonManager(object): rdf = get_namespace_id(doc, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#') description = doc.getElementsByTagName(rdf + 'Description').item(0) - for entry, value in description.attributes.items(): + for entry, value in list(description.attributes.items()): # Remove the namespace prefix from the tag for comparison entry = entry.replace(em, "") - if entry in details.keys(): + if entry in list(details.keys()): details.update({entry: value}) for node in description.childNodes: # Remove the namespace prefix from the tag for comparison entry = node.nodeName.replace(em, "") - if entry in details.keys(): + if entry in list(details.keys()): details.update({entry: get_text(node)}) except Exception as e: raise AddonFormatError(str(e)), None, sys.exc_info()[2] diff --git a/testing/mozbase/mozprofile/mozprofile/permissions.py b/testing/mozbase/mozprofile/mozprofile/permissions.py index ea13d96f02..1ddd5cfeda 100644 --- a/testing/mozbase/mozprofile/mozprofile/permissions.py +++ b/testing/mozbase/mozprofile/mozprofile/permissions.py @@ -267,7 +267,7 @@ class Permissions(object): for location in locations: # set the permissions permissions = {'allowXULXBL': 'noxul' not in location.options} - for perm, allow in permissions.iteritems(): + for perm, allow in permissions.items(): if allow: permission_type = 1 else: diff --git a/testing/mozbase/mozprofile/mozprofile/prefs.py b/testing/mozbase/mozprofile/mozprofile/prefs.py index 8936f3d67b..f9876dece4 100644 --- a/testing/mozbase/mozprofile/mozprofile/prefs.py +++ b/testing/mozbase/mozprofile/mozprofile/prefs.py @@ -35,7 +35,7 @@ class Preferences(object): """ # wants a list of 2-tuples if isinstance(prefs, dict): - prefs = prefs.items() + prefs = list(prefs.items()) if cast: prefs = [(i, self.cast(j)) for i, j in prefs] self._prefs += prefs @@ -124,7 +124,7 @@ class Preferences(object): raise PreferencesReadError("No section '%s' in %s" % (section, path)) retval = parser.items(section, raw=True) else: - retval = parser.defaults().items() + retval = list(parser.defaults().items()) # cast the preferences since .ini is just strings return [(i, cls.cast(j)) for i, j in retval] @@ -142,7 +142,7 @@ class Preferences(object): raise PreferencesReadError("Malformed preferences: %s" % path) values = [i[1] for i in prefs] elif isinstance(prefs, dict): - values = prefs.values() + values = list(prefs.values()) else: raise PreferencesReadError("Malformed preferences: %s" % path) types = (bool, basestring, int) @@ -217,7 +217,7 @@ class Preferences(object): if isinstance(prefs, dict): # order doesn't matter - prefs = prefs.items() + prefs = list(prefs.items()) # serialize -> JSON _prefs = [(json.dumps(k), json.dumps(v)) diff --git a/testing/mozbase/mozprofile/mozprofile/profile.py b/testing/mozbase/mozprofile/mozprofile/profile.py index bfa733684d..ff0bd285d7 100644 --- a/testing/mozbase/mozprofile/mozprofile/profile.py +++ b/testing/mozbase/mozprofile/mozprofile/profile.py @@ -66,7 +66,7 @@ class Profile(object): if preferences: if isinstance(preferences, dict): # unordered - preferences = preferences.items() + preferences = list(preferences.items()) # sanity check assert not [i for i in preferences if len(i) != 2] @@ -220,7 +220,7 @@ class Profile(object): # this is a dict sometimes, convert if isinstance(preferences, dict): - preferences = preferences.items() + preferences = list(preferences.items()) # add new prefs to preserve them during reset for new_pref in preferences: diff --git a/testing/mozbase/mozprofile/mozprofile/webapps.py b/testing/mozbase/mozprofile/mozprofile/webapps.py index 4daf9ef06a..587c883be6 100644 --- a/testing/mozbase/mozprofile/mozprofile/webapps.py +++ b/testing/mozbase/mozprofile/mozprofile/webapps.py @@ -265,7 +265,7 @@ class WebappCollection(object): apps = [] if isinstance(app_json, dict): - for k, v in app_json.iteritems(): + for k, v in app_json.items(): v['name'] = k apps.append(v) else: diff --git a/testing/mozbase/mozprofile/tests/addon_stubs.py b/testing/mozbase/mozprofile/tests/addon_stubs.py index f9602de462..cc05d48b2e 100644 --- a/testing/mozbase/mozprofile/tests/addon_stubs.py +++ b/testing/mozbase/mozprofile/tests/addon_stubs.py @@ -34,7 +34,7 @@ def generate_addon(addon_id, path=None, name=None, xpi=True): Returns the file-path of the addon's .xpi file """ - if addon_id not in stubs.keys(): + if addon_id not in list(stubs.keys()): raise IOError('Requested addon stub "%s" does not exist' % addon_id) # Generate directory structure for addon diff --git a/testing/mozbase/mozprofile/tests/test_preferences.py b/testing/mozbase/mozprofile/tests/test_preferences.py index 45d99c2e27..c57cea14d8 100755 --- a/testing/mozbase/mozprofile/tests/test_preferences.py +++ b/testing/mozbase/mozprofile/tests/test_preferences.py @@ -62,7 +62,7 @@ class PreferencesTest(unittest.TestCase): _prefs = {"browser.startup.homepage": "http://planet.mozilla.org/"} commandline = [] - _prefs = _prefs.items() + _prefs = list(_prefs.items()) for pref, value in _prefs: commandline += ["--pref", "%s:%s" % (pref, value)] self.compare_generated(_prefs, commandline) diff --git a/testing/mozbase/mozprofile/tests/test_profile_view.py b/testing/mozbase/mozprofile/tests/test_profile_view.py index 2e10a913bd..74c9f2b2db 100644 --- a/testing/mozbase/mozprofile/tests/test_profile_view.py +++ b/testing/mozbase/mozprofile/tests/test_profile_view.py @@ -57,18 +57,18 @@ class TestProfilePrint(unittest.TestCase): # diff two profiles diff = dict(mozprofile.diff(profile1, profile2)) - self.assertEqual(diff.keys(), ['user.js']) + self.assertEqual(list(diff.keys()), ['user.js']) lines = [line.strip() for line in diff['user.js'].splitlines()] self.assertTrue('+foo: bar' in lines) # diff a blank vs FirefoxProfile ff_profile = mozprofile.FirefoxProfile() diff = dict(mozprofile.diff(profile2, ff_profile)) - self.assertEqual(diff.keys(), ['user.js']) + self.assertEqual(list(diff.keys()), ['user.js']) lines = [line.strip() for line in diff['user.js'].splitlines()] self.assertTrue('-foo: bar' in lines) ff_pref_lines = ['+%s: %s' % (key, value) - for key, value in mozprofile.FirefoxProfile.preferences.items()] + for key, value in list(mozprofile.FirefoxProfile.preferences.items())] self.assertTrue(set(ff_pref_lines).issubset(lines)) if __name__ == '__main__': diff --git a/testing/mozbase/mozrunner/mozrunner/base/device.py b/testing/mozbase/mozrunner/mozrunner/base/device.py index 6eeef042f4..d52bf3082a 100644 --- a/testing/mozbase/mozrunner/mozrunner/base/device.py +++ b/testing/mozbase/mozrunner/mozrunner/base/device.py @@ -59,7 +59,7 @@ class DeviceRunner(BaseRunner): if self.app_ctx.dm._deviceSerial: cmd.extend(['-s', self.app_ctx.dm._deviceSerial]) cmd.append('shell') - for k, v in self._device_env.iteritems(): + for k, v in self._device_env.items(): cmd.append('%s=%s' % (k, v)) cmd.append(self.app_ctx.remote_binary) return cmd @@ -178,7 +178,7 @@ class FennecRunner(DeviceRunner): app_params.extend(self.cmdargs) am_subcommand.extend(["--es", "args", "'%s'" % " ".join(app_params)]) # Append env variables in the form |--es env0 MOZ_CRASHREPORTER=1| - for (count, (k, v)) in enumerate(self._device_env.iteritems()): + for (count, (k, v)) in enumerate(self._device_env.items()): am_subcommand.extend(["--es", "env%d" % count, "%s=%s" % (k, v)]) cmd.append("%s" % " ".join(am_subcommand)) return cmd diff --git a/testing/mozbase/mozrunner/mozrunner/cli.py b/testing/mozbase/mozrunner/mozrunner/cli.py index 8fe854983b..e8c628a785 100644 --- a/testing/mozbase/mozrunner/mozrunner/cli.py +++ b/testing/mozbase/mozrunner/mozrunner/cli.py @@ -63,7 +63,7 @@ class CLI(MozProfileCLI): self.profile_class = get_app_context(app).profile_class except KeyError: self.parser.error('Application "%s" unknown (should be one of "%s")' % - (app, ', '.join(runners.keys()))) + (app, ', '.join(list(runners.keys())))) def add_options(self, parser): """add options to the parser""" diff --git a/testing/mozbase/mozrunner/mozrunner/devices/android_device.py b/testing/mozbase/mozrunner/mozrunner/devices/android_device.py index d72f033d02..85294abe68 100644 --- a/testing/mozbase/mozrunner/mozrunner/devices/android_device.py +++ b/testing/mozbase/mozrunner/mozrunner/devices/android_device.py @@ -570,7 +570,7 @@ class AndroidEmulator(object): return telnet_ok def _get_avd_type(self, requested): - if requested in AVD_DICT.keys(): + if requested in list(AVD_DICT.keys()): return requested if self.substs: if not self.substs['TARGET_CPU'].startswith('arm'): diff --git a/testing/mozbase/mozrunner/mozrunner/devices/base.py b/testing/mozbase/mozrunner/mozrunner/devices/base.py index 3227aad722..0c1a3885e5 100644 --- a/testing/mozbase/mozrunner/mozrunner/devices/base.py +++ b/testing/mozbase/mozrunner/mozrunner/devices/base.py @@ -292,12 +292,12 @@ class ProfileConfigParser(RawConfigParser): def write(self, fp): if self._defaults: fp.write("[%s]\n" % ConfigParser.DEFAULTSECT) - for (key, value) in self._defaults.items(): + for (key, value) in list(self._defaults.items()): fp.write("%s=%s\n" % (key, str(value).replace('\n', '\n\t'))) fp.write("\n") for section in self._sections: fp.write("[%s]\n" % section) - for (key, value) in self._sections[section].items(): + for (key, value) in list(self._sections[section].items()): if key == "__name__": continue if (value is not None) or (self._optcre == self.OPTCRE): diff --git a/testing/mozbase/mozsystemmonitor/mozsystemmonitor/resourcemonitor.py b/testing/mozbase/mozsystemmonitor/mozsystemmonitor/resourcemonitor.py index 56a1f0ef70..71bc6a0a1a 100644 --- a/testing/mozbase/mozsystemmonitor/mozsystemmonitor/resourcemonitor.py +++ b/testing/mozbase/mozsystemmonitor/mozsystemmonitor/resourcemonitor.py @@ -676,7 +676,7 @@ class SystemResourceMonitor(object): o['events'] = [list(ev) for ev in self.events] - for phase, v in self.phases.items(): + for phase, v in list(self.phases.items()): o['phases'].append(phase_entry(phase, v[0], v[1])) if have_psutil: diff --git a/testing/mozbase/mozsystemmonitor/mozsystemmonitor/test/test_resource_monitor.py b/testing/mozbase/mozsystemmonitor/mozsystemmonitor/test/test_resource_monitor.py index b6763e20e9..5423c078b1 100644 --- a/testing/mozbase/mozsystemmonitor/mozsystemmonitor/test/test_resource_monitor.py +++ b/testing/mozbase/mozsystemmonitor/mozsystemmonitor/test/test_resource_monitor.py @@ -56,7 +56,7 @@ class TestResourceMonitor(unittest.TestCase): monitor.stop() self.assertEqual(len(monitor.phases), 2) - self.assertEqual(['phase2', 'phase1'], monitor.phases.keys()) + self.assertEqual(['phase2', 'phase1'], list(monitor.phases.keys())) all = list(monitor.range_usage()) data1 = list(monitor.phase_usage('phase1')) diff --git a/testing/mozbase/moztest/moztest/output/xunit.py b/testing/mozbase/moztest/moztest/output/xunit.py index 0d0ef7bb4d..fe833bcc07 100644 --- a/testing/mozbase/moztest/moztest/output/xunit.py +++ b/testing/mozbase/moztest/moztest/output/xunit.py @@ -86,7 +86,7 @@ class XUnitOutput(Output): for tr in results_collection.tests_with_result('PASS'): _extract_xml(tr, result='Pass') - for cls in classes.itervalues(): + for cls in classes.values(): assembly.appendChild(cls) doc.appendChild(assembly) diff --git a/testing/mozbase/moztest/moztest/results.py b/testing/mozbase/moztest/moztest/results.py index 435665c670..ce78458e0e 100644 --- a/testing/mozbase/moztest/moztest/results.py +++ b/testing/mozbase/moztest/moztest/results.py @@ -46,7 +46,7 @@ class TestContext(object): def get(attr): value = getattr(self, attr) if isinstance(value, dict): - value = frozenset(value.items()) + value = frozenset(list(value.items())) return value return hash(frozenset([get(a) for a in self.attrs])) diff --git a/testing/mozbase/mozversion/mozversion/mozversion.py b/testing/mozbase/mozversion/mozversion/mozversion.py index 5dfcd306a9..f25336a947 100644 --- a/testing/mozbase/mozversion/mozversion/mozversion.py +++ b/testing/mozbase/mozversion/mozversion/mozversion.py @@ -242,7 +242,7 @@ class RemoteB2GVersion(B2GVersion): for line in build_props.split('\n'): if not line.strip().startswith('#') and '=' in line: key, value = [s.strip() for s in line.split('=', 1)] - if key in desired_props.keys(): + if key in list(desired_props.keys()): self._info[desired_props[key]] = value if self._info.get('device_id', '').lower() == 'flame': diff --git a/testing/mozbase/setup_development.py b/testing/mozbase/setup_development.py index f49cc1926f..7d1851fe4f 100755 --- a/testing/mozbase/setup_development.py +++ b/testing/mozbase/setup_development.py @@ -41,7 +41,7 @@ extra_packages = ["sphinx"] def cycle_check(order, dependencies): """ensure no cyclic dependencies""" order_dict = dict([(j, i) for i, j in enumerate(order)]) - for package, deps in dependencies.items(): + for package, deps in list(dependencies.items()): index = order_dict[package] for d in deps: assert index > order_dict[d], "Cyclic dependencies detected" @@ -138,7 +138,7 @@ def unroll_dependencies(dependencies): # flatten all packages = set(dependencies.keys()) - for deps in dependencies.values(): + for deps in list(dependencies.values()): packages.update(deps) while len(order) != len(packages): @@ -202,7 +202,7 @@ def main(args=sys.argv[1:]): flag = True while flag: flag = False - for value in deps.values(): + for value in list(deps.values()): for dep in value: if dep in mozbase_packages and dep not in deps: key, value = get_dependencies(os.path.join(here, dep)) @@ -227,7 +227,7 @@ def main(args=sys.argv[1:]): unrolled = unroll_dependencies(deps) # make a reverse mapping: package name -> subdirectory - reverse_mapping = dict([(j, i) for i, j in mapping.items()]) + reverse_mapping = dict([(j, i) for i, j in list(mapping.items())]) # we only care about dependencies in mozbase unrolled = [package for package in unrolled if package in reverse_mapping] @@ -254,9 +254,9 @@ def main(args=sys.argv[1:]): # these need to be installed separately and the --no-deps flag # subsequently used due to a bug in setuptools; see # https://bugzilla.mozilla.org/show_bug.cgi?id=759836 - pypi_deps = dict([(i, j) for i, j in alldeps.items() + pypi_deps = dict([(i, j) for i, j in list(alldeps.items()) if i not in unrolled]) - for package, version in pypi_deps.items(): + for package, version in list(pypi_deps.items()): # easy_install should be available since we rely on setuptools call(['easy_install', version]) diff --git a/testing/mozbase/versioninfo.py b/testing/mozbase/versioninfo.py index 7abc56fd51..5f7800a0d3 100755 --- a/testing/mozbase/versioninfo.py +++ b/testing/mozbase/versioninfo.py @@ -99,7 +99,7 @@ def dependencies(args): dependencies[name] = _dependencies # print package version information - for value in info.values(): + for value in list(info.values()): print('%s %s : %s' % (value['Name'], value['Version'], ', '.join(dependencies[value['Name']]))) diff --git a/testing/mozharness/examples/action_config_script.py b/testing/mozharness/examples/action_config_script.py index d04d21f5a8..b733e6b2cd 100755 --- a/testing/mozharness/examples/action_config_script.py +++ b/testing/mozharness/examples/action_config_script.py @@ -108,7 +108,7 @@ class ActionsConfigExample(BaseScript): """) def nap(self): - for var_name in self.config.keys(): + for var_name in list(self.config.keys()): if var_name.startswith("random_config_key"): self.info("This is going to be %s!" % self.config[var_name]) sleep_time = self.config['long_sleep_time'] diff --git a/testing/mozharness/external_tools/clobberer.py b/testing/mozharness/external_tools/clobberer.py index e2fa78e22d..c881f8a11f 100755 --- a/testing/mozharness/external_tools/clobberer.py +++ b/testing/mozharness/external_tools/clobberer.py @@ -211,7 +211,7 @@ if __name__ == "__main__": root_dir = os.path.abspath(options.dir) - for builddir, (server_clobber_date, who) in server_clobber_dates.items(): + for builddir, (server_clobber_date, who) in list(server_clobber_dates.items()): builder_dir = os.path.join(root_dir, builddir) if not os.path.isdir(builder_dir): print("%s doesn't exist, skipping" % builder_dir) diff --git a/testing/mozharness/external_tools/extract_and_run_command.py b/testing/mozharness/external_tools/extract_and_run_command.py index ab48ee1dff..5167e3553d 100644 --- a/testing/mozharness/external_tools/extract_and_run_command.py +++ b/testing/mozharness/external_tools/extract_and_run_command.py @@ -90,7 +90,7 @@ def maybe_extract(filename): directory and chmods it. The consumer is responsible for removing the extracted files, if desired.""" ext = path.splitext(filename)[1] - if ext not in EXTRACTORS.keys(): + if ext not in list(EXTRACTORS.keys()): return None # Append the full filepath to the tempdir tempdir_root = tempfile.mkdtemp() diff --git a/testing/mozharness/external_tools/virtualenv/site.py b/testing/mozharness/external_tools/virtualenv/site.py index 9ef04da181..91400c9c39 100644 --- a/testing/mozharness/external_tools/virtualenv/site.py +++ b/testing/mozharness/external_tools/virtualenv/site.py @@ -100,7 +100,7 @@ def makepath(*paths): def abs__file__(): """Set all module' __file__ attribute to an absolute path""" - for m in sys.modules.values(): + for m in list(sys.modules.values()): if ((_is_jython and not isinstance(m, ModuleType)) or hasattr(m, '__loader__')): # only modules need the abspath in Jython. and don't mess diff --git a/testing/mozharness/external_tools/virtualenv/virtualenv.py b/testing/mozharness/external_tools/virtualenv/virtualenv.py index 9ebe639865..9bb7bbacc5 100755 --- a/testing/mozharness/external_tools/virtualenv/virtualenv.py +++ b/testing/mozharness/external_tools/virtualenv/virtualenv.py @@ -451,7 +451,7 @@ class ConfigOptionParser(optparse.OptionParser): # 2. environmental variables config.update(dict(self.get_environ_vars())) # Then set the options with those values - for key, val in config.items(): + for key, val in list(config.items()): key = key.replace('_', '-') if not key.startswith('--'): key = '--%s' % key # only prefer long opts @@ -490,7 +490,7 @@ class ConfigOptionParser(optparse.OptionParser): """ Returns a generator with all environmental vars with prefix VIRTUALENV """ - for key, val in os.environ.items(): + for key, val in list(os.environ.items()): if key.startswith(prefix): yield (key.replace(prefix, '').lower(), val) @@ -1459,7 +1459,7 @@ def install_files(home_dir, bin_dir, prompt, files): if hasattr(home_dir, 'decode'): home_dir = home_dir.decode(sys.getfilesystemencoding()) vname = os.path.basename(home_dir) - for name, content in files.items(): + for name, content in list(files.items()): content = content.replace('__VIRTUAL_PROMPT__', prompt or '') content = content.replace('__VIRTUAL_WINPROMPT__', prompt or '(%s)' % vname) content = content.replace('__VIRTUAL_ENV__', home_dir) @@ -1473,7 +1473,7 @@ def install_python_config(home_dir, bin_dir, prompt=None): else: files = {'python-config': PYTHON_CONFIG} install_files(home_dir, bin_dir, prompt, files) - for name, content in files.items(): + for name, content in list(files.items()): make_exe(os.path.join(bin_dir, name)) def install_distutils(home_dir): @@ -1519,7 +1519,7 @@ def fix_lib64(lib_dir, symlink=True): logger.debug('PyPy detected, skipping lib64 symlinking') return # Check we have a lib64 library path - if not [p for p in distutils.sysconfig.get_config_vars().values() + if not [p for p in list(distutils.sysconfig.get_config_vars().values()) if isinstance(p, basestring) and 'lib64' in p]: return diff --git a/testing/mozharness/external_tools/virtualenv/virtualenv_embedded/site.py b/testing/mozharness/external_tools/virtualenv/virtualenv_embedded/site.py index bda518f65f..867f7026f2 100644 --- a/testing/mozharness/external_tools/virtualenv/virtualenv_embedded/site.py +++ b/testing/mozharness/external_tools/virtualenv/virtualenv_embedded/site.py @@ -99,7 +99,7 @@ def makepath(*paths): def abs__file__(): """Set all module' __file__ attribute to an absolute path""" - for m in sys.modules.values(): + for m in list(sys.modules.values()): if ((_is_jython and not isinstance(m, ModuleType)) or hasattr(m, '__loader__')): # only modules need the abspath in Jython. and don't mess diff --git a/testing/mozharness/mozharness/base/config.py b/testing/mozharness/mozharness/base/config.py index 02da6d7604..1257b4213b 100644 --- a/testing/mozharness/mozharness/base/config.py +++ b/testing/mozharness/mozharness/base/config.py @@ -92,7 +92,7 @@ class ReadOnlyDict(dict): assert not self._lock, "ReadOnlyDict is locked!" def lock(self): - for (k, v) in self.items(): + for (k, v) in list(self.items()): self[k] = make_immutable(v) self._lock = True @@ -128,10 +128,10 @@ class ReadOnlyDict(dict): cls = self.__class__ result = cls.__new__(cls) memo[id(self)] = result - for k, v in self.__dict__.items(): + for k, v in list(self.__dict__.items()): setattr(result, k, deepcopy(v, memo)) result._lock = False - for k, v in self.items(): + for k, v in list(self.items()): result[k] = deepcopy(v, memo) return result @@ -485,7 +485,7 @@ class BaseConfig(object): # We only append values from various configs for the 'env' entry # For everything else we follow the standard behaviour for i, (c_file, c_dict) in enumerate(self.all_cfg_files_and_dicts): - for v in c_dict.keys(): + for v in list(c_dict.keys()): if v == 'env' and v in config: config[v].update(c_dict[v]) else: @@ -499,7 +499,7 @@ class BaseConfig(object): # as the keys/values that make up that instance. Ultimately, # this becomes self.config during BaseScript's init self.set_config(config) - for key in defaults.keys(): + for key in list(defaults.keys()): value = getattr(options, key) if value is None: continue @@ -511,7 +511,7 @@ class BaseConfig(object): # The idea behind the volatile_config is we don't want to save this # info over multiple runs. This defaults to the action-specific # config options, but can be anything. - for key in self.volatile_config.keys(): + for key in list(self.volatile_config.keys()): if self._config.get(key) is not None: self.volatile_config[key] = self._config[key] del(self._config[key]) diff --git a/testing/mozharness/mozharness/base/log.py b/testing/mozharness/mozharness/base/log.py index 025d3c440b..e031823906 100755 --- a/testing/mozharness/mozharness/base/log.py +++ b/testing/mozharness/mozharness/base/log.py @@ -666,7 +666,7 @@ class MultiFileLogger(BaseLogger): BaseLogger.new_logger(self) min_logger_level = self.get_logger_level(self.log_level) - for level in self.LEVELS.keys(): + for level in list(self.LEVELS.keys()): if self.get_logger_level(level) >= min_logger_level: self.log_files[level] = '%s_%s.log' % (self.log_name, level) diff --git a/testing/mozharness/mozharness/base/python.py b/testing/mozharness/mozharness/base/python.py index cb5bfbc46c..ce6fa45e2c 100644 --- a/testing/mozharness/mozharness/base/python.py +++ b/testing/mozharness/mozharness/base/python.py @@ -190,7 +190,7 @@ class VirtualenvMixin(object): """ Return whether the package is installed """ - packages = self.package_versions(error_level=error_level).keys() + packages = list(self.package_versions(error_level=error_level).keys()) return package_name.lower() in [package.lower() for package in packages] def install_module(self, module=None, module_url=None, install_method=None, @@ -646,7 +646,7 @@ class ResourceMonitoringMixin(PerfherderResourceOptionsMixin): }) - for phase in rm.phases.keys(): + for phase in list(rm.phases.keys()): phase_duration = rm.phases[phase][1] - rm.phases[phase][0] subtests = [ { @@ -726,7 +726,7 @@ class ResourceMonitoringMixin(PerfherderResourceOptionsMixin): self._tinderbox_print('Swap in / out
{:,} / {:,}'.format( swap_in, swap_out)) - for phase in rm.phases.keys(): + for phase in list(rm.phases.keys()): start_time, end_time = rm.phases[phase] cpu_percent, cpu_times, io, swap = resources(phase) log_usage(phase, end_time - start_time, cpu_percent, cpu_times, io) diff --git a/testing/mozharness/mozharness/base/script.py b/testing/mozharness/mozharness/base/script.py index f137841b6d..662317d2b1 100755 --- a/testing/mozharness/mozharness/base/script.py +++ b/testing/mozharness/mozharness/base/script.py @@ -1183,7 +1183,7 @@ class ScriptMixin(PlatformMixin): for key in default_replace_dict: if key not in replace_dict: replace_dict[key] = default_replace_dict[key] - for key in partial_env.keys(): + for key in list(partial_env.keys()): env[key] = partial_env[key] % replace_dict self.log("ENV: %s is now %s" % (key, env[key]), level=log_level) for k in purge_env: @@ -1232,7 +1232,7 @@ class ScriptMixin(PlatformMixin): if isinstance(exe, dict): found = False # allow for searchable paths of the buildbot exe - for name, path in exe.iteritems(): + for name, path in exe.items(): if isinstance(path, list) or isinstance(path, tuple): path = [x % repl_dict for x in path] if all([os.path.exists(section) for section in path]): @@ -1919,7 +1919,7 @@ class BaseScript(ScriptMixin, LogMixin, object): """Copies logs to the upload directory""" self.info("Copying logs to upload dir...") log_files = ['localconfig.json'] - for log_name in self.log_obj.log_files.keys(): + for log_name in list(self.log_obj.log_files.keys()): log_files.append(self.log_obj.log_files[log_name]) dirs = self.query_abs_dirs() for log_file in log_files: @@ -2122,7 +2122,7 @@ class BaseScript(ScriptMixin, LogMixin, object): "append_to_log": False, } log_type = self.config.get("log_type", "multi") - for key in log_config.keys(): + for key in list(log_config.keys()): value = self.config.get(key, None) if value is not None: log_config[key] = value diff --git a/testing/mozharness/mozharness/base/vcs/mercurial.py b/testing/mozharness/mozharness/base/vcs/mercurial.py index 71e5e3ea03..057ba9842f 100755 --- a/testing/mozharness/mozharness/base/vcs/mercurial.py +++ b/testing/mozharness/mozharness/base/vcs/mercurial.py @@ -481,7 +481,7 @@ class MercurialVCS(ScriptMixin, LogMixin, TransferMixin): # # So we grab the first element ("28537" in this case) and then pull # out the 'date' field. - pushid = contents.iterkeys().next() + pushid = iter(contents.keys()).next() self.info('Pushid is: %s' % pushid) pushdate = contents[pushid]['date'] self.info('Pushdate is: %s' % pushdate) diff --git a/testing/mozharness/mozharness/mozilla/buildbot.py b/testing/mozharness/mozharness/mozilla/buildbot.py index e17343633b..78e34bf558 100755 --- a/testing/mozharness/mozharness/mozilla/buildbot.py +++ b/testing/mozharness/mozharness/mozilla/buildbot.py @@ -133,7 +133,7 @@ class BuildbotMixin(object): if not os.path.isdir(dir_name): self.mkdir_p(dir_name) if not prop_list: - prop_list = self.buildbot_properties.keys() + prop_list = list(self.buildbot_properties.keys()) self.info("Writing buildbot properties to %s" % file_name) else: if not isinstance(prop_list, (list, tuple)): @@ -171,7 +171,7 @@ class BuildbotMixin(object): if self.buildbot_config['sourcestamp']['changes'][0].get('comments'): sendchange += ['--comments', self.buildbot_config['sourcestamp']['changes'][0]['comments'].encode('ascii', 'ignore')] if sendchange_props: - for key, value in sendchange_props.iteritems(): + for key, value in sendchange_props.items(): sendchange.extend(['--property', '%s:%s' % (key, value)]) else: if self.buildbot_config["properties"].get("builduid"): diff --git a/testing/mozharness/mozharness/mozilla/building/buildbase.py b/testing/mozharness/mozharness/mozilla/building/buildbase.py index 9fd507816d..8f7999f5c4 100755 --- a/testing/mozharness/mozharness/mozilla/building/buildbase.py +++ b/testing/mozharness/mozharness/mozilla/building/buildbase.py @@ -55,7 +55,7 @@ from mozharness.base.python import ( VirtualenvMixin, ) -AUTOMATION_EXIT_CODES = EXIT_STATUS_DICT.values() +AUTOMATION_EXIT_CODES = list(EXIT_STATUS_DICT.values()) AUTOMATION_EXIT_CODES.sort() MISSING_CFG_KEY_MSG = "The key '%s' could not be determined \ @@ -466,7 +466,7 @@ class BuildOptionParser(object): "shortname: %s \n\t-- a valid path in %s \n\t-- a " "valid variant for the given platform and bits." % ( prospective_cfg_path, - str(cls.build_variants.keys()), + str(list(cls.build_variants.keys())), str(cls.config_file_search_path))) parser.values.config_files.append(valid_variant_cfg_path) setattr(parser.values, option.dest, value) # the pool @@ -528,7 +528,7 @@ BUILD_BASE_CONFIG_OPTIONS = [ "help": "Sets the build type and will determine appropriate" " additional config to use. Either pass a config path" " or use a valid shortname from: " - "%s" % (BuildOptionParser.build_variants.keys(),)}], + "%s" % (list(BuildOptionParser.build_variants.keys()),)}], [['--build-pool'], { "action": "callback", "callback": BuildOptionParser.set_build_pool, @@ -676,7 +676,7 @@ platform '%(platform)s'. Updating self.config with the following from \ } ) if c.get("platform_overrides"): - if c['stage_platform'] in c['platform_overrides'].keys(): + if c['stage_platform'] in list(c['platform_overrides'].keys()): self.info( pf_override_msg % { 'branch': c['branch'], @@ -960,7 +960,7 @@ or run without that action (ie: --no-{action})" dirs = self.query_abs_dirs() check_test_env = {} if c.get('check_test_env'): - for env_var, env_value in c['check_test_env'].iteritems(): + for env_var, env_value in c['check_test_env'].items(): check_test_env[env_var] = env_value % dirs return check_test_env @@ -1224,8 +1224,8 @@ or run without that action (ie: --no-{action})" # persisted to file rather than use whats in the buildbot_properties # live object so we become less action dependant. all_current_props = dict( - chain(self.buildbot_config['properties'].items(), - self.buildbot_properties.items()) + chain(list(self.buildbot_config['properties'].items()), + list(self.buildbot_properties.items())) ) # graph_server_post.py expects a file with 'properties' key graph_props = dict(properties=all_current_props) @@ -1250,7 +1250,7 @@ or run without that action (ie: --no-{action})" if console_output: self.info("Properties set from 'mach build'") self.info(pprint.pformat(build_props)) - for key, prop in build_props.iteritems(): + for key, prop in build_props.items(): if prop != 'UNKNOWN': self.set_buildbot_property(key, prop, write_to_file=True) else: @@ -1510,7 +1510,7 @@ or run without that action (ie: --no-{action})" ] # Also upload our mozharness log files - files.extend([os.path.join(self.log_obj.abs_log_dir, x) for x in self.log_obj.log_files.values()]) + files.extend([os.path.join(self.log_obj.abs_log_dir, x) for x in list(self.log_obj.log_files.values())]) # Also upload our buildprops.json file. files.extend([os.path.join(dirs['base_work_dir'], 'buildprops.json')]) @@ -2147,7 +2147,7 @@ or run without that action (ie: --no-{action})" "Valid return codes %s" % (self.return_code, AUTOMATION_EXIT_CODES)) self.return_code = 2 - for status, return_code in EXIT_STATUS_DICT.iteritems(): + for status, return_code in EXIT_STATUS_DICT.items(): if return_code == self.return_code: self.buildbot_status(status, TBPL_STATUS_DICT[status]) self.summary() diff --git a/testing/mozharness/mozharness/mozilla/l10n/locales.py b/testing/mozharness/mozharness/mozilla/l10n/locales.py index 24920ae445..53ef7f2ff5 100755 --- a/testing/mozharness/mozharness/mozilla/l10n/locales.py +++ b/testing/mozharness/mozharness/mozilla/l10n/locales.py @@ -126,7 +126,7 @@ class LocalesMixin(ChunkingMixin): if locales_file.endswith('json'): locales_json = parse_config_file(locales_file) - for locale in locales_json.keys(): + for locale in list(locales_json.keys()): if isinstance(locales_json[locale], dict): if platform and platform not in locales_json[locale]['platforms']: continue @@ -196,7 +196,7 @@ class LocalesMixin(ChunkingMixin): dirs['abs_locales_dir'] = os.path.join(dirs['abs_objdir'], c['locales_dir']) - for key in dirs.keys(): + for key in list(dirs.keys()): if key not in abs_dirs: abs_dirs[key] = dirs[key] self.abs_dirs = abs_dirs diff --git a/testing/mozharness/mozharness/mozilla/mock.py b/testing/mozharness/mozharness/mozilla/mock.py index f8587c0d66..c548b245f8 100644 --- a/testing/mozharness/mozharness/mozilla/mock.py +++ b/testing/mozharness/mozharness/mozilla/mock.py @@ -110,7 +110,7 @@ class MockMixin(object): if env: env_cmd = ['/usr/bin/env'] - for key, value in env.items(): + for key, value in list(env.items()): # $HOME won't work inside the mock chroot if key == 'HOME': continue diff --git a/testing/mozharness/mozharness/mozilla/structuredlog.py b/testing/mozharness/mozharness/mozilla/structuredlog.py index d87c5ebdc3..0d65ac8e79 100644 --- a/testing/mozharness/mozharness/mozilla/structuredlog.py +++ b/testing/mozharness/mozharness/mozilla/structuredlog.py @@ -111,7 +111,7 @@ class StructuredOutputParser(OutputParser): 'suite_end': 'No suite end message was emitted by this harness.', 'test_end': 'No checks run.', } - for action, diagnostic_message in required_actions.iteritems(): + for action, diagnostic_message in required_actions.items(): if action not in summary.action_counts: self.log(diagnostic_message, ERROR) self.update_levels(*error_pair) diff --git a/testing/mozharness/mozharness/mozilla/testing/device.py b/testing/mozharness/mozharness/mozilla/testing/device.py index fea43ba20e..7d94128cb7 100644 --- a/testing/mozharness/mozharness/mozilla/testing/device.py +++ b/testing/mozharness/mozharness/mozilla/testing/device.py @@ -676,7 +676,7 @@ device_config_options = [[ {"action": "store", "type": "choice", "dest": "device_protocol", - "choices": DEVICE_PROTOCOL_DICT.keys(), + "choices": list(DEVICE_PROTOCOL_DICT.keys()), "help": "Specify the device communication protocol." } ], [ diff --git a/testing/mozharness/mozharness/mozilla/testing/talos.py b/testing/mozharness/mozharness/mozilla/testing/talos.py index 73f384ce7a..ce7e9e7451 100755 --- a/testing/mozharness/mozharness/mozilla/testing/talos.py +++ b/testing/mozharness/mozharness/mozilla/testing/talos.py @@ -261,7 +261,7 @@ class Talos(TestingMixin, MercurialScript, BlobUploadMixin): if tests and not isinstance(tests, basestring): tests = ':'.join(tests) # Talos expects this format kw_options['activeTests'] = tests - for key, value in kw_options.items(): + for key, value in list(kw_options.items()): options.extend(['--%s' % key, value]) # configure profiling options options.extend(self.query_sps_profile_options()) diff --git a/testing/mozharness/mozharness/mozilla/testing/testbase.py b/testing/mozharness/mozharness/mozilla/testing/testbase.py index c882a8689f..c35b44125b 100755 --- a/testing/mozharness/mozharness/mozilla/testing/testbase.py +++ b/testing/mozharness/mozharness/mozilla/testing/testbase.py @@ -258,7 +258,7 @@ class TestingMixin(VirtualenvMixin, BuildbotMixin, ResourceMonitoringMixin, if c.get("test_packages_url"): c["test_packages_url"] = _replace_url(c["test_packages_url"], c["replace_urls"]) - for key, value in self.config.iteritems(): + for key, value in self.config.items(): if type(value) == str and value.startswith("http"): self.config[key] = _replace_url(value, c["replace_urls"]) diff --git a/testing/mozharness/mozharness/mozilla/testing/try_tools.py b/testing/mozharness/mozharness/mozilla/testing/try_tools.py index 3708e71db6..5265585d25 100644 --- a/testing/mozharness/mozharness/mozilla/testing/try_tools.py +++ b/testing/mozharness/mozharness/mozilla/testing/try_tools.py @@ -109,7 +109,7 @@ class TryToolsMixin(TransferMixin): url = '{}json-pushes?changeset={}&full=1'.format(repo_url, rev) pushinfo = self.load_json_from_url(url) - for k, v in pushinfo.items(): + for k, v in list(pushinfo.items()): if isinstance(v, dict) and 'changesets' in v: msg = v['changesets'][-1]['desc'] @@ -188,7 +188,7 @@ class TryToolsMixin(TransferMixin): return label_dict[val] return '--%s' % val.replace('_', '-') - for label, (opts, _) in self.known_try_arguments.iteritems(): + for label, (opts, _) in self.known_try_arguments.items(): if 'action' in opts and opts['action'] not in ('append', 'store', 'store_true', 'store_false'): self.fatal('Try syntax does not support passing custom or store_const ' @@ -207,7 +207,7 @@ class TryToolsMixin(TransferMixin): # This is a pretty hacky way to echo arguments down to the harness. # Hopefully this can be improved once we have a configuration system # in tree for harnesses that relies less on a command line. - for arg, value in vars(args).iteritems(): + for arg, value in vars(args).items(): if value: label = label_from_val(arg) _, flavors = self.known_try_arguments[label] diff --git a/testing/mozharness/mozharness/mozilla/updates/balrog.py b/testing/mozharness/mozharness/mozilla/updates/balrog.py index 26253283cf..fe0fc814df 100644 --- a/testing/mozharness/mozharness/mozilla/updates/balrog.py +++ b/testing/mozharness/mozharness/mozilla/updates/balrog.py @@ -20,13 +20,13 @@ class BalrogMixin(object): ) if self.buildbot_config and "properties" in self.buildbot_config: - buildbot_properties = self.buildbot_config["properties"].items() + buildbot_properties = list(self.buildbot_config["properties"].items()) else: buildbot_properties = [] balrog_props = dict(properties=dict(chain( buildbot_properties, - self.buildbot_properties.items(), + list(self.buildbot_properties.items()), ))) if self.config.get('balrog_platform'): balrog_props["properties"]["platform"] = self.config['balrog_platform'] diff --git a/testing/mozharness/mozinfo/mozinfo.py b/testing/mozharness/mozinfo/mozinfo.py index 7fa5771230..310dc836a5 100755 --- a/testing/mozharness/mozinfo/mozinfo.py +++ b/testing/mozharness/mozinfo/mozinfo.py @@ -161,7 +161,7 @@ def find_and_update_from_json(*dirs): update({}) # exports -__all__ = info.keys() +__all__ = list(info.keys()) __all__ += ['is' + os_name.title() for os_name in choices['os']] __all__ += [ 'info', @@ -194,7 +194,7 @@ def main(args=None): # print out choices if requested flag = False - for key, value in options.__dict__.items(): + for key, value in list(options.__dict__.items()): if value is True: print('%s choices: %s' % (key, ' '.join([str(choice) for choice in choices[key]]))) @@ -202,7 +202,7 @@ def main(args=None): if flag: return # otherwise, print out all info - for key, value in info.items(): + for key, value in list(info.items()): print('%s: %s' % (key, value)) if __name__ == '__main__': diff --git a/testing/mozharness/mozprocess/winprocess.py b/testing/mozharness/mozprocess/winprocess.py index f8850f07ce..de96393da7 100644 --- a/testing/mozharness/mozprocess/winprocess.py +++ b/testing/mozharness/mozprocess/winprocess.py @@ -140,7 +140,7 @@ class EnvironmentBlock: self._as_parameter_ = None else: values = ["%s=%s" % (key, value) - for (key, value) in dict.iteritems()] + for (key, value) in dict.items()] values.append("") self._as_parameter_ = LPCWSTR("\0".join(values)) diff --git a/testing/mozharness/scripts/android_emulator_unittest.py b/testing/mozharness/scripts/android_emulator_unittest.py index 84c5447ed3..32cf6e4a93 100644 --- a/testing/mozharness/scripts/android_emulator_unittest.py +++ b/testing/mozharness/scripts/android_emulator_unittest.py @@ -159,7 +159,7 @@ class AndroidEmulatorTest(BlobUploadMixin, TestingMixin, EmulatorMixin, VCSMixin 'marionette', 'harness', 'marionette_harness', 'tests') dirs['abs_avds_dir'] = self.config.get("avds_dir", "/home/cltbld/.android") - for key in dirs.keys(): + for key in list(dirs.keys()): if key not in abs_dirs: abs_dirs[key] = dirs[key] self.abs_dirs = abs_dirs diff --git a/testing/mozharness/scripts/bouncer_submitter.py b/testing/mozharness/scripts/bouncer_submitter.py index eaa43e8511..db90817a2c 100755 --- a/testing/mozharness/scripts/bouncer_submitter.py +++ b/testing/mozharness/scripts/bouncer_submitter.py @@ -94,7 +94,7 @@ class BouncerSubmitter(BaseScript, PurgeMixin, BouncerSubmitterMixin, BuildbotMi def need_shipped_locales(self): return any(e.get("add-locales") for e in - self.config["products"].values()) + list(self.config["products"].values())) def query_shipped_locales_path(self): dirs = self.query_abs_dirs() diff --git a/testing/mozharness/scripts/desktop_l10n.py b/testing/mozharness/scripts/desktop_l10n.py index 0626ce35b5..561b4f6a22 100755 --- a/testing/mozharness/scripts/desktop_l10n.py +++ b/testing/mozharness/scripts/desktop_l10n.py @@ -584,7 +584,7 @@ class DesktopSingleLocale(LocalesMixin, ReleaseMixin, MockMixin, BuildbotMixin, BaseScript.add_failure(self, locale, message=message, **kwargs) def query_failed_locales(self): - return [l for l, res in self.locales_property.items() if + return [l for l, res in list(self.locales_property.items()) if res == FAILURE_STR] def summary(self): @@ -623,7 +623,7 @@ class DesktopSingleLocale(LocalesMixin, ReleaseMixin, MockMixin, BuildbotMixin, for repository in config['repos']: current_repo = {} - for key, value in repository.iteritems(): + for key, value in repository.items(): try: current_repo[key] = value % replace_dict except TypeError: @@ -880,7 +880,7 @@ class DesktopSingleLocale(LocalesMixin, ReleaseMixin, MockMixin, BuildbotMixin, abs_dirs[directory] = value dirs = {} dirs['abs_tools_dir'] = os.path.join(abs_dirs['abs_work_dir'], 'tools') - for key in dirs.keys(): + for key in list(dirs.keys()): if key not in abs_dirs: abs_dirs[key] = dirs[key] self.abs_dirs = abs_dirs @@ -1095,7 +1095,7 @@ class DesktopSingleLocale(LocalesMixin, ReleaseMixin, MockMixin, BuildbotMixin, artifacts_task = artifacts_tc.get_task(artifacts_task_id) artifacts_tc.claim_task(artifacts_task) - for locale, files in self.upload_files.iteritems(): + for locale, files in self.upload_files.items(): self.info("Uploading files to S3 for locale '%s': %s" % (locale, files)) routes = [] for template in templates: diff --git a/testing/mozharness/scripts/desktop_partner_repacks.py b/testing/mozharness/scripts/desktop_partner_repacks.py index ff07dffc84..abb4c626b6 100755 --- a/testing/mozharness/scripts/desktop_partner_repacks.py +++ b/testing/mozharness/scripts/desktop_partner_repacks.py @@ -133,7 +133,7 @@ class DesktopPartnerRepacks(ReleaseMixin, BuildbotMixin, PurgeMixin, dirs['abs_repo_dir'] = os.path.join(abs_dirs['abs_work_dir'], '.repo') dirs['abs_partners_dir'] = os.path.join(abs_dirs['abs_work_dir'], 'partners') dirs['abs_scripts_dir'] = os.path.join(abs_dirs['abs_work_dir'], 'scripts') - for key in dirs.keys(): + for key in list(dirs.keys()): if key not in abs_dirs: abs_dirs[key] = dirs[key] self.abs_dirs = abs_dirs diff --git a/testing/mozharness/scripts/desktop_unittest.py b/testing/mozharness/scripts/desktop_unittest.py index b2e7545671..cb11c06b83 100755 --- a/testing/mozharness/scripts/desktop_unittest.py +++ b/testing/mozharness/scripts/desktop_unittest.py @@ -451,7 +451,7 @@ class DesktopUnittest(TestingMixin, MercurialScript, BlobUploadMixin, MozbaseMix # suites gets a dict of everything from all_suites where a key # is also in specified_suites suites = dict((key, all_suites.get(key)) for key in - specified_suites if key in all_suites.keys()) + specified_suites if key in list(all_suites.keys())) else: if c.get('run_all_suites'): # needed if you dont specify any suites suites = all_suites @@ -536,7 +536,7 @@ class DesktopUnittest(TestingMixin, MercurialScript, BlobUploadMixin, MozbaseMix extract_dirs = None if c['specific_tests_zip_dirs']: extract_dirs = list(c['minimum_tests_zip_dirs']) - for category in c['specific_tests_zip_dirs'].keys(): + for category in list(c['specific_tests_zip_dirs'].keys()): if c['run_all_suites'] or self._query_specified_suites(category) \ or 'run-tests' not in self.actions: extract_dirs.extend(c['specific_tests_zip_dirs'][category]) diff --git a/testing/mozharness/scripts/marionette.py b/testing/mozharness/scripts/marionette.py index b7f9c2765c..2dde980b90 100755 --- a/testing/mozharness/scripts/marionette.py +++ b/testing/mozharness/scripts/marionette.py @@ -163,7 +163,7 @@ class MarionetteTest(TestingMixin, MercurialScript, BlobUploadMixin, TransferMix dirs['abs_blob_upload_dir'] = os.path.join(abs_dirs['abs_work_dir'], 'blobber_upload_dir') - for key in dirs.keys(): + for key in list(dirs.keys()): if key not in abs_dirs: abs_dirs[key] = dirs[key] self.abs_dirs = abs_dirs diff --git a/testing/mozharness/scripts/marionette_harness_tests.py b/testing/mozharness/scripts/marionette_harness_tests.py index 0811bef9cb..da92249a81 100644 --- a/testing/mozharness/scripts/marionette_harness_tests.py +++ b/testing/mozharness/scripts/marionette_harness_tests.py @@ -131,7 +131,7 @@ class MarionetteHarnessTests(VirtualenvMixin, BuildbotMixin, BaseScript): self.info('Calling pytest.main with the following arguments: %s' % command) status = self._get_pytest_status(pytest.main(command)) self.read_from_file(logs['tbpl']) - for log in logs.values(): + for log in list(logs.values()): self.copy_to_upload_dir(log, dest='logs/') self.buildbot_status(status) diff --git a/testing/mozharness/scripts/mobile_partner_repack.py b/testing/mozharness/scripts/mobile_partner_repack.py index 8d99f825a5..603d3a4fb9 100755 --- a/testing/mozharness/scripts/mobile_partner_repack.py +++ b/testing/mozharness/scripts/mobile_partner_repack.py @@ -242,7 +242,7 @@ class MobilePartnerRepack(LocalesMixin, ReleaseMixin, MobileSigningMixin, self.warning("%s:%s had previous issues; skipping!" % (platform, locale)) continue original_path = '%s/original/%s/%s/%s' % (dirs['abs_work_dir'], platform, locale, installer_name) - for partner in c['partner_config'].keys(): + for partner in list(c['partner_config'].keys()): repack_path = '%s/unsigned/partner-repacks/%s/%s/%s/%s' % (dirs['abs_work_dir'], partner, platform, locale, installer_name) total_count += 1 if self._repack_apk(partner, original_path, repack_path): @@ -291,7 +291,7 @@ class MobilePartnerRepack(LocalesMixin, ReleaseMixin, MobileSigningMixin, if self.query_failure(platform, locale): self.warning("%s:%s had previous issues; skipping!" % (platform, locale)) continue - for partner in c['partner_config'].keys(): + for partner in list(c['partner_config'].keys()): unsigned_path = '%s/unsigned/partner-repacks/%s/%s/%s/%s' % (dirs['abs_work_dir'], partner, platform, locale, installer_name) signed_dir = '%s/partner-repacks/%s/%s/%s' % (dirs['abs_work_dir'], partner, platform, locale) signed_path = "%s/%s" % (signed_dir, installer_name) diff --git a/testing/mozharness/scripts/release/beet_mover.py b/testing/mozharness/scripts/release/beet_mover.py index 6961b52054..bab46dded8 100755 --- a/testing/mozharness/scripts/release/beet_mover.py +++ b/testing/mozharness/scripts/release/beet_mover.py @@ -364,7 +364,7 @@ class BeetMover(BaseScript, VirtualenvMixin, object): def mime_fix(self): """ Add mimetypes for custom extensions """ mimetypes.init() - list(map(lambda (ext, mime_type,): mimetypes.add_type(mime_type, ext), MIME_MAP.items())) + list(map(lambda (ext, mime_type,): mimetypes.add_type(mime_type, ext), list(MIME_MAP.items()))) if __name__ == '__main__': beet_mover = BeetMover(pop_aws_auth_from_env()) diff --git a/testing/mozharness/scripts/release/generate-checksums.py b/testing/mozharness/scripts/release/generate-checksums.py index 61a1c43d25..2d0acc9eb9 100644 --- a/testing/mozharness/scripts/release/generate-checksums.py +++ b/testing/mozharness/scripts/release/generate-checksums.py @@ -204,7 +204,7 @@ class ChecksumsGenerator(BaseScript, VirtualenvMixin, SigningMixin, VCSMixin, Bu pool.map(worker, find_checksums_files()) for c in raw_checksums: - for f, info in parse_checksums_file(c).iteritems(): + for f, info in parse_checksums_file(c).items(): for pattern in self.config["includes"]: if re.search(pattern, f): if f in self.checksums: diff --git a/testing/mozharness/scripts/release/postrelease_bouncer_aliases.py b/testing/mozharness/scripts/release/postrelease_bouncer_aliases.py index 78a60b4bc5..260d3eecd3 100644 --- a/testing/mozharness/scripts/release/postrelease_bouncer_aliases.py +++ b/testing/mozharness/scripts/release/postrelease_bouncer_aliases.py @@ -94,7 +94,7 @@ class PostReleaseBouncerAliases(BaseScript, VirtualenvMixin, BuildbotMixin): execfile(credentials_file, credentials) auth = (credentials['tuxedoUsername'], credentials['tuxedoPassword']) version = self.config['version'] - for product, info in self.config["products"].iteritems(): + for product, info in self.config["products"].items(): if "alias" in info: product_template = info["product-name"] related_product = product_template % {"version": version} diff --git a/testing/mozharness/scripts/release/publish_balrog.py b/testing/mozharness/scripts/release/publish_balrog.py index edb3813112..80d50d7c07 100644 --- a/testing/mozharness/scripts/release/publish_balrog.py +++ b/testing/mozharness/scripts/release/publish_balrog.py @@ -73,7 +73,7 @@ class PublishBalrog(MercurialScript, BuildbotMixin): :return: list """ - return [(n, c) for n, c in self.config["update_channels"].items() if + return [(n, c) for n, c in list(self.config["update_channels"].items()) if n in self.config["channels"]] def query_repos(self): diff --git a/testing/mozharness/scripts/release/updates.py b/testing/mozharness/scripts/release/updates.py index 4b660a67b8..caa189f625 100644 --- a/testing/mozharness/scripts/release/updates.py +++ b/testing/mozharness/scripts/release/updates.py @@ -146,7 +146,7 @@ class UpdatesBumper(MercurialScript, BuildbotMixin, :return: list """ - return [(n, c) for n, c in self.config["update_channels"].items() if + return [(n, c) for n, c in list(self.config["update_channels"].items()) if n in self.config["channels"]] def pull(self): diff --git a/testing/mozharness/scripts/release/uptake_monitoring.py b/testing/mozharness/scripts/release/uptake_monitoring.py index 9ec24621f6..7c932ce0a7 100644 --- a/testing/mozharness/scripts/release/uptake_monitoring.py +++ b/testing/mozharness/scripts/release/uptake_monitoring.py @@ -122,7 +122,7 @@ class UptakeMonitoring(BaseScript, VirtualenvMixin, BuildbotMixin): version = self.config["version"] dl = [] - for product, info in self.config["products"].iteritems(): + for product, info in self.config["products"].items(): if info.get("check_uptake"): product_template = info["product-name"] related_product = product_template % {"version": version} @@ -137,7 +137,7 @@ class UptakeMonitoring(BaseScript, VirtualenvMixin, BuildbotMixin): related_product, bouncer_platform)) # handle the partials as well prev_versions = self.config["partial_versions"] - for product, info in self.config["partials"].iteritems(): + for product, info in self.config["partials"].items(): if info.get("check_uptake"): product_template = info["product-name"] for prev_version in prev_versions: diff --git a/testing/mozharness/scripts/spidermonkey_build.py b/testing/mozharness/scripts/spidermonkey_build.py index b474e1aec0..04046f80a2 100755 --- a/testing/mozharness/scripts/spidermonkey_build.py +++ b/testing/mozharness/scripts/spidermonkey_build.py @@ -166,7 +166,7 @@ class SpidermonkeyBuild(MockMixin, dirs = self.query_abs_dirs() replacements = self.config['env_replacements'].copy() - for k,v in replacements.items(): + for k,v in list(replacements.items()): replacements[k] = v % dirs self.env = self.query_env(replace_dict=replacements, diff --git a/testing/mozharness/test/test_base_config.py b/testing/mozharness/test/test_base_config.py index 42ec7a641d..874cc1d207 100644 --- a/testing/mozharness/test/test_base_config.py +++ b/testing/mozharness/test/test_base_config.py @@ -38,13 +38,13 @@ class TestParseConfigFile(unittest.TestCase): def test_json_config(self): c = config.BaseConfig(initial_config_file='test/test.json') content_dict = self._get_json_config() - for key in content_dict.keys(): + for key in list(content_dict.keys()): self.assertEqual(content_dict[key], c._config[key]) def test_python_config(self): c = config.BaseConfig(initial_config_file='test/test.py') config_dict = self._get_python_config() - for key in config_dict.keys(): + for key in list(config_dict.keys()): self.assertEqual(config_dict[key], c._config[key]) def test_illegal_config(self): @@ -158,7 +158,7 @@ class TestReadOnlyDict(unittest.TestCase): def test_set_default(self): r = self.get_unlocked_ROD() - for key in self.control_dict.keys(): + for key in list(self.control_dict.keys()): r.setdefault(key, self.control_dict[key]) self.assertEqual(r, self.control_dict, msg="can't setdefault() ReadOnlyDict when unlocked") diff --git a/testing/mozharness/test/test_base_script.py b/testing/mozharness/test/test_base_script.py index 99ede69e97..250cdb6cb4 100644 --- a/testing/mozharness/test/test_base_script.py +++ b/testing/mozharness/test/test_base_script.py @@ -100,7 +100,7 @@ class TestScript(unittest.TestCase): # now let's see if only unique items were added from each config t_override = local_cfg_files.get('test/test_override.py', {}) self.assertTrue( - t_override.get('keep_string') == "don't change me" and len(t_override.keys()) == 1, + t_override.get('keep_string') == "don't change me" and len(list(t_override.keys())) == 1, msg="--dump-config-hierarchy dumped wrong keys/value for " "`test/test_override.py`. There should only be one " "item and it should be unique to all the other " diff --git a/testing/mozharness/test/test_l10n_locales.py b/testing/mozharness/test/test_l10n_locales.py index e8372a9fbb..7889a7dbe3 100644 --- a/testing/mozharness/test/test_l10n_locales.py +++ b/testing/mozharness/test/test_l10n_locales.py @@ -85,21 +85,21 @@ class TestLocalesMixin(unittest.TestCase): def test_query_abs_dirs_base(self): l = self._get_query_abs_dirs_obj() - dirs = l.query_abs_dirs().keys() + dirs = list(l.query_abs_dirs().keys()) dirs.sort() self.assertEqual(dirs, self.BASE_ABS_DIRS) def test_query_abs_dirs_base2(self): l = self._get_query_abs_dirs_obj() - l.query_abs_dirs().keys() - dirs = l.query_abs_dirs().keys() + list(l.query_abs_dirs().keys()) + dirs = list(l.query_abs_dirs().keys()) dirs.sort() self.assertEqual(dirs, self.BASE_ABS_DIRS) def test_query_abs_dirs_l10n(self): l = self._get_query_abs_dirs_obj() l.config['l10n_dir'] = "l10n_dir" - dirs = l.query_abs_dirs().keys() + dirs = list(l.query_abs_dirs().keys()) dirs.sort() expected_dirs = self.BASE_ABS_DIRS + ['abs_l10n_dir'] expected_dirs.sort() @@ -110,7 +110,7 @@ class TestLocalesMixin(unittest.TestCase): l.config['l10n_dir'] = "l10n_dir" l.config['mozilla_dir'] = "mozilla_dir" l.config['locales_dir'] = "locales_dir" - dirs = l.query_abs_dirs().keys() + dirs = list(l.query_abs_dirs().keys()) dirs.sort() expected_dirs = self.BASE_ABS_DIRS + ['abs_mozilla_dir', 'abs_locales_src_dir', 'abs_l10n_dir'] expected_dirs.sort() @@ -122,7 +122,7 @@ class TestLocalesMixin(unittest.TestCase): l.config['mozilla_dir'] = "mozilla_dir" l.config['locales_dir'] = "locales_dir" l.config['objdir'] = "objdir" - dirs = l.query_abs_dirs().keys() + dirs = list(l.query_abs_dirs().keys()) dirs.sort() expected_dirs = self.BASE_ABS_DIRS + ['abs_mozilla_dir', 'abs_locales_src_dir', 'abs_l10n_dir', 'abs_objdir', 'abs_merge_dir', 'abs_locales_dir'] expected_dirs.sort() diff --git a/testing/runtimes/writeruntimes.py b/testing/runtimes/writeruntimes.py index d67d5b0055..a3edfdd916 100644 --- a/testing/runtimes/writeruntimes.py +++ b/testing/runtimes/writeruntimes.py @@ -55,7 +55,7 @@ def write_runtimes(data, suite, indir=here, outdir=here): # identify a threshold of durations, below which we ignore runtimes = [] - for result in data.itervalues(): + for result in data.values(): duration = int(result * 1000) if result else 0 if duration: runtimes.append(duration) @@ -66,7 +66,7 @@ def write_runtimes(data, suite, indir=here, outdir=here): omitted = [] specified = indata if indata else {} current_tests = [] - for test, duration in data.iteritems(): + for test, duration in data.items(): current_tests.append(test) duration = int(duration * 1000) if duration else 0 if duration > 0 and duration < threshold: diff --git a/testing/talos/talos/cmanager.py b/testing/talos/talos/cmanager.py index 4192e777e0..12e1999a44 100644 --- a/testing/talos/talos/cmanager.py +++ b/testing/talos/talos/cmanager.py @@ -16,7 +16,7 @@ class CounterManager(object): def _loadCounters(self): """Loads all of the counters defined in the counterDict""" - for counter in self.counterDict.keys(): + for counter in list(self.counterDict.keys()): self.allCounters[counter] = self.counterDict[counter] def registerCounters(self, counters): diff --git a/testing/talos/talos/cmdline.py b/testing/talos/talos/cmdline.py index e1dea7d41a..3a35c603df 100644 --- a/testing/talos/talos/cmdline.py +++ b/testing/talos/talos/cmdline.py @@ -26,7 +26,7 @@ class _ListTests(_StopAction): print('================\n') test_class_names = [ (test_class.name(), test_class.description()) - for test_class in test.test_dict().itervalues() + for test_class in test.test_dict().values() ] test_class_names.sort() for name, description in test_class_names: diff --git a/testing/talos/talos/config.py b/testing/talos/talos/config.py index a5906bd381..a37a6b0a4d 100644 --- a/testing/talos/talos/config.py +++ b/testing/talos/talos/config.py @@ -377,7 +377,7 @@ def get_test(config, global_overrides, counters, test_instance): _counters = getattr(test_instance, key) _counters.extend([counter for counter in counters if counter not in _counters]) - return dict(test_instance.items()) + return dict(list(test_instance.items())) @validator @@ -415,7 +415,7 @@ def get_browser_config(config): browser_config = dict(title=config['title']) browser_config.update(dict([(i, config[i]) for i in required])) browser_config.update(dict([(i, config.get(i, j)) - for i, j in optional.items()])) + for i, j in list(optional.items())])) return browser_config @@ -448,7 +448,7 @@ def get_config(argv=None): for validate in CONF_VALIDATORS: validate(config) # remove None Values - for k, v in config.items(): + for k, v in list(config.items()): if v is None: del config[k] return config diff --git a/testing/talos/talos/ffsetup.py b/testing/talos/talos/ffsetup.py index 14ff576d54..6c3951ae83 100644 --- a/testing/talos/talos/ffsetup.py +++ b/testing/talos/talos/ffsetup.py @@ -61,7 +61,7 @@ class FFSetup(object): def _init_env(self): self.env = dict(os.environ) - for k, v in self.browser_config['env'].iteritems(): + for k, v in self.browser_config['env'].items(): self.env[k] = str(v) self.env['MOZ_CRASHREPORTER_NO_REPORT'] = '1' # for winxp e10s logging: @@ -79,14 +79,14 @@ class FFSetup(object): if self.test_config.get('preferences'): test_prefs = dict( [(i, utils.parse_pref(j)) - for i, j in self.test_config['preferences'].items()] + for i, j in list(self.test_config['preferences'].items())] ) preferences.update(test_prefs) # interpolate webserver value in prefs webserver = self.browser_config['webserver'] if '://' not in webserver: webserver = 'http://' + webserver - for name, value in preferences.items(): + for name, value in list(preferences.items()): if type(value) is str: value = utils.interpolate(value, webserver=webserver) preferences[name] = value diff --git a/testing/talos/talos/mainthreadio.py b/testing/talos/talos/mainthreadio.py index 0288859027..08a9b3f4da 100644 --- a/testing/talos/talos/mainthreadio.py +++ b/testing/talos/talos/mainthreadio.py @@ -95,7 +95,7 @@ def write_output(outfilename, data): try: with open(outfilename, 'w') as outfile: outfile.write("[\n") - for idx, (key, value) in utils.indexed_items(data.iteritems()): + for idx, (key, value) in utils.indexed_items(iter(data.items())): output = " [\"%s\", \"%s\", \"%s\", \"%s\", %d, %d, %f]" % ( key[0], key[1], key[2], key[3], value[KEY_COUNT], value[KEY_RUN_COUNT], value[KEY_DURATION]) diff --git a/testing/talos/talos/output.py b/testing/talos/talos/output.py index 003e98f021..cf76c2c5e8 100755 --- a/testing/talos/talos/output.py +++ b/testing/talos/talos/output.py @@ -128,7 +128,7 @@ class Output(object): # counters results_aux data counter_subtests = [] for cd in test.all_counter_results: - for name, vals in cd.items(): + for name, vals in list(cd.items()): # We want to add the xperf data as talos_counters # exclude counters whose values are tuples (bad for # graphserver) diff --git a/testing/talos/talos/profiler/symFileManager.py b/testing/talos/talos/profiler/symFileManager.py index 0413a9ee81..bd94260a31 100755 --- a/testing/talos/talos/profiler/symFileManager.py +++ b/testing/talos/talos/profiler/symFileManager.py @@ -165,7 +165,7 @@ class SymFileManager: return None logString = "Found " + \ - str(len(symbolMap.keys())) + " unique entries from " + str(len(list(symbolMap.keys()))) + " unique entries from " logString += str(publicCount) + " PUBLIC lines, " + \ str(funcCount) + " FUNC lines" LogTrace(logString) diff --git a/testing/talos/talos/profiler/symbolication.py b/testing/talos/talos/profiler/symbolication.py index 854a2c76d8..36cdd4ead5 100755 --- a/testing/talos/talos/profiler/symbolication.py +++ b/testing/talos/talos/profiler/symbolication.py @@ -356,7 +356,7 @@ class ProfileSymbolicator: libs_with_symbols[lib["start"]] = { "library": lib, "symbols": set()} libs_with_symbols[lib["start"]]["symbols"].add(address) - return libs_with_symbols.values() + return list(libs_with_symbols.values()) def _module_from_lib(self, lib): if "breakpadId" in lib: diff --git a/testing/talos/talos/results.py b/testing/talos/talos/results.py index b52b39d4a5..84b0b072b0 100755 --- a/testing/talos/talos/results.py +++ b/testing/talos/talos/results.py @@ -38,7 +38,7 @@ class TalosResults(object): tbpl_output = {} try: - for key, urls in output_formats.items(): + for key, urls in list(output_formats.items()): _output = output.Output(self) results = _output() for url in urls: @@ -420,7 +420,7 @@ class BrowserLogResults(object): self.mainthread_io(counter_results) if not set(counters).union(set(mainthread_counters))\ - .intersection(counter_results.keys()): + .intersection(list(counter_results.keys())): # no xperf counters to accumulate return @@ -455,7 +455,7 @@ class BrowserLogResults(object): counter_results.setdefault(counter_name, []).append(value) self.using_xperf = True - if (set(mainthread_counters).intersection(counter_results.keys())): + if (set(mainthread_counters).intersection(list(counter_results.keys()))): filename = 'etl_output.csv' if not os.path.exists(filename): print(("Warning: we are looking for xperf results file" @@ -485,7 +485,7 @@ class BrowserLogResults(object): counters = ['Main', 'Content'] if not set(['%s_RSS' % i for i in counters])\ - .intersection(counter_results.keys()): + .intersection(list(counter_results.keys())): # no RSS counters to accumulate return for line in self.results_raw.split('\n'): diff --git a/testing/talos/talos/sps_profile.py b/testing/talos/talos/sps_profile.py index 9c778007a0..4be76179ed 100644 --- a/testing/talos/talos/sps_profile.py +++ b/testing/talos/talos/sps_profile.py @@ -205,5 +205,5 @@ class SpsProfile(object): Clean up temp folders created with the instance creation. """ mozfile.remove(self.option('dir')) - for symbol_path in self.symbol_paths.values(): + for symbol_path in list(self.symbol_paths.values()): mozfile.remove(symbol_path) diff --git a/testing/talos/talos/talosconfig.py b/testing/talos/talos/talosconfig.py index 2645a56bf3..24d920abe2 100644 --- a/testing/talos/talos/talosconfig.py +++ b/testing/talos/talos/talosconfig.py @@ -3,7 +3,7 @@ import json def writeConfigFile(obj, vals): - data = dict((opt, obj[opt]) for opt in (vals or obj.keys())) + data = dict((opt, obj[opt]) for opt in (vals or list(obj.keys()))) return json.dumps(data) diff --git a/testing/talos/talos/test.py b/testing/talos/talos/test.py index 6df5835bb7..53c8995cd6 100644 --- a/testing/talos/talos/test.py +++ b/testing/talos/talos/test.py @@ -65,7 +65,7 @@ class Test(object): def __str__(self): """string form appropriate for YAML output""" - items = self.items() + items = list(self.items()) key, value = items.pop(0) lines = ["- %s: %s" % (key, value)] diff --git a/testing/talos/talos/ttest.py b/testing/talos/talos/ttest.py index 3c57f020dd..639ea05ed4 100644 --- a/testing/talos/talos/ttest.py +++ b/testing/talos/talos/ttest.py @@ -240,10 +240,10 @@ class TTest(object): # include global (cross-cycle) counters test_results.all_counter_results.extend( - [{key: value} for key, value in global_counters.items()] + [{key: value} for key, value in list(global_counters.items())] ) for c in test_results.all_counter_results: - for key, value in c.items(): + for key, value in list(c.items()): LOG.debug("COUNTER %r: %s" % (key, value)) # return results diff --git a/testing/talos/talos/whitelist.py b/testing/talos/talos/whitelist.py index 71aaaa3101..d1c9fb2757 100644 --- a/testing/talos/talos/whitelist.py +++ b/testing/talos/talos/whitelist.py @@ -45,7 +45,7 @@ class Whitelist: filename = filename.lower() filename.replace(' (x86)', '') - for path, subst in self.path_substitutions.iteritems(): + for path, subst in self.path_substitutions.items(): parts = filename.split(path) if len(parts) >= 2: if self.PRE_PROFILE == '' and subst == '{profile}': @@ -68,7 +68,7 @@ class Whitelist: filename = "%s%s" % (subst, path.join(parts[1:])) - for old_name, new_name in self.name_substitutions.iteritems(): + for old_name, new_name in self.name_substitutions.items(): parts = filename.split(old_name) if len(parts) >= 2: filename = "%s%s" % (parts[0], new_name) @@ -77,7 +77,7 @@ class Whitelist: def check(self, test, file_name_index): errors = {} - for row_key in test.iterkeys(): + for row_key in test.keys(): filename = self.sanitize_filename(row_key[file_name_index]) if filename in self.listmap: @@ -94,7 +94,7 @@ class Whitelist: def checkDuration(self, test, file_name_index, file_duration_index): errors = {} - for idx, (row_key, row_value) in utils.indexed_items(test.iteritems()): + for idx, (row_key, row_value) in utils.indexed_items(iter(test.items())): if row_value[file_duration_index] > DEFAULT_DURATION: filename = self.sanitize_filename(row_key[file_name_index]) if filename in self.listmap and \ @@ -113,7 +113,7 @@ class Whitelist: return errors def filter(self, test, file_name_index): - for row_key in test.keys(): + for row_key in list(test.keys()): filename = self.sanitize_filename(row_key[file_name_index]) if filename in self.listmap: if 'ignore' in self.listmap[filename] and \ @@ -127,7 +127,7 @@ class Whitelist: @staticmethod def get_error_strings(errors): error_strs = [] - for filename, data in errors.iteritems(): + for filename, data in errors.items(): for datum in data: error_strs.append("File '%s' was accessed and we were not" " expecting it: %r" % (filename, datum)) diff --git a/testing/talos/talos/xtalos/etlparser.py b/testing/talos/talos/xtalos/etlparser.py index 519081bc97..561d643c71 100644 --- a/testing/talos/talos/xtalos/etlparser.py +++ b/testing/talos/talos/xtalos/etlparser.py @@ -297,7 +297,7 @@ def etlparser(xperf_path, etl_filename, processID, approot=None, mozfile.remove(csvname) output = "thread, stage, counter, value\n" - for cntr in sorted(io.iterkeys()): + for cntr in sorted(io.keys()): output += "%s, %s\n" % (", ".join(cntr), str(io[cntr])) if outputFile: fname = "%s_thread_stats%s" % os.path.splitext(outputFile) @@ -314,7 +314,7 @@ def etlparser(xperf_path, etl_filename, processID, approot=None, # Filter out stages, threads, and whitelisted files that we're not # interested in - filekeys = [x for x in files.iterkeys() if (all_stages or x[2] == stages[0]) and + filekeys = [x for x in files.keys() if (all_stages or x[2] == stages[0]) and (all_threads or x[1].endswith("(main)")) and (all_stages and x[2] != stages[0] or not checkWhitelist(x[0], whitelist))] diff --git a/testing/talos/talos/xtalos/parse_xperf.py b/testing/talos/talos/xtalos/parse_xperf.py index 5a82331632..5e2bef61fb 100644 --- a/testing/talos/talos/xtalos/parse_xperf.py +++ b/testing/talos/talos/xtalos/parse_xperf.py @@ -33,7 +33,7 @@ def stop_from_config(config_file=None, debug=False, **kwargs): kwargs = xtalos.options_from_config(kwargs, config_file) # ensure the required options are given - for key, msg in required.items(): + for key, msg in list(required.items()): if not kwargs.get(key): raise xtalos.XTalosError(msg) diff --git a/testing/talos/talos/xtalos/start_xperf.py b/testing/talos/talos/xtalos/start_xperf.py index 609e591baf..dbca3e1ac7 100644 --- a/testing/talos/talos/xtalos/start_xperf.py +++ b/testing/talos/talos/xtalos/start_xperf.py @@ -48,7 +48,7 @@ def start_from_config(config_file=None, debug=False, **kwargs): kwargs = xtalos.options_from_config(kwargs, config_file) # ensure the required options are given - for key, msg in required.items(): + for key, msg in list(required.items()): if not kwargs.get(key): raise xtalos.XTalosError(msg) @@ -58,7 +58,7 @@ def start_from_config(config_file=None, debug=False, **kwargs): % kwargs['xperf_path']) # make calling arguments - args = dict([(key, kwargs[key]) for key in required.keys()]) + args = dict([(key, kwargs[key]) for key in list(required.keys())]) args['debug'] = debug # call start diff --git a/testing/talos/talos/xtalos/xtalos.py b/testing/talos/talos/xtalos/xtalos.py index cb14397dba..04166d81e3 100644 --- a/testing/talos/talos/xtalos/xtalos.py +++ b/testing/talos/talos/xtalos/xtalos.py @@ -25,7 +25,7 @@ def options_from_config(options, config_file): with open(config_file, 'r') as config: conf = json.load(config) - for optname, value in options.items(): + for optname, value in list(options.items()): options[optname] = conf.get(optname, value) return options diff --git a/testing/tools/autotry/autotry.py b/testing/tools/autotry/autotry.py index 343eef22f5..839e34e549 100644 --- a/testing/tools/autotry/autotry.py +++ b/testing/tools/autotry/autotry.py @@ -43,7 +43,7 @@ def arg_parser(): parser.add_argument('-v', '--verbose', dest='verbose', action='store_true', default=False, help='Print detailed information about the resulting test selection ' 'and commands performed.') - for arg, opts in AutoTry.pass_through_arguments.items(): + for arg, opts in list(AutoTry.pass_through_arguments.items()): parser.add_argument(arg, **opts) return parser @@ -351,7 +351,7 @@ class AutoTry(object): dir_relpath = os.path.dirname(file_relpath) paths_by_flavor[flavor].add(dir_relpath) - for flavor, path_set in paths_by_flavor.items(): + for flavor, path_set in list(paths_by_flavor.items()): paths_by_flavor[flavor] = self.deduplicate_prefixes(path_set, paths) return dict(paths_by_flavor) @@ -388,7 +388,7 @@ class AutoTry(object): suites = tests if not intersection else {} paths = set() - for flavor, flavor_tests in paths_by_flavor.iteritems(): + for flavor, flavor_tests in paths_by_flavor.items(): suite = self.flavor_suites[flavor] if suite not in suites and (not intersection or suite in tests): for job_name in self.flavor_jobs[flavor]: @@ -401,7 +401,7 @@ class AutoTry(object): if extras.get('artifact'): rejected = [] - for suite in suites.keys(): + for suite in list(suites.keys()): if any([suite.startswith(c) for c in self.compiled_suites]): rejected.append(suite) if rejected: @@ -422,8 +422,8 @@ class AutoTry(object): if paths: parts.append("--try-test-paths %s" % " ".join(sorted(paths))) - args_by_dest = {v['dest']: k for k, v in AutoTry.pass_through_arguments.items()} - for dest, value in extras.iteritems(): + args_by_dest = {v['dest']: k for k, v in list(AutoTry.pass_through_arguments.items())} + for dest, value in extras.items(): assert dest in args_by_dest arg = args_by_dest[dest] action = AutoTry.pass_through_arguments[arg]['action'] @@ -438,7 +438,7 @@ class AutoTry(object): parts.append(arg) try_syntax = " ".join(parts) - if extras.get('artifact') and 'all' in suites.keys(): + if extras.get('artifact') and 'all' in list(suites.keys()): message = ('You asked for |-u all| with |--artifact| but compiled-code tests ({tests})' ' can\'t run against an artifact build. Try listing the suites you want' ' instead. For example, this syntax covers most suites:\n{try_syntax}') @@ -572,7 +572,7 @@ class AutoTry(object): reader = BuildReader(config) files_info = reader.files_info(changed_files) - for path, info in files_info.items(): + for path, info in list(files_info.items()): paths |= info.test_files tags |= info.test_tags diff --git a/testing/tools/iceserver/iceserver.py b/testing/tools/iceserver/iceserver.py index e8292b4c7b..a169f653a2 100644 --- a/testing/tools/iceserver/iceserver.py +++ b/testing/tools/iceserver/iceserver.py @@ -678,7 +678,7 @@ class TcpStunHandler(protocol.Protocol): def connectionLost(self, reason): print(("Lost connection from {}".format(self.address))) # Destroy allocations that this connection made - for key, allocation in allocations.items(): + for key, allocation in list(allocations.items()): if allocation.other_transport_handler == self: print(("Closing allocation due to dropped connection: {}" .format(key))) @@ -711,7 +711,7 @@ except: def prune_allocations(): now = time.time() - for key, allocation in allocations.items(): + for key, allocation in list(allocations.items()): if allocation.expiry < now: print(("Allocation expired: {}".format(key))) del allocations[key] diff --git a/testing/tools/mach_test_package_bootstrap.py b/testing/tools/mach_test_package_bootstrap.py index f7a8fb397b..9b9db7e14b 100644 --- a/testing/tools/mach_test_package_bootstrap.py +++ b/testing/tools/mach_test_package_bootstrap.py @@ -179,7 +179,7 @@ def bootstrap(test_package_root): mach = mach.main.Mach(os.getcwd()) mach.populate_context_handler = populate_context - for category, meta in CATEGORIES.items(): + for category, meta in list(CATEGORIES.items()): mach.define_category(category, meta['short'], meta['long'], meta['priority']) diff --git a/testing/tools/proxyserver/proxyserver.py b/testing/tools/proxyserver/proxyserver.py index c65b6aeea8..f91c26078a 100644 --- a/testing/tools/proxyserver/proxyserver.py +++ b/testing/tools/proxyserver/proxyserver.py @@ -78,7 +78,7 @@ class HTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def getHeaders(self): h = {} - for name in self.headers.keys(): + for name in list(self.headers.keys()): h[name] = self.headers[name] return h diff --git a/testing/tps/create_venv.py b/testing/tps/create_venv.py index 810ddd585a..9186f15d8a 100755 --- a/testing/tps/create_venv.py +++ b/testing/tps/create_venv.py @@ -93,7 +93,7 @@ def update_configfile(source, target, replacements): with open(source) as config: for line in config: - for source_string, target_string in replacements.iteritems(): + for source_string, target_string in replacements.items(): if target_string: line = line.replace(source_string, target_string) lines.append(line) diff --git a/testing/xpcshell/mach_commands.py b/testing/xpcshell/mach_commands.py index d821ff46fb..2ca2a2fb94 100644 --- a/testing/xpcshell/mach_commands.py +++ b/testing/xpcshell/mach_commands.py @@ -124,7 +124,7 @@ class XPCShellRunner(MozbuildObject): # Python through 2.7.2 has issues with unicode in some of the # arguments. Work around that. filtered_args = {} - for k, v in kwargs.iteritems(): + for k, v in kwargs.items(): if isinstance(v, unicode_type): v = v.encode('utf-8') diff --git a/testing/xpcshell/remotexpcshelltests.py b/testing/xpcshell/remotexpcshelltests.py index 4886bf71e5..df558f486b 100644 --- a/testing/xpcshell/remotexpcshelltests.py +++ b/testing/xpcshell/remotexpcshelltests.py @@ -321,7 +321,7 @@ class XPCShellRemote(xpcshell.XPCShellTests, object): localWrapper = tempfile.mktemp() f = open(localWrapper, "w") f.write("#!/system/bin/sh\n") - for envkey, envval in self.env.iteritems(): + for envkey, envval in self.env.items(): f.write("export %s=%s\n" % (envkey, envval)) f.writelines([ "cd $1\n", diff --git a/testing/xpcshell/runxpcshelltests.py b/testing/xpcshell/runxpcshelltests.py index 0ed7d81803..5f6a8794bd 100755 --- a/testing/xpcshell/runxpcshelltests.py +++ b/testing/xpcshell/runxpcshelltests.py @@ -267,8 +267,8 @@ class XPCShellTestThread(Thread): self.log.info("%s | current directory: %r" % (name, testdir)) # Show only those environment variables that are changed from # the ambient environment. - changedEnv = (set("%s=%s" % i for i in self.env.iteritems()) - - set("%s=%s" % i for i in os.environ.iteritems())) + changedEnv = (set("%s=%s" % i for i in self.env.items()) + - set("%s=%s" % i for i in os.environ.items())) self.log.info("%s | environment: %s" % (name, list(changedEnv))) def killTimeout(self, proc): @@ -751,7 +751,7 @@ class XPCShellTestThread(Thread): if self.failureManifest: with open(self.failureManifest, 'a') as f: f.write('[%s]\n' % self.test_object['path']) - for k, v in self.test_object.items(): + for k, v in list(self.test_object.items()): f.write('%s = %s\n' % (k, v)) else: @@ -1043,7 +1043,7 @@ class XPCShellTests(object): """ Shut down our node process, if it exists """ - for name, proc in self.nodeProc.iteritems(): + for name, proc in self.nodeProc.items(): self.log.info('Node %s server shutting down ...' % name) if proc.poll() is not None: self.log.info('Node server %s already dead %s' % (name, proc.poll())) @@ -1219,7 +1219,7 @@ class XPCShellTests(object): # an older Python that can't handle Unicode keys in kwargs. # All of the keys in question should be ASCII. fixedInfo = {} - for k, v in self.mozInfo.items(): + for k, v in list(self.mozInfo.items()): if isinstance(k, unicode): k = k.encode('ascii') fixedInfo[k] = v diff --git a/toolkit/library/dependentlibs.py b/toolkit/library/dependentlibs.py index 958fe5ef1d..5575650d9e 100644 --- a/toolkit/library/dependentlibs.py +++ b/toolkit/library/dependentlibs.py @@ -149,7 +149,7 @@ def gen_list(output, lib): deps = dependentlibs(lib, libpaths, func) deps[lib] = mozpath.join(libpaths[0], lib) - output.write('\n'.join(deps.keys()) + '\n') + output.write('\n'.join(list(deps.keys())) + '\n') return set(deps.values()) def main(): diff --git a/toolkit/mozapps/installer/find-dupes.py b/toolkit/mozapps/installer/find-dupes.py index 59bbe24468..5fc3a11536 100644 --- a/toolkit/mozapps/installer/find-dupes.py +++ b/toolkit/mozapps/installer/find-dupes.py @@ -23,7 +23,7 @@ def find_dupes(source): md5s[m][1].append(p) total = 0 num_dupes = 0 - for m, (size, paths) in md5s.iteritems(): + for m, (size, paths) in md5s.items(): if len(paths) > 1: print('Duplicates %d bytes%s:' % (size, ' (%d times)' % (len(paths) - 1) if len(paths) > 2 else '')) diff --git a/toolkit/mozapps/installer/packager.py b/toolkit/mozapps/installer/packager.py index 07e7810ce4..afd0d6fe7b 100644 --- a/toolkit/mozapps/installer/packager.py +++ b/toolkit/mozapps/installer/packager.py @@ -80,7 +80,7 @@ class ToolLauncher(object): # Work around a bug in Python 2.7.2 and lower where unicode types in # environment variables aren't handled by subprocess. - for k, v in env.items(): + for k, v in list(env.items()): if isinstance(v, unicode): env[k] = v.encode('utf-8') diff --git a/tools/check-moz-style/checkmozstyle.py b/tools/check-moz-style/checkmozstyle.py index d8261aec5a..6e45192432 100755 --- a/tools/check-moz-style/checkmozstyle.py +++ b/tools/check-moz-style/checkmozstyle.py @@ -116,7 +116,7 @@ def process_patch(patch_string, root, cwd, scm): cpplint.error("patch", 0, "patch/nodescription", 3, "Patch does not have a description.") - for filename, diff in patch.files.iteritems(): + for filename, diff in patch.files.items(): file_extension = os.path.splitext(filename)[1] if file_extension in ['.cpp', '.c', '.h']: diff --git a/tools/check-moz-style/modules/cpplint.py b/tools/check-moz-style/modules/cpplint.py index 8e522134ab..25784ea136 100644 --- a/tools/check-moz-style/modules/cpplint.py +++ b/tools/check-moz-style/modules/cpplint.py @@ -2854,7 +2854,7 @@ def check_for_include_what_you_use(filename, clean_lines, include_state, error, # include_state is modified during iteration, so we iterate over a copy of # the keys. - for header in include_state.keys(): #NOLINT + for header in list(include_state.keys()): #NOLINT (same_module, common_path) = files_belong_to_same_module(abs_filename, header) fullpath = common_path + header if same_module and update_include_state(fullpath, include_state, io): diff --git a/tools/profiler/merge-profiles.py b/tools/profiler/merge-profiles.py index c9f90e14d6..ff9dfd7c38 100755 --- a/tools/profiler/merge-profiles.py +++ b/tools/profiler/merge-profiles.py @@ -69,7 +69,7 @@ def MergeProfiles(files): symTable[newLoc] = oldLoc filesyms = fileData['symbolicationTable'] - for sym in filesyms.keys(): + for sym in list(filesyms.keys()): symTable[pidStr + sym] = filesyms[sym] # For each thread, make the time offsets line up based on the diff --git a/tools/rb/find_leakers.py b/tools/rb/find_leakers.py index 35d7b5f92b..7df6bc3531 100755 --- a/tools/rb/find_leakers.py +++ b/tools/rb/find_leakers.py @@ -15,7 +15,7 @@ import sys def print_output(allocation, obj_to_class): '''Formats and prints output.''' items = [] - for obj, count, in allocation.iteritems(): + for obj, count, in allocation.items(): # Adding items to a list, so we can sort them. items.append((obj, count)) # Sorting by count. diff --git a/xpcom/idl-parser/xpidl/xpidl.py b/xpcom/idl-parser/xpidl/xpidl.py index 198072a7a8..68040f86b7 100755 --- a/xpcom/idl-parser/xpidl/xpidl.py +++ b/xpcom/idl-parser/xpidl/xpidl.py @@ -201,7 +201,7 @@ class NameMap(object): return self._d[key] def __iter__(self): - return self._d.itervalues() + return iter(self._d.values()) def __contains__(self, key): return key in builtinMap or key in self._d @@ -422,7 +422,7 @@ class Native(object): if self.modifier is not None: raise IDLError("More than one ptr/ref modifier", aloc) self.modifier = name - elif name in self.specialtypes.keys(): + elif name in list(self.specialtypes.keys()): if self.specialtype is not None: raise IDLError("More than one special type", aloc) self.specialtype = name @@ -1053,7 +1053,7 @@ class IDLParser(object): 'NATIVEID', ] - tokens.extend(keywords.values()) + tokens.extend(list(keywords.values())) states = ( ('nativeid', 'exclusive'),