From: gregnoel Date: Sat, 27 Mar 2010 07:39:52 +0000 (+0000) Subject: http://scons.tigris.org/issues/show_bug.cgi?id=2329 X-Git-Url: http://git.tremily.us/?a=commitdiff_plain;h=704f6e2480ef60718f1aa42c266f04afc9c79580;p=scons.git scons.tigris.org/issues/show_bug.cgi?id=2329 Applied a number of idiomatic changes. Uses of the 'sort()' method were converted into calls of 'sorted()' when possible and the sorted() expression was inserted into a subsequent statement whenever that made sense. The statement 'while 1:' was changed to 'while True:'. Names from the 'types' module (e.g., 'types.FooType') were converted to the equivalent build-in type (e.g., 'foo'). Comparisons between types were changed to use 'isinstance()'. git-svn-id: http://scons.tigris.org/svn/scons/trunk@4733 fdb21ef1-2011-0410-befe-b5e4ea1792b1 --- diff --git a/QMTest/TestCmd.py b/QMTest/TestCmd.py index 163a78d8..7c8e1a50 100644 --- a/QMTest/TestCmd.py +++ b/QMTest/TestCmd.py @@ -229,7 +229,6 @@ import sys import tempfile import time import traceback -import types import UserList __all__ = [ @@ -250,7 +249,7 @@ except ImportError: __all__.append('simple_diff') def is_List(e): - return type(e) is types.ListType \ + return isinstance(e, list) \ or isinstance(e, UserList.UserList) try: @@ -259,14 +258,15 @@ except ImportError: class UserString: pass -if hasattr(types, 'UnicodeType'): +try: unicode +except NameError: def is_String(e): - return type(e) is types.StringType \ - or type(e) is types.UnicodeType \ - or isinstance(e, UserString) + return isinstance(e, str) or isinstance(e, UserString) else: def is_String(e): - return type(e) is types.StringType or isinstance(e, UserString) + return isinstance(e, str) \ + or isinstance(e, unicode) \ + or isinstance(e, UserString) tempfile.template = 'testcmd.' if os.name in ('posix', 'nt'): @@ -440,9 +440,9 @@ def match_re(lines = None, res = None): def match_re_dotall(lines = None, res = None): """ """ - if not type(lines) is type(""): + if not isinstance(lines, str): lines = "\n".join(lines) - if not type(res) is type(""): + if not isinstance(res, str): res = "\n".join(res) s = "^" + res + "$" try: @@ -997,21 +997,21 @@ class TestCmd(object): interpreter = None, arguments = None): if program: - if type(program) == type('') and not os.path.isabs(program): + if isinstance(program, str) and not os.path.isabs(program): program = os.path.join(self._cwd, program) else: program = self.program if not interpreter: interpreter = self.interpreter - if not type(program) in [type([]), type(())]: + if not type(program) in [list, tuple]: program = [program] cmd = list(program) if interpreter: - if not type(interpreter) in [type([]), type(())]: + if not type(interpreter) in [list, tuple]: interpreter = [interpreter] cmd = list(interpreter) + cmd if arguments: - if type(arguments) == type(''): + if isinstance(arguments, str): arguments = arguments.split() cmd.extend(arguments) return cmd diff --git a/QMTest/TestCommon.py b/QMTest/TestCommon.py index e9ae6a40..6b452f79 100644 --- a/QMTest/TestCommon.py +++ b/QMTest/TestCommon.py @@ -98,7 +98,6 @@ import os import os.path import stat import sys -import types import UserList from TestCmd import * @@ -172,7 +171,7 @@ else: dll_suffix = '.so' def is_List(e): - return type(e) is types.ListType \ + return isinstance(e, list) \ or isinstance(e, UserList.UserList) def is_writable(f): diff --git a/QMTest/TestSCons.py b/QMTest/TestSCons.py index 38f2c926..a1ec2278 100644 --- a/QMTest/TestSCons.py +++ b/QMTest/TestSCons.py @@ -515,9 +515,7 @@ class TestSCons(TestCommon): import glob result = [] for p in patterns: - paths = glob.glob(p) - paths.sort() - result.extend(paths) + result.extend(sorted(glob.glob(p))) return result @@ -770,7 +768,7 @@ else: self.QT_LIB_DIR = self.workpath(dir, 'lib') def Qt_create_SConstruct(self, place): - if type(place) is type([]): + if isinstance(place, list): place = test.workpath(*place) self.write(place, """\ if ARGUMENTS.get('noqtdir', 0): QTDIR=None diff --git a/QMTest/scons_tdb.py b/QMTest/scons_tdb.py index 73e84308..b5788c00 100644 --- a/QMTest/scons_tdb.py +++ b/QMTest/scons_tdb.py @@ -397,9 +397,7 @@ class AegisBatchStream(FileResultStream): self._outcomes[test_id] = exit_status def Summarize(self): self.file.write('test_result = [\n') - file_names = self._outcomes.keys() - file_names.sort() - for file_name in file_names: + for file_name in sorted(self._outcomes.keys()): exit_status = self._outcomes[file_name] file_name = file_name.replace('\\', '/') self.file.write(' { file_name = "%s";\n' % file_name) diff --git a/QMTest/unittest.py b/QMTest/unittest.py index e5a86686..476c1fc1 100644 --- a/QMTest/unittest.py +++ b/QMTest/unittest.py @@ -633,7 +633,7 @@ Examples: """ def __init__(self, module='__main__', defaultTest=None, argv=None, testRunner=None): - if type(module) == type(''): + if isinstance(module, str): self.module = __import__(module) for part in module.split('.')[1:]: self.module = getattr(self.module, part) diff --git a/SConstruct b/SConstruct index b90ae5a7..08c7683b 100644 --- a/SConstruct +++ b/SConstruct @@ -280,8 +280,7 @@ runtest.py -p option to run tests against what's been actually packaged: """) -aliases = packaging_flavors + [('doc', 'The SCons documentation.')] -aliases.sort() +aliases = sorted(packaging_flavors + [('doc', 'The SCons documentation.')]) for alias, help_text in aliases: tw = textwrap.TextWrapper( diff --git a/bench/bench.py b/bench/bench.py index e076e43a..2acc29f8 100644 --- a/bench/bench.py +++ b/bench/bench.py @@ -94,10 +94,9 @@ exec(open(args[0], 'rU').read()) try: FunctionList except NameError: - function_names = [x for x in locals().keys() if x[:4] == FunctionPrefix] - function_names.sort() + function_names = sorted([x for x in locals().keys() if x[:4] == FunctionPrefix]) l = [locals()[f] for f in function_names] - FunctionList = [f for f in l if type(f) == types.FunctionType] + FunctionList = [f for f in l if isinstance(f, types.FunctionType)] IterationList = [None] * Iterations diff --git a/bench/env.__setitem__.py b/bench/env.__setitem__.py index 61d8c1eb..36a76727 100644 --- a/bench/env.__setitem__.py +++ b/bench/env.__setitem__.py @@ -37,13 +37,11 @@ def times(num=1000000, init='', title='Results:', **statements): t = Timing(n, num, init, s) t.timeit() timings.append(t) - + print print title - l = [] - for i in timings: l.append((i.getResult(),i.name)) - l.sort() - for i in l: print " %9.3f s %s" % i + for i in sorted([(i.getResult(),i.name) for i in timings]): + print " %9.3f s %s" % i # Import the necessary local SCons.* modules used by some of our # alternative implementations below, first manipulating sys.path so diff --git a/bench/is_types.py b/bench/is_types.py index f9f76770..9cc397e5 100644 --- a/bench/is_types.py +++ b/bench/is_types.py @@ -15,7 +15,7 @@ except ImportError: # and modified slightly for use with SCons. class UserString: def __init__(self, seq): - if type(seq) == type(''): + if isinstance(seq, str): self.data = seq elif isinstance(seq, UserString): self.data = seq.data[:] @@ -60,11 +60,14 @@ except ImportError: __rmul__ = __mul__ InstanceType = types.InstanceType -DictType = types.DictType -ListType = types.ListType -StringType = types.StringType -if hasattr(types, 'UnicodeType'): - UnicodeType = types.UnicodeType +DictType = dict +ListType = list +StringType = str +try: unicode +except NameError: + UnicodeType = None +else: + UnicodeType = unicode # The original implementations, pretty straightforward checks for the @@ -72,19 +75,19 @@ if hasattr(types, 'UnicodeType'): # User* type. def original_is_Dict(e): - return type(e) is types.DictType or isinstance(e, UserDict) + return isinstance(e, dict) or isinstance(e, UserDict) def original_is_List(e): - return type(e) is types.ListType or isinstance(e, UserList) + return isinstance(e, list) or isinstance(e, UserList) -if hasattr(types, 'UnicodeType'): +if UnicodeType is not None: def original_is_String(e): - return type(e) is types.StringType \ - or type(e) is types.UnicodeType \ + return isinstance(e, str) \ + or isinstance(e, unicode) \ or isinstance(e, UserString) else: def original_is_String(e): - return type(e) is types.StringType or isinstance(e, UserString) + return isinstance(e, str) or isinstance(e, UserString) @@ -93,22 +96,22 @@ else: # type. def checkInstanceType_is_Dict(e): - return type(e) is types.DictType or \ - (type(e) is types.InstanceType and isinstance(e, UserDict)) + return isinstance(e, dict) or \ + (isinstance(e, types.InstanceType) and isinstance(e, UserDict)) def checkInstanceType_is_List(e): - return type(e) is types.ListType \ - or (type(e) is types.InstanceType and isinstance(e, UserList)) + return isinstance(e, list) \ + or (isinstance(e, types.InstanceType) and isinstance(e, UserList)) -if hasattr(types, 'UnicodeType'): +if UnicodeType is not None: def checkInstanceType_is_String(e): - return type(e) is types.StringType \ - or type(e) is types.UnicodeType \ - or (type(e) is types.InstanceType and isinstance(e, UserString)) + return isinstance(e, str) \ + or isinstance(e, unicode) \ + or (isinstance(e, types.InstanceType) and isinstance(e, UserString)) else: def checkInstanceType_is_String(e): - return type(e) is types.StringType \ - or (type(e) is types.InstanceType and isinstance(e, UserString)) + return isinstance(e, str) \ + or (isinstance(e, types.InstanceType) and isinstance(e, UserString)) @@ -117,24 +120,24 @@ else: def cache_type_e_is_Dict(e): t = type(e) - return t is types.DictType or \ + return t is dict or \ (t is types.InstanceType and isinstance(e, UserDict)) def cache_type_e_is_List(e): t = type(e) - return t is types.ListType \ + return t is list \ or (t is types.InstanceType and isinstance(e, UserList)) -if hasattr(types, 'UnicodeType'): +if UnicodeType is not None: def cache_type_e_is_String(e): t = type(e) - return t is types.StringType \ - or t is types.UnicodeType \ + return t is str \ + or t is unicode \ or (t is types.InstanceType and isinstance(e, UserString)) else: def cache_type_e_is_String(e): t = type(e) - return t is types.StringType \ + return t is str \ or (t is types.InstanceType and isinstance(e, UserString)) @@ -153,7 +156,7 @@ def global_cache_type_e_is_List(e): return t is ListType \ or (t is InstanceType and isinstance(e, UserList)) -if hasattr(types, 'UnicodeType'): +if UnicodeType is not None: def global_cache_type_e_is_String(e): t = type(e) return t is StringType \ @@ -171,18 +174,18 @@ else: # to their corresponding underlying types. instanceTypeMap = { - UserDict : types.DictType, - UserList : types.ListType, - UserString : types.StringType, + UserDict : dict, + UserList : list, + UserString : str, } -if hasattr(types, 'UnicodeType'): +if UnicodeType is not None: def myType(obj): t = type(obj) if t is types.InstanceType: t = instanceTypeMap.get(obj.__class__, t) - elif t is types.UnicodeType: - t = types.StringType + elif t is unicode: + t = str return t else: def myType(obj): @@ -192,13 +195,13 @@ else: return t def myType_is_Dict(e): - return myType(e) is types.DictType + return myType(e) is dict def myType_is_List(e): - return myType(e) is types.ListType + return myType(e) is list def myType_is_String(e): - return myType(e) is types.StringType + return myType(e) is str diff --git a/bin/Command.py b/bin/Command.py index efaa3569..28fb110a 100644 --- a/bin/Command.py +++ b/bin/Command.py @@ -44,7 +44,7 @@ class CommandRunner: return string def do_display(self, string): - if type(string) == type(()): + if isinstance(string, tuple): func = string[0] args = string[1:] s = '%s(%s)' % (func.__name__, ', '.join(map(repr, args))) @@ -59,14 +59,14 @@ class CommandRunner: pass def do_execute(self, command): - if type(command) == type(''): + if isinstance(command, str): command = self.subst(command) cmdargs = shlex.split(command) if cmdargs[0] == 'cd': command = (os.chdir,) + tuple(cmdargs[1:]) elif cmdargs[0] == 'mkdir': command = (os.mkdir,) + tuple(cmdargs[1:]) - if type(command) == type(()): + if isinstance(command, tuple): func = command[0] args = command[1:] return func(*args) diff --git a/bin/SConsDoc.py b/bin/SConsDoc.py index d164d11e..298e2521 100644 --- a/bin/SConsDoc.py +++ b/bin/SConsDoc.py @@ -354,15 +354,13 @@ class SConsDocHandler(xml.sax.handler.ContentHandler, def start_uses(self, attrs): self.begin_collecting([]) def end_uses(self): - self.current_object.uses = ''.join(self.collect).split() - self.current_object.uses.sort() + self.current_object.uses = sorted(''.join(self.collect).split()) self.end_collecting() def start_sets(self, attrs): self.begin_collecting([]) def end_sets(self): - self.current_object.sets = ''.join(self.collect).split() - self.current_object.sets.sort() + self.current_object.sets = sorted(''.join(self.collect).split()) self.end_collecting() # Stuff for the ErrorHandler portion. diff --git a/bin/import-test.py b/bin/import-test.py index fe5ea2fd..69e6cc7d 100644 --- a/bin/import-test.py +++ b/bin/import-test.py @@ -40,11 +40,8 @@ class Dir: self.path = path self.entries = {} def call_for_each_entry(self, func): - entries = self.entries - names = entries.keys() - names.sort() - for name in names: - func(name, entries[name]) + for name in sorted(self.entries.keys()): + func(name, self.entries[name]) def lookup(dirname): global Top, TopPath diff --git a/bin/objcounts.py b/bin/objcounts.py index c1f2dd56..06620126 100644 --- a/bin/objcounts.py +++ b/bin/objcounts.py @@ -86,20 +86,14 @@ def printline(c1, c2, classname): diffstr(c1[3], c2[3]) + \ ' ' + classname -keys = common.keys() -keys.sort() -for k in keys: +for k in sorted(common.keys()): c = common[k] printline(c[0], c[1], k) -keys = c1.keys() -keys.sort() -for k in keys: +for k in sorted(list(c1.keys())): printline(c1[k], ['--']*4, k) -keys = c2.keys() -keys.sort() -for k in keys: +for k in sorted(list(c2.keys())): printline(['--']*4, c2[k], k) # Local Variables: diff --git a/bin/scons-diff.py b/bin/scons-diff.py index d1e48cf5..52bd51b1 100644 --- a/bin/scons-diff.py +++ b/bin/scons-diff.py @@ -173,9 +173,7 @@ def diff_dir(left, right): u[l] = 1 for r in rlist: u[r] = 1 - clist = [ x for x in u.keys() if x[-4:] != '.pyc' ] - clist.sort() - for x in clist: + for x in sorted([ x for x in u.keys() if x[-4:] != '.pyc' ]): if x in llist: if x in rlist: do_diff(os.path.join(left, x), diff --git a/bin/scons-doc.py b/bin/scons-doc.py index f140743e..03c66fa5 100644 --- a/bin/scons-doc.py +++ b/bin/scons-doc.py @@ -241,7 +241,7 @@ def Str(target, source, env, cmd=""): class ToolSurrogate: def __init__(self, tool, variable, func, varlist): self.tool = tool - if not type(variable) is type([]): + if not isinstance(variable, list): variable = [variable] self.variable = variable self.func = func @@ -477,10 +477,7 @@ def command_edit(args, c, test, dict): def command_ls(args, c, test, dict): def ls(a): - files = os.listdir(a) - files = [x for x in files if x[0] != '.'] - files.sort() - return [' '.join(files)] + return [' '.join(sorted([x for x in os.listdir(a) if x[0] != '.']))] if args: l = [] for a in args: diff --git a/bin/scons-test.py b/bin/scons-test.py index 8d1950f1..0089e247 100644 --- a/bin/scons-test.py +++ b/bin/scons-test.py @@ -82,7 +82,7 @@ if outdir is None: def outname(n, outdir=outdir): l = [] - while 1: + while True: n, tail = os.path.split(n) if not n: break @@ -204,10 +204,7 @@ if format == '--xml': ] print " " - #keys = os.environ.keys() - keys = environ_keys - keys.sort() - for key in keys: + for key in sorted(environ_keys): value = os.environ.get(key) if value: print " " diff --git a/bin/scons-unzip.py b/bin/scons-unzip.py index c0eb8aa9..d4ec4bff 100644 --- a/bin/scons-unzip.py +++ b/bin/scons-unzip.py @@ -45,7 +45,7 @@ if outdir is None: def outname(n, outdir=outdir): l = [] - while 1: + while True: n, tail = os.path.split(n) if not n: break diff --git a/bin/time-scons.py b/bin/time-scons.py index 78d26e54..c1c8e8e8 100644 --- a/bin/time-scons.py +++ b/bin/time-scons.py @@ -81,11 +81,11 @@ class CommandRunner: def display(self, command, stdout=None, stderr=None): if not self.verbose: return - if type(command) == type(()): + if isinstance(command, tuple): func = command[0] args = command[1:] s = '%s(%s)' % (func.__name__, ', '.join(map(repr, args))) - if type(command) == type([]): + if isinstance(command, list): # TODO: quote arguments containing spaces # TODO: handle meta characters? s = ' '.join(command) @@ -102,12 +102,12 @@ class CommandRunner: """ if not self.active: return 0 - if type(command) == type(''): + if isinstance(command, str): command = self.subst(command) cmdargs = shlex.split(command) if cmdargs[0] == 'cd': command = (os.chdir,) + tuple(cmdargs[1:]) - if type(command) == type(()): + if isinstance(command, tuple): func = command[0] args = command[1:] return func(*args) diff --git a/bin/xmlagenda.py b/bin/xmlagenda.py index 3009e4c6..fb62f9a2 100755 --- a/bin/xmlagenda.py +++ b/bin/xmlagenda.py @@ -17,8 +17,7 @@ # The team members # FIXME: These names really should be external to this script -team = 'Bill Greg Steven Gary Ken Brandon Sohail Jim David'.split() -team.sort() +team = sorted('Steven Gary Greg Ken Jim David Bill Sergey Jason'.split()) # The elements to be picked out of the issue PickList = [ diff --git a/doc/user/environments.in b/doc/user/environments.in index 0c043821..afd1463c 100644 --- a/doc/user/environments.in +++ b/doc/user/environments.in @@ -672,11 +672,8 @@ environment, of directory names, suffixes, etc. env = Environment() - dict = env.Dictionary() - keys = dict.keys() - keys.sort() - for key in keys: - print "construction variable = '%s', value = '%s'" % (key, dict[key]) + for item in sorted(env.Dictionary().items()): + print "construction variable = '%s', value = '%s'" % item @@ -1559,8 +1556,7 @@ environment, of directory names, suffixes, etc. if len(sys.argv) > 1: keys = sys.argv[1:] else: - keys = os.environ.keys() - keys.sort() + keys = sorted(os.environ.keys()) for key in keys: print " " + key + "=" + os.environ[key] diff --git a/doc/user/environments.xml b/doc/user/environments.xml index 0746793b..563d6353 100644 --- a/doc/user/environments.xml +++ b/doc/user/environments.xml @@ -672,11 +672,8 @@ environment, of directory names, suffixes, etc. env = Environment() - dict = env.Dictionary() - keys = dict.keys() - keys.sort() - for key in keys: - print "construction variable = '%s', value = '%s'" % (key, dict[key]) + for item in sorted(env.Dictionary().items()): + print "construction variable = '%s', value = '%s'" % item @@ -1546,8 +1543,7 @@ environment, of directory names, suffixes, etc. if len(sys.argv) > 1: keys = sys.argv[1:] else: - keys = os.environ.keys() - keys.sort() + keys = sorted(os.environ.keys()) for key in keys: print " " + key + "=" + os.environ[key] diff --git a/doc/user/parseflags.in b/doc/user/parseflags.in index 733ee1d4..a0ea2906 100644 --- a/doc/user/parseflags.in +++ b/doc/user/parseflags.in @@ -61,9 +61,7 @@ env = Environment() d = env.ParseFlags("-I/opt/include -L/opt/lib -lfoo") - l = d.items() - l.sort() - for k,v in l: + for k,v in sorted(d.items()): if v: print k, v env.MergeFlags(d) @@ -102,9 +100,7 @@ env = Environment() d = env.ParseFlags("-whatever") - l = d.items() - l.sort() - for k,v in l: + for k,v in sorted(d.items()): if v: print k, v env.MergeFlags(d) @@ -130,9 +126,7 @@ env = Environment() d = env.ParseFlags(["-I/opt/include", ["-L/opt/lib", "-lfoo"]]) - l = d.items() - l.sort() - for k,v in l: + for k,v in sorted(d.items()): if v: print k, v env.MergeFlags(d) @@ -159,9 +153,7 @@ env = Environment() d = env.ParseFlags(["!echo -I/opt/include", "!echo -L/opt/lib", "-lfoo"]) - l = d.items() - l.sort() - for k,v in l: + for k,v in sorted(d.items()): if v: print k, v env.MergeFlags(d) diff --git a/doc/user/parseflags.xml b/doc/user/parseflags.xml index 632077e5..09533d24 100644 --- a/doc/user/parseflags.xml +++ b/doc/user/parseflags.xml @@ -60,9 +60,7 @@ env = Environment() d = env.ParseFlags("-I/opt/include -L/opt/lib -lfoo") - l = d.items() - l.sort() - for k,v in l: + for k,v in sorted(d.items()): if v: print k, v env.MergeFlags(d) @@ -106,9 +104,7 @@ env = Environment() d = env.ParseFlags("-whatever") - l = d.items() - l.sort() - for k,v in l: + for k,v in sorted(d.items()): if v: print k, v env.MergeFlags(d) @@ -132,9 +128,7 @@ env = Environment() d = env.ParseFlags(["-I/opt/include", ["-L/opt/lib", "-lfoo"]]) - l = d.items() - l.sort() - for k,v in l: + for k,v in sorted(d.items()): if v: print k, v env.MergeFlags(d) @@ -161,8 +155,6 @@ env = Environment() d = env.ParseFlags(["!echo -I/opt/include", "!echo -L/opt/lib", "-lfoo"]) - l = d.items() - l.sort() for k,v in l: if v: print k, v diff --git a/runtest.py b/runtest.py index 7fb505a3..11f87e1a 100644 --- a/runtest.py +++ b/runtest.py @@ -97,6 +97,31 @@ import time if not hasattr(os, 'WEXITSTATUS'): os.WEXITSTATUS = lambda x: x +try: + sorted +except NameError: + # Pre-2.4 Python has no sorted() function. + # + # The pre-2.4 Python list.sort() method does not support + # list.sort(key=) nor list.sort(reverse=) keyword arguments, so + # we must implement the functionality of those keyword arguments + # by hand instead of passing them to list.sort(). + def sorted(iterable, cmp=None, key=None, reverse=0): + if key is not None: + result = [(key(x), x) for x in iterable] + else: + result = iterable[:] + if cmp is None: + # Pre-2.3 Python does not support list.sort(None). + result.sort() + else: + result.sort(cmp) + if key is not None: + result = [t1 for t0,t1 in result] + if reverse: + result.reverse() + return result + cwd = os.getcwd() all = 0 @@ -619,9 +644,7 @@ if args: os.path.walk(path, find_Tests_py, tdict) elif path[:4] == 'test': os.path.walk(path, find_py, tdict) - t = tdict.keys() - t.sort() - tests.extend(t) + tests.extend(sorted(tdict.keys())) else: tests.append(path) elif testlistfile: @@ -658,8 +681,7 @@ elif all and not qmtest: elif a[-1] not in tdict: tdict[a[-1]] = Test(a[-1], spe) - tests = tdict.keys() - tests.sort() + tests = sorted(tdict.keys()) if qmtest: if baseline: diff --git a/src/engine/SCons/Action.py b/src/engine/SCons/Action.py index 35c7316d..9d497526 100644 --- a/src/engine/SCons/Action.py +++ b/src/engine/SCons/Action.py @@ -704,7 +704,7 @@ class CommandAction(_ActionAction): result = env.subst_list(self.cmd_list, 0, target, source) silent = None ignore = None - while 1: + while True: try: c = result[0][0][0] except IndexError: c = None if c == '@': silent = 1 diff --git a/src/engine/SCons/ActionTests.py b/src/engine/SCons/ActionTests.py index 12756e59..052582bd 100644 --- a/src/engine/SCons/ActionTests.py +++ b/src/engine/SCons/ActionTests.py @@ -304,7 +304,9 @@ class ActionTestCase(unittest.TestCase): # a singleton list returns the contained action test_positional_args(cmd_action, ["string"]) - if hasattr(types, 'UnicodeType'): + try: unicode + except NameError: pass + else: a2 = eval("SCons.Action.Action(u'string')") assert isinstance(a2, SCons.Action.CommandAction), a2 @@ -540,18 +542,18 @@ class _ActionActionTestCase(unittest.TestCase): env = Environment() def execfunc(target, source, env): - assert type(target) is type([]), type(target) - assert type(source) is type([]), type(source) + assert isinstance(target, list), type(target) + assert isinstance(source, list), type(source) return 7 a = SCons.Action.Action(execfunc) def firstfunc(target, source, env): - assert type(target) is type([]), type(target) - assert type(source) is type([]), type(source) + assert isinstance(target, list), type(target) + assert isinstance(source, list), type(source) return 0 def lastfunc(target, source, env): - assert type(target) is type([]), type(target) - assert type(source) is type([]), type(source) + assert isinstance(target, list), type(target) + assert isinstance(source, list), type(source) return 9 b = SCons.Action.Action([firstfunc, execfunc, lastfunc]) diff --git a/src/engine/SCons/BuilderTests.py b/src/engine/SCons/BuilderTests.py index f26aa677..e4ddaec5 100644 --- a/src/engine/SCons/BuilderTests.py +++ b/src/engine/SCons/BuilderTests.py @@ -35,7 +35,6 @@ def Func(): import os.path import re import sys -import types import StringIO import unittest import UserList @@ -306,7 +305,8 @@ class BuilderTestCase(unittest.TestCase): #be = target.get_build_env() #assert be['VAR'] == 'foo', be['VAR'] - if not hasattr(types, 'UnicodeType'): + try: unicode + except NameError: uni = str else: uni = unicode diff --git a/src/engine/SCons/Conftest.py b/src/engine/SCons/Conftest.py index 9221e2fa..04a6bc2a 100644 --- a/src/engine/SCons/Conftest.py +++ b/src/engine/SCons/Conftest.py @@ -729,7 +729,7 @@ def _Have(context, key, have, comment = None): line = "#define %s 1\n" % key_up elif have == 0: line = "/* #undef %s */\n" % key_up - elif type(have) == IntType: + elif isinstance(have, IntType): line = "#define %s %d\n" % (key_up, have) else: line = "#define %s %s\n" % (key_up, str(have)) diff --git a/src/engine/SCons/Debug.py b/src/engine/SCons/Debug.py index a6c0cb55..18e65466 100644 --- a/src/engine/SCons/Debug.py +++ b/src/engine/SCons/Debug.py @@ -55,9 +55,7 @@ tracked_classes = {} def string_to_classes(s): if s == '*': - c = tracked_classes.keys() - c.sort() - return c + return sorted(tracked_classes.keys()) else: return s.split() @@ -148,21 +146,15 @@ def caller_trace(back=0): # print a single caller and its callers, if any def _dump_one_caller(key, file, level=0): - l = [] - for c,v in caller_dicts[key].items(): - l.append((-v,c)) - l.sort() leader = ' '*level - for v,c in l: + for v,c in sorted([(-v,c) for c,v in caller_dicts[key].items()]): file.write("%s %6d %s:%d(%s)\n" % ((leader,-v) + func_shorten(c[-3:]))) if c in caller_dicts: _dump_one_caller(c, file, level+1) # print each call tree def dump_caller_counts(file=sys.stdout): - keys = caller_bases.keys() - keys.sort() - for k in keys: + for k in sorted(caller_bases.keys()): file.write("Callers of %s:%d(%s), %d calls:\n" % (func_shorten(k) + (caller_bases[k],))) _dump_one_caller(k, file) diff --git a/src/engine/SCons/Defaults.py b/src/engine/SCons/Defaults.py index 2f48d0d3..f532354d 100644 --- a/src/engine/SCons/Defaults.py +++ b/src/engine/SCons/Defaults.py @@ -42,7 +42,6 @@ import errno import shutil import stat import time -import types import sys import SCons.Action @@ -373,7 +372,7 @@ def processDefines(defs): if SCons.Util.is_List(defs): l = [] for d in defs: - if SCons.Util.is_List(d) or type(d) is types.TupleType: + if SCons.Util.is_List(d) or isinstance(d, tuple): l.append(str(d[0]) + '=' + str(d[1])) else: l.append(str(d)) @@ -385,10 +384,7 @@ def processDefines(defs): # Consequently, we have to sort the keys to ensure a # consistent order... l = [] - keys = defs.keys() - keys.sort() - for k in keys: - v = defs[k] + for k,v in sorted(defs.items()): if v is None: l.append(str(k)) else: diff --git a/src/engine/SCons/DefaultsTests.py b/src/engine/SCons/DefaultsTests.py index 8534cf8d..99cb120b 100644 --- a/src/engine/SCons/DefaultsTests.py +++ b/src/engine/SCons/DefaultsTests.py @@ -27,7 +27,6 @@ import os import os.path import StringIO import sys -import types import unittest from UserDict import UserDict diff --git a/src/engine/SCons/Environment.py b/src/engine/SCons/Environment.py index 3ebba120..267b73dc 100644 --- a/src/engine/SCons/Environment.py +++ b/src/engine/SCons/Environment.py @@ -99,7 +99,7 @@ def apply_tools(env, tools, toolpath): return # Filter out null tools from the list. for tool in [_f for _f in tools if _f]: - if SCons.Util.is_List(tool) or type(tool)==type(()): + if SCons.Util.is_List(tool) or isinstance(tool, tuple): toolname = tool[0] toolargs = tool[1] # should be a dict of kw args tool = env.Tool(toolname, **toolargs) diff --git a/src/engine/SCons/EnvironmentTests.py b/src/engine/SCons/EnvironmentTests.py index b692e96f..25404082 100644 --- a/src/engine/SCons/EnvironmentTests.py +++ b/src/engine/SCons/EnvironmentTests.py @@ -128,7 +128,7 @@ class Scanner: class CLVar(UserList.UserList): def __init__(self, seq): - if type(seq) == type(''): + if isinstance(seq, str): seq = seq.split() UserList.UserList.__init__(self, seq) def __add__(self, other): @@ -271,8 +271,9 @@ class SubstitutionTestCase(unittest.TestCase): assert isinstance(nodes[0], X) assert nodes[0].name == "Util.py UtilTests.py" - import types - if hasattr(types, 'UnicodeType'): + try: unicode + except NameError: pass + else: code = """if 1: nodes = env.arg2nodes(u"Util.py UtilTests.py", Factory) assert len(nodes) == 1, nodes diff --git a/src/engine/SCons/Job.py b/src/engine/SCons/Job.py index 5d6befe6..08e37a5f 100644 --- a/src/engine/SCons/Job.py +++ b/src/engine/SCons/Job.py @@ -189,7 +189,7 @@ class Serial: fails to execute (i.e. execute() raises an exception), then the job will stop.""" - while 1: + while True: task = self.taskmaster.next_task() if task is None: @@ -242,7 +242,7 @@ else: self.start() def run(self): - while 1: + while True: task = self.requestQueue.get() if task is None: @@ -376,7 +376,7 @@ else: jobs = 0 - while 1: + while True: # Start up as many available tasks as we're # allowed to. while jobs < self.maxjobs: @@ -404,7 +404,7 @@ else: # Let any/all completed tasks finish up before we go # back and put the next batch of tasks on the queue. - while 1: + while True: task, ok = self.tp.get() jobs = jobs - 1 diff --git a/src/engine/SCons/JobTests.py b/src/engine/SCons/JobTests.py index afa00fb0..85708ad1 100644 --- a/src/engine/SCons/JobTests.py +++ b/src/engine/SCons/JobTests.py @@ -527,8 +527,8 @@ if __name__ == "__main__": result = runner.run(suite()) if (len(result.failures) == 0 and len(result.errors) == 1 - and type(result.errors[0][0]) == SerialTestCase - and type(result.errors[0][1][0]) == NoThreadsException): + and isinstance(result.errors[0][0], SerialTestCase) + and isinstance(result.errors[0][1][0], NoThreadsException)): sys.exit(2) elif not result.wasSuccessful(): sys.exit(1) diff --git a/src/engine/SCons/Node/FS.py b/src/engine/SCons/Node/FS.py index 705e0bcd..e5b81470 100644 --- a/src/engine/SCons/Node/FS.py +++ b/src/engine/SCons/Node/FS.py @@ -1682,10 +1682,7 @@ class Dir(Base): """Return content signatures and names of all our children separated by new-lines. Ensure that the nodes are sorted.""" contents = [] - name_cmp = lambda a, b: cmp(a.name, b.name) - sorted_children = self.children()[:] - sorted_children.sort(name_cmp) - for node in sorted_children: + for node in sorted(self.children(), key=lambda t: t.name): contents.append('%s %s\n' % (node.get_csig(), node.name)) return ''.join(contents) @@ -1952,9 +1949,8 @@ class Dir(Base): """ dirname, basename = os.path.split(pathname) if not dirname: - result = self._glob1(basename, ondisk, source, strings) - result.sort(lambda a, b: cmp(str(a), str(b))) - return result + return sorted(self._glob1(basename, ondisk, source, strings), + key=lambda t: str(t)) if has_glob_magic(dirname): list = self.glob(dirname, ondisk, source, strings=False) else: diff --git a/src/engine/SCons/Node/FSTests.py b/src/engine/SCons/Node/FSTests.py index af7638d3..e68b389a 100644 --- a/src/engine/SCons/Node/FSTests.py +++ b/src/engine/SCons/Node/FSTests.py @@ -1722,8 +1722,7 @@ class DirTestCase(_tempdirTestCase): fs.Dir(os.path.join('ddd', 'd1', 'f4')) fs.Dir(os.path.join('ddd', 'd1', 'f5')) dir.scan() - kids = [x.path for x in dir.children(None)] - kids.sort() + kids = sorted([x.path for x in dir.children(None)]) assert kids == [os.path.join('ddd', 'd1'), os.path.join('ddd', 'f1'), os.path.join('ddd', 'f2'), @@ -1768,14 +1767,12 @@ class DirTestCase(_tempdirTestCase): fs.File(os.path.join('ddd', 'f1')) dir.scan() - kids = [x.path for x in dir.children()] - kids.sort() + kids = sorted([x.path for x in dir.children()]) assert kids == [os.path.join('ddd', 'f1')], kids fs.File(os.path.join('ddd', 'f2')) dir.scan() - kids = [x.path for x in dir.children()] - kids.sort() + kids = sorted([x.path for x in dir.children()]) assert kids == [os.path.join('ddd', 'f1'), os.path.join('ddd', 'f2')], kids @@ -2240,8 +2237,7 @@ class GlobTestCase(_tempdirTestCase): strings_kwargs = copy.copy(kwargs) strings_kwargs['strings'] = True for input, string_expect, node_expect in cases: - r = self.fs.Glob(input, **strings_kwargs) - r.sort() + r = sorted(self.fs.Glob(input, **strings_kwargs)) assert r == string_expect, "Glob(%s, strings=True) expected %s, got %s" % (input, string_expect, r) # Now execute all of the cases without string=True and look for @@ -2256,13 +2252,12 @@ class GlobTestCase(_tempdirTestCase): r.sort(lambda a,b: cmp(a.path, b.path)) result = [] for n in node_expect: - if type(n) == type(''): + if isinstance(n, str): n = self.fs.Entry(n) result.append(n) fmt = lambda n: "%s %s" % (repr(n), repr(str(n))) else: - r = list(map(str, r)) - r.sort() + r = sorted(map(str, r)) result = string_expect fmt = lambda n: n if r != result: diff --git a/src/engine/SCons/Node/NodeTests.py b/src/engine/SCons/Node/NodeTests.py index 07842375..6b76e9a0 100644 --- a/src/engine/SCons/Node/NodeTests.py +++ b/src/engine/SCons/Node/NodeTests.py @@ -27,7 +27,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os import re import sys -import types import unittest import UserList @@ -50,7 +49,7 @@ def _actionAppend(a1, a2): all.append(curr_a) elif isinstance(curr_a, MyListAction): all.extend(curr_a.list) - elif type(curr_a) == type([1,2]): + elif isinstance(curr_a, list): all.extend(curr_a) else: raise 'Cannot Combine Actions' diff --git a/src/engine/SCons/Node/__init__.py b/src/engine/SCons/Node/__init__.py index c25c955e..455487ec 100644 --- a/src/engine/SCons/Node/__init__.py +++ b/src/engine/SCons/Node/__init__.py @@ -136,8 +136,7 @@ class NodeInfoBase: try: field_list = self.field_list except AttributeError: - field_list = self.__dict__.keys() - field_list.sort() + field_list = sorted(self.__dict__.keys()) fields = [] for field in field_list: try: diff --git a/src/engine/SCons/SConf.py b/src/engine/SCons/SConf.py index bd67ab25..e8b6c0eb 100644 --- a/src/engine/SCons/SConf.py +++ b/src/engine/SCons/SConf.py @@ -33,7 +33,6 @@ import re import StringIO import sys import traceback -import types import SCons.Action import SCons.Builder @@ -154,9 +153,8 @@ def _stringSource( target, source, env ): return (str(target[0]) + ' <-\n |' + source[0].get_contents().replace( '\n', "\n |" ) ) -# python 2.2 introduces types.BooleanType -BooleanTypes = [types.IntType] -if hasattr(types, 'BooleanType'): BooleanTypes.append(types.BooleanType) +# python 2.2 introduces bool +BooleanTypes = [int, bool] class SConfBuildInfo(SCons.Node.FS.FileBuildInfo): """ @@ -790,7 +788,7 @@ class CheckContext: text = "yes" else: text = "no" - elif type(res) == types.StringType: + elif isinstance(res, str): text = res else: raise TypeError, "Expected string, int or bool, got " + str(type(res)) diff --git a/src/engine/SCons/SConfTests.py b/src/engine/SCons/SConfTests.py index d0da84a9..26f21f39 100644 --- a/src/engine/SCons/SConfTests.py +++ b/src/engine/SCons/SConfTests.py @@ -61,7 +61,7 @@ class SConfTestCase(unittest.TestCase): for n in sys.modules.keys(): if n.split('.')[0] == 'SCons' and n[:12] != 'SCons.compat': m = sys.modules[n] - if type(m) is ModuleType: + if isinstance(m, ModuleType): # if this is really a scons module, clear its namespace del sys.modules[n] m.__dict__.clear() diff --git a/src/engine/SCons/SConsign.py b/src/engine/SCons/SConsign.py index a87eeeb1..bd322780 100644 --- a/src/engine/SCons/SConsign.py +++ b/src/engine/SCons/SConsign.py @@ -202,7 +202,7 @@ class DB(Base): else: try: self.entries = cPickle.loads(rawentries) - if type(self.entries) is not type({}): + if not isinstance(self.entries, dict): self.entries = {} raise TypeError except KeyboardInterrupt: @@ -261,7 +261,7 @@ class Dir(Base): return self.entries = cPickle.load(fp) - if type(self.entries) is not type({}): + if not isinstance(self.entries, dict): self.entries = {} raise TypeError diff --git a/src/engine/SCons/Scanner/CTests.py b/src/engine/SCons/Scanner/CTests.py index e92af248..2869d3be 100644 --- a/src/engine/SCons/Scanner/CTests.py +++ b/src/engine/SCons/Scanner/CTests.py @@ -190,7 +190,7 @@ class DummyEnvironment(UserDict.UserDict): return [[strSubst]] def subst_path(self, path, target=None, source=None, conv=None): - if type(path) != type([]): + if not isinstance(path, list): path = [path] return list(map(self.subst, path)) diff --git a/src/engine/SCons/Scanner/Dir.py b/src/engine/SCons/Scanner/Dir.py index 6b7f05b9..3a0767af 100644 --- a/src/engine/SCons/Scanner/Dir.py +++ b/src/engine/SCons/Scanner/Dir.py @@ -101,8 +101,7 @@ def scan_in_memory(node, env, path=()): # mixed Node types (Dirs and Files, for example) has a Dir as # the first entry. return [] - entry_list = list(filter(do_not_scan, entries.keys())) - entry_list.sort() + entry_list = sorted(filter(do_not_scan, entries.keys())) return [entries[n] for n in entry_list] # Local Variables: diff --git a/src/engine/SCons/Scanner/DirTests.py b/src/engine/SCons/Scanner/DirTests.py index 0ad1cfe7..1e45e265 100644 --- a/src/engine/SCons/Scanner/DirTests.py +++ b/src/engine/SCons/Scanner/DirTests.py @@ -25,7 +25,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os.path import sys -import types import unittest import TestCmd diff --git a/src/engine/SCons/Scanner/Fortran.py b/src/engine/SCons/Scanner/Fortran.py index fd6a0148..74f44bc1 100644 --- a/src/engine/SCons/Scanner/Fortran.py +++ b/src/engine/SCons/Scanner/Fortran.py @@ -123,9 +123,7 @@ class F90Scanner(SCons.Scanner.Classic): sortkey = self.sort_key(dep) nodes.append((sortkey, n)) - nodes.sort() - nodes = [pair[1] for pair in nodes] - return nodes + return [pair[1] for pair in sorted(nodes)] def FortranScan(path_variable="FORTRANPATH"): """Return a prototype Scanner instance for scanning source files diff --git a/src/engine/SCons/Scanner/FortranTests.py b/src/engine/SCons/Scanner/FortranTests.py index 0380e87f..b75da580 100644 --- a/src/engine/SCons/Scanner/FortranTests.py +++ b/src/engine/SCons/Scanner/FortranTests.py @@ -238,7 +238,7 @@ class DummyEnvironment: return arg def subst_path(self, path, target=None, source=None, conv=None): - if type(path) != type([]): + if not isinstance(path, list): path = [path] return list(map(self.subst, path)) diff --git a/src/engine/SCons/Scanner/IDLTests.py b/src/engine/SCons/Scanner/IDLTests.py index 26b3956b..096fc9fa 100644 --- a/src/engine/SCons/Scanner/IDLTests.py +++ b/src/engine/SCons/Scanner/IDLTests.py @@ -203,7 +203,7 @@ class DummyEnvironment: return arg def subst_path(self, path, target=None, source=None, conv=None): - if type(path) != type([]): + if not isinstance(path, list): path = [path] return list(map(self.subst, path)) diff --git a/src/engine/SCons/Scanner/LaTeX.py b/src/engine/SCons/Scanner/LaTeX.py index f3085d1b..622f2a3c 100644 --- a/src/engine/SCons/Scanner/LaTeX.py +++ b/src/engine/SCons/Scanner/LaTeX.py @@ -365,10 +365,7 @@ class LaTeX(SCons.Scanner.Base): # recurse down queue.extend( self.scan(n) ) - # - nodes.sort() - nodes = [pair[1] for pair in nodes] - return nodes + return [pair[1] for pair in sorted(nodes)] # Local Variables: # tab-width:4 diff --git a/src/engine/SCons/Scanner/LaTeXTests.py b/src/engine/SCons/Scanner/LaTeXTests.py index ac978cf9..4ded0b84 100644 --- a/src/engine/SCons/Scanner/LaTeXTests.py +++ b/src/engine/SCons/Scanner/LaTeXTests.py @@ -25,7 +25,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os.path import sys -import types import unittest import UserDict @@ -85,7 +84,7 @@ class DummyEnvironment(UserDict.UserDict): return [[strSubst]] def subst_path(self, path, target=None, source=None, conv=None): - if type(path) != type([]): + if not isinstance(path, list): path = [path] return list(map(self.subst, path)) diff --git a/src/engine/SCons/Scanner/ProgTests.py b/src/engine/SCons/Scanner/ProgTests.py index ee62ca75..2b02c908 100644 --- a/src/engine/SCons/Scanner/ProgTests.py +++ b/src/engine/SCons/Scanner/ProgTests.py @@ -25,7 +25,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os.path import sys -import types import unittest import TestCmd @@ -79,7 +78,7 @@ class DummyEnvironment: return s def subst_path(self, path, target=None, source=None, conv=None): - if type(path) != type([]): + if not isinstance(path, list): path = [path] return list(map(self.subst, path)) @@ -101,8 +100,7 @@ class DummyNode: return self.name def deps_match(deps, libs): - deps=list(map(str, deps)) - deps.sort() + deps=sorted(map(str, deps)) libs.sort() return list(map(os.path.normpath, deps)) == list(map(os.path.normpath, libs)) @@ -232,7 +230,9 @@ def suite(): suite.addTest(ProgramScannerTestCase6()) suite.addTest(ProgramScannerTestCase7()) suite.addTest(ProgramScannerTestCase8()) - if hasattr(types, 'UnicodeType'): + try: unicode + except NameError: pass + else: code = """if 1: class ProgramScannerTestCase4(unittest.TestCase): def runTest(self): diff --git a/src/engine/SCons/Scanner/RCTests.py b/src/engine/SCons/Scanner/RCTests.py index a20c9199..60af3b4f 100644 --- a/src/engine/SCons/Scanner/RCTests.py +++ b/src/engine/SCons/Scanner/RCTests.py @@ -86,7 +86,7 @@ class DummyEnvironment(UserDict.UserDict): return strSubst def subst_path(self, path, target=None, source=None, conv=None): - if type(path) != type([]): + if not isinstance(path, list): path = [path] return list(map(self.subst, path)) @@ -112,10 +112,8 @@ if os.path.normcase('foo') == os.path.normcase('FOO'): my_normpath = os.path.normcase def deps_match(self, deps, headers): - scanned = list(map(my_normpath, list(map(str, deps)))) - expect = list(map(my_normpath, headers)) - scanned.sort() - expect.sort() + scanned = sorted(map(my_normpath, list(map(str, deps)))) + expect = sorted(map(my_normpath, headers)) self.failUnless(scanned == expect, "expect %s != scanned %s" % (expect, scanned)) # define some tests: diff --git a/src/engine/SCons/Scanner/ScannerTests.py b/src/engine/SCons/Scanner/ScannerTests.py index d89fb149..500ce1ae 100644 --- a/src/engine/SCons/Scanner/ScannerTests.py +++ b/src/engine/SCons/Scanner/ScannerTests.py @@ -48,7 +48,7 @@ class DummyEnvironment(UserDict.UserDict): return [self.data[strSubst[1:]]] return [[strSubst]] def subst_path(self, path, target=None, source=None, conv=None): - if type(path) != type([]): + if not isinstance(path, list): path = [path] return list(map(self.subst, path)) def get_factory(self, factory): @@ -134,7 +134,7 @@ class BaseTestCase(unittest.TestCase): self.failUnless(self.env == env, "the environment was passed incorrectly") self.failUnless(scanned_strs == deps, "the dependencies were returned incorrectly") for d in scanned: - self.failUnless(type(d) != type(""), "got a string in the dependencies") + self.failUnless(not isinstance(d, str), "got a string in the dependencies") if len(args) > 0: self.failUnless(self.arg == args[0], "the argument was passed incorrectly") diff --git a/src/engine/SCons/Scanner/__init__.py b/src/engine/SCons/Scanner/__init__.py index be08256d..3cfe4b7f 100644 --- a/src/engine/SCons/Scanner/__init__.py +++ b/src/engine/SCons/Scanner/__init__.py @@ -378,12 +378,9 @@ class Classic(Current): SCons.Warnings.warn(SCons.Warnings.DependencyWarning, "No dependency generated for file: %s (included from: %s) -- file not found" % (i, node)) else: - sortkey = self.sort_key(include) - nodes.append((sortkey, n)) + nodes.append((self.sort_key(include), n)) - nodes.sort() - nodes = [pair[1] for pair in nodes] - return nodes + return [pair[1] for pair in sorted(nodes)] class ClassicCPP(Classic): """ diff --git a/src/engine/SCons/Script/Main.py b/src/engine/SCons/Script/Main.py index 7173f1b4..55ac5982 100644 --- a/src/engine/SCons/Script/Main.py +++ b/src/engine/SCons/Script/Main.py @@ -316,11 +316,7 @@ class CleanTask(SCons.Taskmaster.AlwaysTask): display("Removed " + pathstr) elif os.path.isdir(path) and not os.path.islink(path): # delete everything in the dir - entries = os.listdir(path) - # Sort for deterministic output (os.listdir() Can - # return entries in a random order). - entries.sort() - for e in entries: + for e in sorted(os.listdir(path)): p = os.path.join(path, e) s = os.path.join(pathstr, e) if os.path.isfile(p): @@ -508,8 +504,6 @@ class CountStats(Stats): for n, c in s: stats_table[n][i] = c i = i + 1 - keys = stats_table.keys() - keys.sort() self.outfp.write("Object counts:\n") pre = [" "] post = [" %s\n"] @@ -520,7 +514,7 @@ class CountStats(Stats): labels.append(("", "Class")) self.outfp.write(fmt1 % tuple([x[0] for x in labels])) self.outfp.write(fmt1 % tuple([x[1] for x in labels])) - for k in keys: + for k in sorted(stats_table.keys()): r = stats_table[k][:l] + [k] self.outfp.write(fmt2 % tuple(r)) @@ -1228,7 +1222,7 @@ def _exec_main(parser, values): options, args = parser.parse_args(all_args, values) - if type(options.debug) == type([]) and "pdb" in options.debug: + if isinstance(options.debug, list) and "pdb" in options.debug: import pdb pdb.Pdb().runcall(_main, parser) elif options.profile_file: diff --git a/src/engine/SCons/Script/SConscript.py b/src/engine/SCons/Script/SConscript.py index 10219210..c55d2203 100644 --- a/src/engine/SCons/Script/SConscript.py +++ b/src/engine/SCons/Script/SConscript.py @@ -51,7 +51,6 @@ import os.path import re import sys import traceback -import types import UserList # The following variables used to live in this module. Some @@ -629,7 +628,7 @@ def BuildDefaultGlobals(): import SCons.Script d = SCons.Script.__dict__ def not_a_module(m, d=d, mtype=type(SCons.Script)): - return type(d[m]) != mtype + return not isinstance(d[m], mtype) for m in filter(not_a_module, dir(SCons.Script)): GlobalDict[m] = d[m] diff --git a/src/engine/SCons/Subst.py b/src/engine/SCons/Subst.py index 936348a2..9888e8db 100644 --- a/src/engine/SCons/Subst.py +++ b/src/engine/SCons/Subst.py @@ -31,7 +31,6 @@ from __future__ import generators ### KEEP FOR COMPATIBILITY FIXERS __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import re -import types import UserList import UserString @@ -399,7 +398,7 @@ def scons_subst(strSubst, env, mode=SUBST_RAW, target=None, source=None, gvars={ handles separating command lines into lists of arguments, so see that function if that's what you're looking for. """ - if type(strSubst) == types.StringType and strSubst.find('$') < 0: + if isinstance(strSubst, str) and strSubst.find('$') < 0: return strSubst class StringSubber: @@ -870,7 +869,7 @@ def scons_subst_once(strSubst, env, key): We do this with some straightforward, brute-force code here... """ - if type(strSubst) == types.StringType and strSubst.find('$') < 0: + if isinstance(strSubst, str) and strSubst.find('$') < 0: return strSubst matchlist = ['$' + key, '${' + key + '}'] diff --git a/src/engine/SCons/SubstTests.py b/src/engine/SCons/SubstTests.py index b587dfae..2eb91cae 100644 --- a/src/engine/SCons/SubstTests.py +++ b/src/engine/SCons/SubstTests.py @@ -29,7 +29,6 @@ import os import os.path import StringIO import sys -import types import unittest from UserDict import UserDict @@ -150,7 +149,7 @@ class SubstTestCase(unittest.TestCase): def _defines(defs): l = [] for d in defs: - if SCons.Util.is_List(d) or type(d) is types.TupleType: + if SCons.Util.is_List(d) or isinstance(d, tuple): l.append(str(d[0]) + '=' + str(d[1])) else: l.append(str(d)) diff --git a/src/engine/SCons/Taskmaster.py b/src/engine/SCons/Taskmaster.py index 66bcdfaf..b2c4204e 100644 --- a/src/engine/SCons/Taskmaster.py +++ b/src/engine/SCons/Taskmaster.py @@ -737,7 +737,7 @@ class Taskmaster: T = self.trace if T: T.write('\n' + self.trace_message('Looking for a node to evaluate')) - while 1: + while True: node = self.next_candidate() if node is None: if T: T.write(self.trace_message('No candidate anymore.') + '\n') @@ -952,7 +952,7 @@ class Taskmaster: T.write(self.trace_message(' removing node %s from the pending children set\n' % self.trace_node(n))) try: - while 1: + while True: try: node = to_visit.pop() except AttributeError: diff --git a/src/engine/SCons/TaskmasterTests.py b/src/engine/SCons/TaskmasterTests.py index 4a0e13a8..65d10b59 100644 --- a/src/engine/SCons/TaskmasterTests.py +++ b/src/engine/SCons/TaskmasterTests.py @@ -910,7 +910,7 @@ class TaskmasterTestCase(unittest.TestCase): assert e.errstr == "OtherError : ", e.errstr assert len(e.exc_info) == 3, e.exc_info exc_traceback = sys.exc_info()[2] - assert type(e.exc_info[2]) == type(exc_traceback), e.exc_info[2] + assert isinstance(e.exc_info[2], type(exc_traceback)), e.exc_info[2] else: raise TestFailed, "did not catch expected BuildError" diff --git a/src/engine/SCons/Tool/intelc.py b/src/engine/SCons/Tool/intelc.py index e1936952..1cc13127 100644 --- a/src/engine/SCons/Tool/intelc.py +++ b/src/engine/SCons/Tool/intelc.py @@ -243,9 +243,7 @@ def get_all_compiler_versions(): m = re.search(r'([0-9.]+)$', d) if m: versions.append(m.group(1)) - versions = uniquify(versions) # remove dups - versions.sort(vercmp) - return versions + return sorted(uniquify(versions)) # remove dups def get_intel_compiler_top(version, abi): """ diff --git a/src/engine/SCons/Tool/javac.py b/src/engine/SCons/Tool/javac.py index d080af5f..ef4bd5ba 100644 --- a/src/engine/SCons/Tool/javac.py +++ b/src/engine/SCons/Tool/javac.py @@ -74,10 +74,7 @@ def emit_java_classes(target, source, env): elif isinstance(entry, SCons.Node.FS.Dir): result = SCons.Util.OrderedDict() def visit(arg, dirname, names, dirnode=entry.rdir()): - java_files = [n for n in names if _my_normcase(n[-len(js):]) == js] - # The on-disk entries come back in arbitrary order. Sort - # them so our target and source lists are determinate. - java_files.sort() + java_files = sorted([n for n in names if _my_normcase(n[-len(js):]) == js]) mydir = dirnode.Dir(dirname) java_paths = [mydir.File(f) for f in java_files] for jp in java_paths: diff --git a/src/engine/SCons/Tool/msvs.py b/src/engine/SCons/Tool/msvs.py index 57098a80..c5e93ac6 100644 --- a/src/engine/SCons/Tool/msvs.py +++ b/src/engine/SCons/Tool/msvs.py @@ -291,8 +291,6 @@ class _DSPGenerator: self.sources[t[0]].append(self.env[t[1]]) for n in sourcenames: - # TODO(1.5): - #self.sources[n].sort(lambda a, b: cmp(a.lower(), b.lower())) self.sources[n].sort(lambda a, b: cmp(a.lower(), b.lower())) def AddConfig(self, variant, buildtarget, outdir, runfile, cmdargs, dspfile=dspfile): @@ -352,8 +350,7 @@ class _GenerateV6DSP(_DSPGenerator): def PrintHeader(self): # pick a default config - confkeys = self.configs.keys() - confkeys.sort() + confkeys = sorted(self.configs.keys()) name = self.name confkey = confkeys[0] @@ -373,8 +370,7 @@ class _GenerateV6DSP(_DSPGenerator): '# PROP Scc_LocalPath ""\n\n') first = 1 - confkeys = self.configs.keys() - confkeys.sort() + confkeys = sorted(self.configs.keys()) for kind in confkeys: outdir = self.configs[kind].outdir buildtarget = self.configs[kind].buildtarget @@ -445,8 +441,6 @@ class _GenerateV6DSP(_DSPGenerator): 'Other Files': ''} cats = categories.keys() - # TODO(1.5): - #cats.sort(lambda a, b: cmp(a.lower(), b.lower())) cats.sort(lambda a, b: cmp(a.lower(), b.lower())) for kind in cats: if not self.sources[kind]: @@ -649,8 +643,7 @@ class _GenerateV7DSP(_DSPGenerator): def PrintProject(self): self.file.write('\t\n') - confkeys = self.configs.keys() - confkeys.sort() + confkeys = sorted(self.configs.keys()) for kind in confkeys: variant = self.configs[kind].variant platform = self.configs[kind].platform @@ -704,8 +697,6 @@ class _GenerateV7DSP(_DSPGenerator): def printSources(self, hierarchy, commonprefix): sorteditems = hierarchy.items() - # TODO(1.5): - #sorteditems.sort(lambda a, b: cmp(a[0].lower(), b[0].lower())) sorteditems.sort(lambda a, b: cmp(a[0].lower(), b[0].lower())) # First folders, then files @@ -737,8 +728,6 @@ class _GenerateV7DSP(_DSPGenerator): self.file.write('\t\n') cats = categories.keys() - # TODO(1.5) - #cats.sort(lambda a, b: cmp(a.lower(), b.lower())) cats.sort(lambda a, b: cmp(a.lower(), b.lower())) cats = [k for k in cats if self.sources[k]] for kind in cats: @@ -1007,8 +996,7 @@ class _GenerateV7DSW(_DSWGenerator): else: self.file.write('\tGlobalSection(SolutionConfiguration) = preSolution\n') - confkeys = self.configs.keys() - confkeys.sort() + confkeys = sorted(self.configs.keys()) cnt = 0 for name in confkeys: variant = self.configs[name].variant diff --git a/src/engine/SCons/Tool/mwcc.py b/src/engine/SCons/Tool/mwcc.py index c720956e..8f1201a0 100644 --- a/src/engine/SCons/Tool/mwcc.py +++ b/src/engine/SCons/Tool/mwcc.py @@ -99,7 +99,7 @@ def find_versions(): product_key = SCons.Util.RegOpenKeyEx(HLM, product) i = 0 - while 1: + while True: name = product + '\\' + SCons.Util.RegEnumKey(product_key, i) name_key = SCons.Util.RegOpenKeyEx(HLM, name) diff --git a/src/engine/SCons/Util.py b/src/engine/SCons/Util.py index a373863d..f8bac89c 100644 --- a/src/engine/SCons/Util.py +++ b/src/engine/SCons/Util.py @@ -42,11 +42,14 @@ from UserString import UserString # Don't "from types import ..." these because we need to get at the # types module later to look for UnicodeType. -DictType = types.DictType +DictType = dict InstanceType = types.InstanceType -ListType = types.ListType -StringType = types.StringType -TupleType = types.TupleType +ListType = list +StringType = str +TupleType = tuple +try: unicode +except NameError: UnicodeType = None +else: UnicodeType = unicode def dictify(keys, values, result={}): for k, v in zip(keys, values): @@ -343,7 +346,7 @@ except TypeError: t = type(obj) return t is TupleType - if hasattr(types, 'UnicodeType'): + if UnicodeType is not None: def is_String(obj): t = type(obj) return t is StringType \ @@ -398,8 +401,7 @@ except TypeError: # to_String_for_signature() will use a for_signature() method if the # specified object has one. # - if hasattr(types, 'UnicodeType'): - UnicodeType = types.UnicodeType + if UnicodeType is not None: def to_String(s): if isinstance(s, UserString): t = type(s.data) @@ -595,15 +597,15 @@ def _semi_deepcopy_dict(x): # Doesn't seem like we need to, but we'll comment it just in case. copy[key] = semi_deepcopy(val) return copy -d[types.DictionaryType] = _semi_deepcopy_dict +d[dict] = _semi_deepcopy_dict def _semi_deepcopy_list(x): return list(map(semi_deepcopy, x)) -d[types.ListType] = _semi_deepcopy_list +d[list] = _semi_deepcopy_list def _semi_deepcopy_tuple(x): return tuple(map(semi_deepcopy, x)) -d[types.TupleType] = _semi_deepcopy_tuple +d[tuple] = _semi_deepcopy_tuple def _semi_deepcopy_inst(x): if hasattr(x, '__semi_deepcopy__'): @@ -1220,8 +1222,7 @@ def unique(s): # sort functions in all languages or libraries, so this approach # is more effective in Python than it may be elsewhere. try: - t = list(s) - t.sort() + t = sorted(s) except TypeError: pass # move on to the next method else: @@ -1291,7 +1292,7 @@ class LogicalLines: def readline(self): result = [] - while 1: + while True: line = self.fileobj.readline() if not line: break @@ -1304,7 +1305,7 @@ class LogicalLines: def readlines(self): result = [] - while 1: + while True: line = self.readline() if not line: break @@ -1545,7 +1546,7 @@ else: def MD5filesignature(fname, chunksize=65536): m = hashlib.md5() f = open(fname, "rb") - while 1: + while True: blck = f.read(chunksize) if not blck: break diff --git a/src/engine/SCons/UtilTests.py b/src/engine/SCons/UtilTests.py index 670fc83c..ad271278 100644 --- a/src/engine/SCons/UtilTests.py +++ b/src/engine/SCons/UtilTests.py @@ -27,7 +27,6 @@ import os import os.path import StringIO import sys -import types import unittest from UserDict import UserDict @@ -38,6 +37,10 @@ import SCons.Errors from SCons.Util import * +try: unicode +except NameError: HasUnicode = False +else: HasUnicode = True + class OutBuffer: def __init__(self): self.buffer = "" @@ -214,7 +217,7 @@ class UtilTestCase(unittest.TestCase): assert not is_Dict([]) assert not is_Dict(()) assert not is_Dict("") - if hasattr(types, 'UnicodeType'): + if HasUnicode: exec "assert not is_Dict(u'')" def test_is_List(self): @@ -231,12 +234,12 @@ class UtilTestCase(unittest.TestCase): assert not is_List(()) assert not is_List({}) assert not is_List("") - if hasattr(types, 'UnicodeType'): + if HasUnicode: exec "assert not is_List(u'')" def test_is_String(self): assert is_String("") - if hasattr(types, 'UnicodeType'): + if HasUnicode: exec "assert is_String(u'')" try: import UserString @@ -267,7 +270,7 @@ class UtilTestCase(unittest.TestCase): assert not is_Tuple([]) assert not is_Tuple({}) assert not is_Tuple("") - if hasattr(types, 'UnicodeType'): + if HasUnicode: exec "assert not is_Tuple(u'')" def test_to_String(self): @@ -289,19 +292,19 @@ class UtilTestCase(unittest.TestCase): assert to_String(s2) == s2, s2 assert to_String(s2) == 'foo', s2 - if hasattr(types, 'UnicodeType'): + if HasUnicode: s3=UserString.UserString(unicode('bar')) assert to_String(s3) == s3, s3 assert to_String(s3) == unicode('bar'), s3 - assert type(to_String(s3)) is types.UnicodeType, \ + assert isinstance(to_String(s3), unicode), \ type(to_String(s3)) except ImportError: pass - if hasattr(types, 'UnicodeType'): + if HasUnicode: s4 = unicode('baz') assert to_String(s4) == unicode('baz'), to_String(s4) - assert type(to_String(s4)) is types.UnicodeType, \ + assert isinstance(to_String(s4), unicode), \ type(to_String(s4)) def test_WhereIs(self): diff --git a/src/engine/SCons/Variables/ListVariable.py b/src/engine/SCons/Variables/ListVariable.py index 36b530a9..5980f331 100644 --- a/src/engine/SCons/Variables/ListVariable.py +++ b/src/engine/SCons/Variables/ListVariable.py @@ -63,8 +63,7 @@ import SCons.Util class _ListVariable(UserList.UserList): def __init__(self, initlist=[], allowedElems=[]): UserList.UserList.__init__(self, [_f for _f in initlist if _f]) - self.allowedElems = allowedElems[:] - self.allowedElems.sort() + self.allowedElems = sorted(allowedElems) def __cmp__(self, other): raise NotImplementedError diff --git a/src/engine/SCons/Variables/__init__.py b/src/engine/SCons/Variables/__init__.py index 27f694fe..09d4e29a 100644 --- a/src/engine/SCons/Variables/__init__.py +++ b/src/engine/SCons/Variables/__init__.py @@ -123,7 +123,7 @@ class Variables: putting it in the environment. """ - if SCons.Util.is_List(key) or type(key) == type(()): + if SCons.Util.is_List(key) or isinstance(key, tuple): self._do_add(*key) return @@ -284,8 +284,7 @@ class Variables: """ if sort: - options = self.options[:] - options.sort(lambda x,y: sort(x.key,y.key)) + options = sorted(self.options, cmp=lambda x,y: sort(x.key,y.key)) else: options = self.options diff --git a/src/engine/SCons/compat/_scons_UserString.py b/src/engine/SCons/compat/_scons_UserString.py index 785a260a..dfc2b303 100644 --- a/src/engine/SCons/compat/_scons_UserString.py +++ b/src/engine/SCons/compat/_scons_UserString.py @@ -33,17 +33,13 @@ In particular, it does not necessarily contain all of the methods found in later versions. """ -import types - -StringType = types.StringType - -if hasattr(types, 'UnicodeType'): - UnicodeType = types.UnicodeType +try: unicode +except NameError: def is_String(obj): - return type(obj) in (StringType, UnicodeType) + return type(obj) is str else: def is_String(obj): - return type(obj) is StringType + return type(obj) in (str, unicode) class UserString: def __init__(self, seq): diff --git a/src/engine/SCons/compat/_scons_optparse.py b/src/engine/SCons/compat/_scons_optparse.py index 5db4c90b..ac5b4480 100644 --- a/src/engine/SCons/compat/_scons_optparse.py +++ b/src/engine/SCons/compat/_scons_optparse.py @@ -643,8 +643,7 @@ class Option: else: setattr(self, attr, None) if attrs: - attrs = attrs.keys() - attrs.sort() + attrs = sorted(attrs.keys()) raise OptionError( "invalid keyword arguments: %s" % string.join(attrs, ", "), self) @@ -693,7 +692,7 @@ class Option: if self.choices is None: raise OptionError( "must supply a list of choices for type 'choice'", self) - elif type(self.choices) not in (types.TupleType, types.ListType): + elif type(self.choices) not in (tuple, list): raise OptionError( "choices must be a list of strings ('%s' supplied)" % string.split(str(type(self.choices)), "'")[1], self) @@ -737,12 +736,12 @@ class Option: raise OptionError( "callback not callable: %r" % self.callback, self) if (self.callback_args is not None and - type(self.callback_args) is not types.TupleType): + type(self.callback_args) is not tuple): raise OptionError( "callback_args, if supplied, must be a tuple: not %r" % self.callback_args, self) if (self.callback_kwargs is not None and - type(self.callback_kwargs) is not types.DictType): + type(self.callback_kwargs) is not dict): raise OptionError( "callback_kwargs, if supplied, must be a dict: not %r" % self.callback_kwargs, self) @@ -855,14 +854,13 @@ try: except NameError: (True, False) = (1, 0) -try: - types.UnicodeType -except AttributeError: +try: unicode +except NameError: def isbasestring(x): - return isinstance(x, types.StringType) + return isinstance(x, str) else: def isbasestring(x): - return isinstance(x, types.StringType) or isinstance(x, types.UnicodeType) + return isinstance(x, str) or isinstance(x, unicode) class Values: @@ -879,7 +877,7 @@ class Values: def __cmp__(self, other): if isinstance(other, Values): return cmp(self.__dict__, other.__dict__) - elif isinstance(other, types.DictType): + elif isinstance(other, dict): return cmp(self.__dict__, other) else: return -1 @@ -1040,7 +1038,7 @@ class OptionContainer: """add_option(Option) add_option(opt_str, ..., kwarg=val, ...) """ - if type(args[0]) is types.StringType: + if type(args[0]) is str: option = apply(self.option_class, args, kwargs) elif len(args) == 1 and not kwargs: option = args[0] @@ -1351,7 +1349,7 @@ class OptionParser (OptionContainer): def add_option_group(self, *args, **kwargs): # XXX lots of overlap with OptionContainer.add_option() - if type(args[0]) is types.StringType: + if type(args[0]) is str: group = apply(OptionGroup, (self,) + args, kwargs) elif len(args) == 1 and not kwargs: group = args[0] diff --git a/src/engine/SCons/compat/_scons_sets.py b/src/engine/SCons/compat/_scons_sets.py index 12dbeadc..713d6e99 100644 --- a/src/engine/SCons/compat/_scons_sets.py +++ b/src/engine/SCons/compat/_scons_sets.py @@ -110,9 +110,9 @@ class BaseSet(object): # __str__ is the same as __repr__ __str__ = __repr__ - def _repr(self, sorted=False): + def _repr(self, sort_them=False): elements = self._data.keys() - if sorted: + if sort_them: elements.sort() return '%s(%r)' % (self.__class__.__name__, elements) diff --git a/src/engine/SCons/compat/builtins.py b/src/engine/SCons/compat/builtins.py index 064415ec..02b94f3e 100644 --- a/src/engine/SCons/compat/builtins.py +++ b/src/engine/SCons/compat/builtins.py @@ -152,25 +152,19 @@ except NameError: # we must implement the functionality of those keyword arguments # by hand instead of passing them to list.sort(). def sorted(iterable, cmp=None, key=None, reverse=False): - if key: - decorated = [ (key(x), x) for x in iterable ] - if cmp is None: - # Pre-2.3 Python does not support list.sort(None). - decorated.sort() - else: - decorated.sort(cmp) - if reverse: - decorated.reverse() - result = [ t[1] for t in decorated ] + if key is not None: + result = [(key(x), x) for x in iterable] else: result = iterable[:] - if cmp is None: - # Pre-2.3 Python does not support list.sort(None). - result.sort() - else: - result.sort(cmp) - if reverse: - result.reverse() + if cmp is None: + # Pre-2.3 Python does not support list.sort(None). + result.sort() + else: + result.sort(cmp) + if key is not None: + result = [t1 for t0,t1 in result] + if reverse: + result.reverse() return result __builtin__.sorted = sorted diff --git a/src/engine/SCons/cpp.py b/src/engine/SCons/cpp.py index 5ccc00e1..5e159eca 100644 --- a/src/engine/SCons/cpp.py +++ b/src/engine/SCons/cpp.py @@ -133,8 +133,7 @@ CPP_to_Python_Ops_Sub = lambda m: CPP_to_Python_Ops_Dict[m.group(0)] # re module, as late as version 2.2.2, empirically matches the # "!" in "!=" first, instead of finding the longest match. # What's up with that? -l = CPP_to_Python_Ops_Dict.keys() -l.sort(lambda a, b: cmp(len(b), len(a))) +l = sorted(CPP_to_Python_Ops_Dict.keys(), cmp=lambda a, b: cmp(len(b), len(a))) # Turn the list of keys into one regular expression that will allow us # to substitute all of the operators at once. diff --git a/src/engine/SCons/dblite.py b/src/engine/SCons/dblite.py index bcb2aa00..2383f1df 100644 --- a/src/engine/SCons/dblite.py +++ b/src/engine/SCons/dblite.py @@ -5,7 +5,6 @@ import cPickle import time import shutil import os -import types import __builtin__ keep_all_files = 00000 @@ -14,13 +13,13 @@ ignore_corrupt_dbfiles = 0 def corruption_warning(filename): print "Warning: Discarding corrupt database:", filename -if hasattr(types, 'UnicodeType'): +try: unicode +except NameError: def is_string(s): - t = type(s) - return t is types.StringType or t is types.UnicodeType + return isinstance(s, str) else: def is_string(s): - return type(s) is types.StringType + return type(s) in (str, unicode) try: unicode('a') diff --git a/src/script/scons-time.py b/src/script/scons-time.py index c75bc133..04fa5730 100644 --- a/src/script/scons-time.py +++ b/src/script/scons-time.py @@ -59,6 +59,32 @@ except NameError: import __builtin__ __builtin__.True = not 0 +try: + sorted +except NameError: + # Pre-2.4 Python has no sorted() function. + # + # The pre-2.4 Python list.sort() method does not support + # list.sort(key=) nor list.sort(reverse=) keyword arguments, so + # we must implement the functionality of those keyword arguments + # by hand instead of passing them to list.sort(). + def sorted(iterable, cmp=None, key=None, reverse=False): + if key is not None: + result = [(key(x), x) for x in iterable] + else: + result = iterable[:] + if cmp is None: + # Pre-2.3 Python does not support list.sort(None). + result.sort() + else: + result.sort(cmp) + if key is not None: + result = [t1 for t0,t1 in result] + if reverse: + result.reverse() + return result + __builtin__.sorted = sorted + def make_temp_file(**kw): try: result = tempfile.mktemp(**kw) @@ -505,9 +531,7 @@ class SConsTimer: """ files = [] for a in args: - g = glob.glob(a) - g.sort() - files.extend(g) + files.extend(sorted(glob.glob(a))) if tail: files = files[-tail:] @@ -589,10 +613,7 @@ class SConsTimer: """ gp = Gnuplotter(self.title, self.key_location) - indices = results.keys() - indices.sort() - - for i in indices: + for i in sorted(results.keys()): try: t = self.run_titles[i] except IndexError: diff --git a/src/script/sconsign.py b/src/script/sconsign.py index fb3bd5e1..ac619a58 100644 --- a/src/script/sconsign.py +++ b/src/script/sconsign.py @@ -282,8 +282,7 @@ def nodeinfo_raw(name, ninfo, prefix=""): try: keys = ninfo.field_list + ['_version_id'] except AttributeError: - keys = d.keys() - keys.sort() + keys = sorted(d.keys()) l = [] for k in keys: l.append('%s: %s' % (repr(k), repr(d.get(k)))) @@ -336,9 +335,7 @@ def printentries(entries, location): print nodeinfo_string(name, entry.ninfo) printfield(name, entry.binfo) else: - names = entries.keys() - names.sort() - for name in names: + for name in sorted(entries.keys()): entry = entries[name] try: ninfo = entry.ninfo @@ -402,9 +399,7 @@ class Do_SConsignDB: else: self.printentries(dir, val) else: - keys = db.keys() - keys.sort() - for dir in keys: + for dir in sorted(db.keys()): self.printentries(dir, db[dir]) def printentries(self, dir, val): diff --git a/src/test_interrupts.py b/src/test_interrupts.py index 69e7a80f..21b0dea4 100644 --- a/src/test_interrupts.py +++ b/src/test_interrupts.py @@ -90,7 +90,7 @@ for f in files: contents = open(os.path.join(scons_lib_dir, f)).read() try_except_lines = {} lastend = 0 - while 1: + while True: match = tryexc_pat.search( contents, lastend ) if match is None: break diff --git a/src/test_pychecker.py b/src/test_pychecker.py index fb60646a..ad689658 100644 --- a/src/test_pychecker.py +++ b/src/test_pychecker.py @@ -90,10 +90,7 @@ for file in ignore: del u[file] except KeyError: pass - -files = u.keys() - -files.sort() +files = sorted(u.keys()) mismatches = [] diff --git a/test/ARGUMENTS.py b/test/ARGUMENTS.py index c028372e..801d83ad 100644 --- a/test/ARGUMENTS.py +++ b/test/ARGUMENTS.py @@ -30,9 +30,7 @@ test = TestSCons.TestSCons() test.write('SConstruct', """ foo = open('foo.out', 'wb') -keys = ARGUMENTS.keys() -keys.sort() -for k in keys: +for k in sorted(list(ARGUMENTS.keys())): foo.write(k + " = " + ARGUMENTS[k] + "\\n") foo.close() """) diff --git a/test/Builder-factories.py b/test/Builder-factories.py index fec90771..673920c8 100644 --- a/test/Builder-factories.py +++ b/test/Builder-factories.py @@ -48,9 +48,7 @@ MakeDirectory = Builder(action=mkdir, target_factory=Dir) def collect(env, source, target): out = open(str(target[0]), 'wb') dir = str(source[0]) - files = os.listdir(dir) - files.sort() - for f in files: + for f in sorted(os.listdir(dir)): f = os.path.join(dir, f) out.write(open(f, 'r').read()) out.close() diff --git a/test/Command.py b/test/Command.py index f3be46ae..74046b10 100644 --- a/test/Command.py +++ b/test/Command.py @@ -58,9 +58,7 @@ def sub(env, target, source): target = str(target[0]) source = str(source[0]) t = open(target, 'wb') - files = os.listdir(source) - files.sort() - for f in files: + for f in sorted(os.listdir(source)): t.write(open(os.path.join(source, f), 'rb').read()) t.close() return 0 diff --git a/test/Copy-Action.py b/test/Copy-Action.py index f64defea..51635c51 100644 --- a/test/Copy-Action.py +++ b/test/Copy-Action.py @@ -153,9 +153,9 @@ errors = 0 def must_be_same(f1, f2): global errors - if type(f1) is type([]): + if isinstance(f1, list): f1 = os.path.join(*f1) - if type(f2) is type([]): + if isinstance(f2, list): f2 = os.path.join(*f2) s1 = os.stat(f1) s2 = os.stat(f2) diff --git a/test/GetBuildFailures/option-k.py b/test/GetBuildFailures/option-k.py index 532c3792..53b57ff8 100644 --- a/test/GetBuildFailures/option-k.py +++ b/test/GetBuildFailures/option-k.py @@ -64,9 +64,8 @@ Command('f6', 'f6.in', r'@%(_python_)s mypass.py f5 - $TARGET $SOURCE') def print_build_failures(): from SCons.Script import GetBuildFailures - bf_list = GetBuildFailures() - bf_list.sort(lambda a,b: cmp(a.filename, b.filename)) - for bf in bf_list: + for bf in sorted(GetBuildFailures(), + cmp=lambda a,b: cmp(a.filename, b.filename)): print "%%s failed: %%s" %% (bf.node, bf.errstr) try: diff --git a/test/GetBuildFailures/parallel.py b/test/GetBuildFailures/parallel.py index 6ee5cc35..e250486a 100644 --- a/test/GetBuildFailures/parallel.py +++ b/test/GetBuildFailures/parallel.py @@ -79,9 +79,7 @@ Command('f6', 'f6.in', r'@%(_python_)s mypass.py f5 - $TARGET $SOURCE') def print_build_failures(): from SCons.Script import GetBuildFailures - bf_list = GetBuildFailures() - bf_list.sort(lambda a,b: cmp(a.filename, b.filename)) - for bf in bf_list: + for bf in sorted(GetBuildFailures(), key=lambda t: t.filename): print "%%s failed: %%s" %% (bf.node, bf.errstr) try: diff --git a/test/GetBuildFailures/serial.py b/test/GetBuildFailures/serial.py index a240d1ef..752b3486 100644 --- a/test/GetBuildFailures/serial.py +++ b/test/GetBuildFailures/serial.py @@ -89,9 +89,7 @@ Command('f15', 'f15.in', returnExcAction(SCons.Errors.InternalError("My Internal def print_build_failures(): from SCons.Script import GetBuildFailures - bf_list = GetBuildFailures() - bf_list.sort(lambda a,b: cmp(str(a.node), str(b.node))) - for bf in bf_list: + for bf in sorted(GetBuildFailures(), key=lambda t: str(t.node)): assert( isinstance(bf, SCons.Errors.BuildError) ) print "BF: %%s failed (%%s): %%s" %% (bf.node, bf.status, bf.errstr) if bf.command: diff --git a/test/Glob/Repository.py b/test/Glob/Repository.py index 5783443a..0a2e3267 100644 --- a/test/Glob/Repository.py +++ b/test/Glob/Repository.py @@ -75,9 +75,7 @@ test.write(['repository', 'src', 'SConscript'], """ Import("env") env.Build('xxx.out', Glob('x*.in')) env.Build('yyy.out', Glob('yy?.in')) -zzz_in = Glob('*/zzz.in') -zzz_in.sort(lambda a,b: cmp(a.abspath, b.abspath)) -env.Build('zzz.out', zzz_in) +env.Build('zzz.out', sorted(Glob('*/zzz.in'), key=lambda t: t.abspath)) """) test.write(['repository', 'src', 'xxx.in'], "repository/src/xxx.in\n") diff --git a/test/Glob/VariantDir.py b/test/Glob/VariantDir.py index 62226ce0..175e5b9c 100644 --- a/test/Glob/VariantDir.py +++ b/test/Glob/VariantDir.py @@ -54,9 +54,7 @@ def concatenate(target, source, env): env['BUILDERS']['Concatenate'] = Builder(action=concatenate) -f_in = Glob('f*.in') -f_in.sort(lambda a,b: cmp(a.name, b.name)) -env.Concatenate('f.out', f_in) +env.Concatenate('f.out', sorted(Glob('f*.in'), key=lambda t: t.name)) """) test.write(['src', 'f1.in'], "src/f1.in\n") diff --git a/test/Glob/basic.py b/test/Glob/basic.py index d985a735..9afbbc69 100644 --- a/test/Glob/basic.py +++ b/test/Glob/basic.py @@ -43,9 +43,7 @@ def concatenate(target, source, env): env['BUILDERS']['Concatenate'] = Builder(action=concatenate) -f_in = Glob('f*.in') -f_in.sort(lambda a,b: cmp(a.name, b.name)) -env.Concatenate('f.out', f_in) +env.Concatenate('f.out', sorted(Glob('f*.in'), key=lambda t: t.name)) """) test.write('f1.in', "f1.in\n") diff --git a/test/Glob/source.py b/test/Glob/source.py index 33baf371..afa17f56 100644 --- a/test/Glob/source.py +++ b/test/Glob/source.py @@ -59,16 +59,14 @@ SConscript('var2/SConscript') test.write(['var1', 'SConscript'], """\ Import("env") -f_in = Glob('f[45].in', source=True) -f_in.sort(lambda a,b: cmp(a.name, b.name)) -env.Concatenate('f.out', f_in) +env.Concatenate('f.out', sorted(Glob('f[45].in', source=True), + key=lambda t: t.name)) """) test.write(['var2', 'SConscript'], """\ Import("env") -f_in = Glob('f[67].in') -f_in.sort(lambda a,b: cmp(a.name, b.name)) +f_in = sorted(Glob('f[67].in'), cmp=lambda a,b: cmp(a.name, b.name)) env.Concatenate('f.out', f_in) """) diff --git a/test/Glob/strings.py b/test/Glob/strings.py index 1ef04214..3e47d103 100644 --- a/test/Glob/strings.py +++ b/test/Glob/strings.py @@ -55,9 +55,7 @@ def concatenate(target, source, env): env['BUILDERS']['Concatenate'] = Builder(action=concatenate) -f_in = Glob('f*.in', strings=True) -f_in.sort() -env.Concatenate('f.out', f_in) +env.Concatenate('f.out', sorted(Glob('f*.in', strings=True))) """) test.write(['src', 'f1.in'], "src/f1.in\n") diff --git a/test/Glob/subdir.py b/test/Glob/subdir.py index 0255ff83..6fc00f63 100644 --- a/test/Glob/subdir.py +++ b/test/Glob/subdir.py @@ -46,9 +46,7 @@ def concatenate(target, source, env): env['BUILDERS']['Concatenate'] = Builder(action=concatenate) -f_in = Glob('subdir/*.in') -f_in.sort(lambda a,b: cmp(a.name, b.name)) -env.Concatenate('f.out', f_in) +env.Concatenate('f.out', sorted(Glob('subdir/*.in'), key=lambda t: t.name)) """) test.write(['subdir', 'file.in'], "subdir/file.in\n") diff --git a/test/Glob/subst.py b/test/Glob/subst.py index abf2bb4f..e21da815 100644 --- a/test/Glob/subst.py +++ b/test/Glob/subst.py @@ -44,9 +44,7 @@ def copy(target, source, env): env['BUILDERS']['Copy'] = Builder(action=copy) -f_in = env.Glob('$PATTERN') -f_in.sort(lambda a,b: cmp(a.name, b.name)) -env.Copy('f.out', f_in) +env.Copy('f.out', sorted(env.Glob('$PATTERN'), key=lambda t: t.name)) """) test.write('f1.in', "f1.in\n") diff --git a/test/Mkdir.py b/test/Mkdir.py index 094e6ed7..dbeecb7a 100644 --- a/test/Mkdir.py +++ b/test/Mkdir.py @@ -129,9 +129,7 @@ def catdir(env, source, target): outfp = open(target, "wb") for src in source: s = str(src) - l = os.listdir(s) - l.sort() - for f in l: + for f in sorted(os.listdir(s)): f = os.path.join(s, f) if os.path.isfile(f): outfp.write(open(f, "rb").read()) diff --git a/test/Scanner/generated.py b/test/Scanner/generated.py index 8c90df45..02120435 100644 --- a/test/Scanner/generated.py +++ b/test/Scanner/generated.py @@ -301,10 +301,8 @@ import os Scanned = {} def write_out(file, dict): - keys = dict.keys() - keys.sort() f = open(file, 'wb') - for k in keys: + for k in sorted(dict.keys()): file = os.path.split(k)[1] f.write(file + ": " + str(dict[k]) + "\\n") f.close() diff --git a/test/Scanner/no-Dir-node.py b/test/Scanner/no-Dir-node.py index 9a47c018..3a918bff 100644 --- a/test/Scanner/no-Dir-node.py +++ b/test/Scanner/no-Dir-node.py @@ -81,10 +81,8 @@ sys.exit(0) test.write('SConstruct', """\ def foo(target, source, env): - children = source[0].children() - children.sort(lambda a,b: cmp(a.name, b.name)) fp = open(str(target[0]), 'wb') - for c in children: + for c in sorted(source[0].children(), key=lambda t: t.name): fp.write('%s\\n' % c) fp.close() Command('list.out', 'subdir', foo, source_scanner = DirScanner) diff --git a/test/TAR/TAR.py b/test/TAR/TAR.py index ac8d7913..5a19a98f 100644 --- a/test/TAR/TAR.py +++ b/test/TAR/TAR.py @@ -44,6 +44,8 @@ for opt, arg in opts: if opt == '-f': out = arg def process(outfile, name): if os.path.isdir(name): + ## TODO 2.5: the next three lines can be replaced by + #for entry in sorted(os.listdir(name)): list = os.listdir(name) list.sort() for entry in list: diff --git a/test/TAR/TARFLAGS.py b/test/TAR/TARFLAGS.py index f349b3a6..96d61fe7 100644 --- a/test/TAR/TARFLAGS.py +++ b/test/TAR/TARFLAGS.py @@ -46,6 +46,8 @@ for opt, arg in cmd_opts: else: opt_string = opt_string + ' ' + opt def process(outfile, name): if os.path.isdir(name): + ## TODO 2.5: the next three lines can be replaced by + #for entry in sorted(os.listdir(name)): entries = os.listdir(name) entries.sort() for entry in entries: diff --git a/test/ZIP/ZIP.py b/test/ZIP/ZIP.py index 73e78105..f9ba417a 100644 --- a/test/ZIP/ZIP.py +++ b/test/ZIP/ZIP.py @@ -49,6 +49,8 @@ import os.path import sys def process(outfile, name): if os.path.isdir(name): + ## TODO 2.5: the next three lines can be replaced by + #for entry in sorted(os.listdir(name)): list = os.listdir(name) list.sort() for entry in list: @@ -115,10 +117,9 @@ if zip: test.write('SConstruct', """\ def marker(target, source, env): open(r'%s', 'wb').write("marker\\n") -import types f1 = Environment() zipcom = f1.Dictionary('ZIPCOM') -if not type(zipcom) is types.ListType: +if not isinstance(zipcom, list): zipcom = [zipcom] f2 = Environment(ZIPCOM = [Action(marker)] + zipcom) f3 = Environment(ZIPSUFFIX = '.xyzzy') diff --git a/test/option--C.py b/test/option--C.py index 1a9a72b7..27f4950e 100644 --- a/test/option--C.py +++ b/test/option--C.py @@ -25,14 +25,13 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import os -import types import TestSCons def match_normcase(lines, matches): - if not type(lines) is types.ListType: + if not isinstance(lines, list): lines = lines.split("\n") - if not type(matches) is types.ListType: + if not isinstance(matches, list): matches = matches.split("\n") if len(lines) != len(matches): return diff --git a/test/option/help-options.py b/test/option/help-options.py index 0f4dd4d6..2b48a66f 100644 --- a/test/option/help-options.py +++ b/test/option/help-options.py @@ -60,11 +60,10 @@ lines = [x[0] == '-' and x[1:] or x for x in lines] options = [x.split()[0] for x in lines] options = [x[-1] == ',' and x[:-1] or x for x in options] lowered = [x.lower() for x in options] -sorted = lowered[:] -sorted.sort() -if lowered != sorted: +ordered = sorted(lowered) +if lowered != ordered: print "lowered =", lowered - print "sorted =", sorted + print "sorted =", ordered test.fail_test() test.pass_test() diff --git a/test/packaging/convenience-functions.py b/test/packaging/convenience-functions.py index 66374e3a..2fc6aeea 100644 --- a/test/packaging/convenience-functions.py +++ b/test/packaging/convenience-functions.py @@ -43,10 +43,8 @@ env = Environment(tools=['default', 'packaging']) prog = env.Install( 'bin/', ["f1", "f2"] ) env.File( "f3" ) -src_files = list(map(str, env.FindSourceFiles())) -oth_files = list(map(str, env.FindInstalledFiles())) -src_files.sort() -oth_files.sort() +src_files = sorted(map(str, env.FindSourceFiles())) +oth_files = sorted(map(str, env.FindInstalledFiles())) print src_files print oth_files diff --git a/timings/SCons_Bars.py b/timings/SCons_Bars.py index 820d3ce6..2b677e94 100644 --- a/timings/SCons_Bars.py +++ b/timings/SCons_Bars.py @@ -42,8 +42,7 @@ class Bars(dict): if color is None: color = self.color if revs is None: - revs = self.keys() - revs.sort() + revs = sorted(self.keys()) if labels: result = [ (r, color, None, self[r]) for r in revs ] else: