http://scons.tigris.org/issues/show_bug.cgi?id=2329
authorgregnoel <gregnoel@fdb21ef1-2011-0410-befe-b5e4ea1792b1>
Sat, 27 Mar 2010 07:39:52 +0000 (07:39 +0000)
committergregnoel <gregnoel@fdb21ef1-2011-0410-befe-b5e4ea1792b1>
Sat, 27 Mar 2010 07:39:52 +0000 (07:39 +0000)
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

102 files changed:
QMTest/TestCmd.py
QMTest/TestCommon.py
QMTest/TestSCons.py
QMTest/scons_tdb.py
QMTest/unittest.py
SConstruct
bench/bench.py
bench/env.__setitem__.py
bench/is_types.py
bin/Command.py
bin/SConsDoc.py
bin/import-test.py
bin/objcounts.py
bin/scons-diff.py
bin/scons-doc.py
bin/scons-test.py
bin/scons-unzip.py
bin/time-scons.py
bin/xmlagenda.py
doc/user/environments.in
doc/user/environments.xml
doc/user/parseflags.in
doc/user/parseflags.xml
runtest.py
src/engine/SCons/Action.py
src/engine/SCons/ActionTests.py
src/engine/SCons/BuilderTests.py
src/engine/SCons/Conftest.py
src/engine/SCons/Debug.py
src/engine/SCons/Defaults.py
src/engine/SCons/DefaultsTests.py
src/engine/SCons/Environment.py
src/engine/SCons/EnvironmentTests.py
src/engine/SCons/Job.py
src/engine/SCons/JobTests.py
src/engine/SCons/Node/FS.py
src/engine/SCons/Node/FSTests.py
src/engine/SCons/Node/NodeTests.py
src/engine/SCons/Node/__init__.py
src/engine/SCons/SConf.py
src/engine/SCons/SConfTests.py
src/engine/SCons/SConsign.py
src/engine/SCons/Scanner/CTests.py
src/engine/SCons/Scanner/Dir.py
src/engine/SCons/Scanner/DirTests.py
src/engine/SCons/Scanner/Fortran.py
src/engine/SCons/Scanner/FortranTests.py
src/engine/SCons/Scanner/IDLTests.py
src/engine/SCons/Scanner/LaTeX.py
src/engine/SCons/Scanner/LaTeXTests.py
src/engine/SCons/Scanner/ProgTests.py
src/engine/SCons/Scanner/RCTests.py
src/engine/SCons/Scanner/ScannerTests.py
src/engine/SCons/Scanner/__init__.py
src/engine/SCons/Script/Main.py
src/engine/SCons/Script/SConscript.py
src/engine/SCons/Subst.py
src/engine/SCons/SubstTests.py
src/engine/SCons/Taskmaster.py
src/engine/SCons/TaskmasterTests.py
src/engine/SCons/Tool/intelc.py
src/engine/SCons/Tool/javac.py
src/engine/SCons/Tool/msvs.py
src/engine/SCons/Tool/mwcc.py
src/engine/SCons/Util.py
src/engine/SCons/UtilTests.py
src/engine/SCons/Variables/ListVariable.py
src/engine/SCons/Variables/__init__.py
src/engine/SCons/compat/_scons_UserString.py
src/engine/SCons/compat/_scons_optparse.py
src/engine/SCons/compat/_scons_sets.py
src/engine/SCons/compat/builtins.py
src/engine/SCons/cpp.py
src/engine/SCons/dblite.py
src/script/scons-time.py
src/script/sconsign.py
src/test_interrupts.py
src/test_pychecker.py
test/ARGUMENTS.py
test/Builder-factories.py
test/Command.py
test/Copy-Action.py
test/GetBuildFailures/option-k.py
test/GetBuildFailures/parallel.py
test/GetBuildFailures/serial.py
test/Glob/Repository.py
test/Glob/VariantDir.py
test/Glob/basic.py
test/Glob/source.py
test/Glob/strings.py
test/Glob/subdir.py
test/Glob/subst.py
test/Mkdir.py
test/Scanner/generated.py
test/Scanner/no-Dir-node.py
test/TAR/TAR.py
test/TAR/TARFLAGS.py
test/ZIP/ZIP.py
test/option--C.py
test/option/help-options.py
test/packaging/convenience-functions.py
timings/SCons_Bars.py

index 163a78d8230d1778b3c6d4188b0bf284a5acd6e5..7c8e1a509c3f937f8959ae1f64e2fd21a0b9615d 100644 (file)
@@ -229,7 +229,6 @@ import sys
 import tempfile
 import time
 import traceback
 import tempfile
 import time
 import traceback
-import types
 import UserList
 
 __all__ = [
 import UserList
 
 __all__ = [
@@ -250,7 +249,7 @@ except ImportError:
     __all__.append('simple_diff')
 
 def is_List(e):
     __all__.append('simple_diff')
 
 def is_List(e):
-    return type(e) is types.ListType \
+    return isinstance(e, list) \
         or isinstance(e, UserList.UserList)
 
 try:
         or isinstance(e, UserList.UserList)
 
 try:
@@ -259,14 +258,15 @@ except ImportError:
     class UserString:
         pass
 
     class UserString:
         pass
 
-if hasattr(types, 'UnicodeType'):
+try: unicode
+except NameError:
     def is_String(e):
     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):
 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'):
 
 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):
     """
     """
 def match_re_dotall(lines = None, res = None):
     """
     """
-    if not type(lines) is type(""):
+    if not isinstance(lines, str):
         lines = "\n".join(lines)
         lines = "\n".join(lines)
-    if not type(res) is type(""):
+    if not isinstance(res, str):
         res = "\n".join(res)
     s = "^" + res + "$"
     try:
         res = "\n".join(res)
     s = "^" + res + "$"
     try:
@@ -997,21 +997,21 @@ class TestCmd(object):
                            interpreter = None,
                            arguments = None):
         if program:
                            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
                 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:
             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:
                 interpreter = [interpreter]
             cmd = list(interpreter) + cmd
         if arguments:
-            if type(arguments) == type(''):
+            if isinstance(arguments, str):
                 arguments = arguments.split()
             cmd.extend(arguments)
         return cmd
                 arguments = arguments.split()
             cmd.extend(arguments)
         return cmd
index e9ae6a404418ac55fe35ef8fb6bd2bac7cce96b0..6b452f79535e5e35c75a4105f59a1c0b56c337aa 100644 (file)
@@ -98,7 +98,6 @@ import os
 import os.path
 import stat
 import sys
 import os.path
 import stat
 import sys
-import types
 import UserList
 
 from TestCmd import *
 import UserList
 
 from TestCmd import *
@@ -172,7 +171,7 @@ else:
     dll_suffix   = '.so'
 
 def is_List(e):
     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):
         or isinstance(e, UserList.UserList)
 
 def is_writable(f):
index 38f2c926888f1fa952544a5ac058831545351d6b..a1ec227804873a99c2828405a783e1308e31ce7d 100644 (file)
@@ -515,9 +515,7 @@ class TestSCons(TestCommon):
         import glob
         result = []
         for p in patterns:
         import glob
         result = []
         for p in patterns:
-            paths = glob.glob(p)
-            paths.sort()
-            result.extend(paths)
+            result.extend(sorted(glob.glob(p)))
         return result
 
 
         return result
 
 
@@ -770,7 +768,7 @@ else:
         self.QT_LIB_DIR = self.workpath(dir, 'lib')
 
     def Qt_create_SConstruct(self, place):
         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
             place = test.workpath(*place)
         self.write(place, """\
 if ARGUMENTS.get('noqtdir', 0): QTDIR=None
index 73e843085eaeb0954185697932ff7d5e861ac168..b5788c00227d0654fe60b2fc01eb65ba1d66bea7 100644 (file)
@@ -397,9 +397,7 @@ class AegisBatchStream(FileResultStream):
         self._outcomes[test_id] = exit_status
     def Summarize(self):
         self.file.write('test_result = [\n')
         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)
             exit_status = self._outcomes[file_name]
             file_name = file_name.replace('\\', '/')
             self.file.write('    { file_name = "%s";\n' % file_name)
index e5a866860afcb00bd883becd2a5582da9667b2ae..476c1fc18335bc0a87a192f45846e35e0e7ee691 100644 (file)
@@ -633,7 +633,7 @@ Examples:
 """
     def __init__(self, module='__main__', defaultTest=None,
                  argv=None, testRunner=None):
 """
     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)
             self.module = __import__(module)
             for part in module.split('.')[1:]:
                 self.module = getattr(self.module, part)
index b90ae5a7207d010834e067bbee017bfac8a23309..08c7683b644b640da639a957281f57f2cc18866d 100644 (file)
@@ -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(
 
 for alias, help_text in aliases:
     tw = textwrap.TextWrapper(
index e076e43a1d06b37b56a844baacf2dad440daf753..2acc29f8f6c960cd4f5ae41f397560bd4abc5819 100644 (file)
@@ -94,10 +94,9 @@ exec(open(args[0], 'rU').read())
 try:
     FunctionList
 except NameError:
 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]
     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
 
 
 IterationList = [None] * Iterations
 
index 61d8c1eb4fffd11292f49382fb5ebcfabeec8e8e..36a76727f2076f24bc489ed6e87b71b3a6b8302f 100644 (file)
@@ -37,13 +37,11 @@ def times(num=1000000, init='', title='Results:', **statements):
         t = Timing(n, num, init, s)
         t.timeit()
         timings.append(t)
         t = Timing(n, num, init, s)
         t.timeit()
         timings.append(t)
-    
+
     print
     print title
     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
 
 # Import the necessary local SCons.* modules used by some of our
 # alternative implementations below, first manipulating sys.path so
index f9f76770c271f840642be2550057c48b388589ca..9cc397e5d7c4d551d7a2324a44f9ce33f71424ee 100644 (file)
@@ -15,7 +15,7 @@ except ImportError:
     # and modified slightly for use with SCons.
     class UserString:
         def __init__(self, seq):
     # 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[:]
                 self.data = seq
             elif isinstance(seq, UserString):
                 self.data = seq.data[:]
@@ -60,11 +60,14 @@ except ImportError:
         __rmul__ = __mul__
 
 InstanceType = types.InstanceType
         __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
 
 
 # The original implementations, pretty straightforward checks for the
@@ -72,19 +75,19 @@ if hasattr(types, 'UnicodeType'):
 # User* type.
 
 def original_is_Dict(e):
 # 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):
 
 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):
     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):
             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):
 # 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):
 
 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):
     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):
 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)
 
 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)
            (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))
 
         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)
     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)
             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))
 
 
             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))
 
     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 \
     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 = {
 # 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)
     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):
         return t
 else:
     def myType(obj):
@@ -192,13 +195,13 @@ else:
         return t
 
 def myType_is_Dict(e):
         return t
 
 def myType_is_Dict(e):
-    return myType(e) is types.DictType
+    return myType(e) is dict
 
 def myType_is_List(e):
 
 def myType_is_List(e):
-    return myType(e) is types.ListType
+    return myType(e) is list
 
 def myType_is_String(e):
 
 def myType_is_String(e):
-    return myType(e) is types.StringType
+    return myType(e) is str
 
 
 
 
 
 
index efaa3569ad9d45c1e4dc176b1d4612154f532d93..28fb110a5a6580e75f465ef51b3700531814f822 100644 (file)
@@ -44,7 +44,7 @@ class CommandRunner:
         return string
 
     def do_display(self, string):
         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)))
             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):
         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:])
             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)
             func = command[0]
             args = command[1:]
             return func(*args)
index d164d11e312a2ce3547897767ae79f4f979a9b51..298e2521eb90202f30e82f236c3163942fcc2731 100644 (file)
@@ -354,15 +354,13 @@ class SConsDocHandler(xml.sax.handler.ContentHandler,
     def start_uses(self, attrs):
         self.begin_collecting([])
     def end_uses(self):
     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.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.
         self.end_collecting()
 
     # Stuff for the ErrorHandler portion.
index fe5ea2fd3d51728c072d9be5fba42774a4bf3fd1..69e6cc7de6d8fca3349eff60166418dee0be8358 100644 (file)
@@ -40,11 +40,8 @@ class Dir:
         self.path = path
         self.entries = {}
     def call_for_each_entry(self, func):
         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
 
 def lookup(dirname):
     global Top, TopPath
index c1f2dd563bf328e5b50e07e2effccf678de6fda6..06620126a0fbfe8640fdec9e27ce6cc93de3aedc 100644 (file)
@@ -86,20 +86,14 @@ def printline(c1, c2, classname):
           diffstr(c1[3], c2[3]) + \
           ' ' + 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)
 
     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)
 
     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:
     printline(['--']*4, c2[k], k)
 
 # Local Variables:
index d1e48cf590ac86ba8c1b19e189fff457872e08e9..52bd51b182331c4a9ca10a86fba42299b2780dd6 100644 (file)
@@ -173,9 +173,7 @@ def diff_dir(left, right):
         u[l] = 1
     for r in rlist:
         u[r] = 1
         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),
         if x in llist:
             if x in rlist:
                 do_diff(os.path.join(left, x),
index f140743e38ee75b1147a785697a0c481e8f8e41a..03c66fa571f75a8fd50dd92b31dd41159e983669 100644 (file)
@@ -241,7 +241,7 @@ def Str(target, source, env, cmd=""):
 class ToolSurrogate:
     def __init__(self, tool, variable, func, varlist):
         self.tool = tool
 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
             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):
 
 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:
     if args:
         l = []
         for a in args:
index 8d1950f181bb2997d82938e9f01a5fd6266d8b23..0089e247ecee828c4bb9df5bc94c9d7788835f41 100644 (file)
@@ -82,7 +82,7 @@ if outdir is None:
 
 def outname(n, outdir=outdir):
     l = []
 
 def outname(n, outdir=outdir):
     l = []
-    while 1:
+    while True:
         n, tail = os.path.split(n)
         if not n:
             break
         n, tail = os.path.split(n)
         if not n:
             break
@@ -204,10 +204,7 @@ if format == '--xml':
     ]
 
     print "  <environment>"
     ]
 
     print "  <environment>"
-    #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 "    <variable>"
         value = os.environ.get(key)
         if value:
             print "    <variable>"
index c0eb8aa96efbc9d0cac5704be2f3f3c691621d7d..d4ec4bffbef9da7ed636e08465a21d8172cc902f 100644 (file)
@@ -45,7 +45,7 @@ if outdir is None:
 
 def outname(n, outdir=outdir):
     l = []
 
 def outname(n, outdir=outdir):
     l = []
-    while 1:
+    while True:
         n, tail = os.path.split(n)
         if not n:
             break
         n, tail = os.path.split(n)
         if not n:
             break
index 78d26e542fea95852c66fb206a31ebacbbc04437..c1c8e8e8fbbf7c68fa5b1bc570da0b2032563956 100644 (file)
@@ -81,11 +81,11 @@ class CommandRunner:
     def display(self, command, stdout=None, stderr=None):
         if not self.verbose:
             return
     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)))
             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)
             # 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 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:])
             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)
             func = command[0]
             args = command[1:]
             return func(*args)
index 3009e4c643def957a8e16ce4dfa21eed858dddcc..fb62f9a21c747293a2afb8057ab7defaf809693e 100755 (executable)
@@ -17,8 +17,7 @@
 
 # The team members
 # FIXME: These names really should be external to this script
 
 # 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 = [
 
 # The elements to be picked out of the issue
 PickList = [
index 0c0438214963a7b0eb66d353cec456e8ad962b15..afd1463c2e9f22dea43b1696c87eafcf76b5b931 100644 (file)
@@ -672,11 +672,8 @@ environment, of directory names, suffixes, etc.
 
       <sconstruct>
          env = Environment()
 
       <sconstruct>
          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
       </sconstruct>
 
     </section>
       </sconstruct>
 
     </section>
@@ -1559,8 +1556,7 @@ environment, of directory names, suffixes, etc.
       if len(sys.argv) > 1:
           keys = sys.argv[1:]
       else:
       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]
       </file>
       for key in keys:
           print "    " + key + "=" + os.environ[key]
       </file>
index 0746793bbdc2f7749a6d3873791d7dc4df3f18e7..563d63531599e13595f98c09091b962fa36108f0 100644 (file)
@@ -672,11 +672,8 @@ environment, of directory names, suffixes, etc.
 
       <programlisting>
          env = Environment()
 
       <programlisting>
          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
       </programlisting>
 
     </section>
       </programlisting>
 
     </section>
@@ -1546,8 +1543,7 @@ environment, of directory names, suffixes, etc.
       if len(sys.argv) > 1:
           keys = sys.argv[1:]
       else:
       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]
       </file>
       for key in keys:
           print "    " + key + "=" + os.environ[key]
       </file>
index 733ee1d428d27f1bec67695ec86dd7a3bd9e6a64..a0ea2906b50a60f4166bb61bcfbb939882490773 100644 (file)
@@ -61,9 +61,7 @@
    <file name="SConstruct" printme="1">
     env = Environment()
     d = env.ParseFlags("-I/opt/include -L/opt/lib -lfoo")
    <file name="SConstruct" printme="1">
     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)
         if v:
             print k, v
     env.MergeFlags(d)
    <file name="SConstruct" printme="1">
     env = Environment()
     d = env.ParseFlags("-whatever")
    <file name="SConstruct" printme="1">
     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)
         if v:
             print k, v
     env.MergeFlags(d)
    <file name="SConstruct" printme="1">
     env = Environment()
     d = env.ParseFlags(["-I/opt/include", ["-L/opt/lib", "-lfoo"]])
    <file name="SConstruct" printme="1">
     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)
         if v:
             print k, v
     env.MergeFlags(d)
    <file name="SConstruct" printme="1">
     env = Environment()
     d = env.ParseFlags(["!echo -I/opt/include", "!echo -L/opt/lib", "-lfoo"])
    <file name="SConstruct" printme="1">
     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)
         if v:
             print k, v
     env.MergeFlags(d)
index 632077e5f141e4febd9621a23291557219b88c44..09533d24cf16371262ae735c0ea4fc65a795c51c 100644 (file)
@@ -60,9 +60,7 @@
  <programlisting>
     env = Environment()
     d = env.ParseFlags("-I/opt/include -L/opt/lib -lfoo")
  <programlisting>
     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)
         if v:
             print k, v
     env.MergeFlags(d)
  <programlisting>
     env = Environment()
     d = env.ParseFlags("-whatever")
  <programlisting>
     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)
         if v:
             print k, v
     env.MergeFlags(d)
  <programlisting>
     env = Environment()
     d = env.ParseFlags(["-I/opt/include", ["-L/opt/lib", "-lfoo"]])
  <programlisting>
     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)
         if v:
             print k, v
     env.MergeFlags(d)
  <programlisting>
     env = Environment()
     d = env.ParseFlags(["!echo -I/opt/include", "!echo -L/opt/lib", "-lfoo"])
  <programlisting>
     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
     for k,v in l:
         if v:
             print k, v
index 7fb505a3872aab9594977417074e2e66ab1c6524..11f87e1af2ad89779a80d20a282de814b6246040 100644 (file)
@@ -97,6 +97,31 @@ import time
 if not hasattr(os, 'WEXITSTATUS'):
     os.WEXITSTATUS = lambda x: x
 
 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
 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)
                         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:
                 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)
 
                 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:
 
 if qmtest:
     if baseline:
index 35c7316d25b2a353f588872e31b3a6b05bb96296..9d497526856b40e17c2a2434697c0c1f362ea6c6 100644 (file)
@@ -704,7 +704,7 @@ class CommandAction(_ActionAction):
             result = env.subst_list(self.cmd_list, 0, target, source)
         silent = None
         ignore = None
             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
             try: c = result[0][0][0]
             except IndexError: c = None
             if c == '@': silent = 1
index 12756e59c7c502714d58056ba67360d4d45b8964..052582bd300b009be562383789ee5e483a77f73d 100644 (file)
@@ -304,7 +304,9 @@ class ActionTestCase(unittest.TestCase):
         # a singleton list returns the contained action
         test_positional_args(cmd_action, ["string"])
 
         # 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
 
             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):
             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):
                 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):
                 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])
             
                 return 9
             b = SCons.Action.Action([firstfunc, execfunc, lastfunc])
             
index f26aa6773f467b153be8f7b260ece6ec59a57e55..e4ddaec5d89783498446a395d0ec5cc917ae1044 100644 (file)
@@ -35,7 +35,6 @@ def Func():
 import os.path
 import re
 import sys
 import os.path
 import re
 import sys
-import types
 import StringIO
 import unittest
 import UserList
 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']
 
         #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
             uni = str
         else:
             uni = unicode
index 9221e2faf49f41fe0bf6911f14e000fb54b78f60..04a6bc2aa9188b2ec93fc4eddec563693b211279 100644 (file)
@@ -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
         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))
         line = "#define %s %d\n" % (key_up, have)
     else:
         line = "#define %s %s\n" % (key_up, str(have))
index a6c0cb55dd589400d0b417ed862ece822712ce18..18e6546639128938b06836d77636b7c80077403c 100644 (file)
@@ -55,9 +55,7 @@ tracked_classes = {}
 
 def string_to_classes(s):
     if s == '*':
 
 def string_to_classes(s):
     if s == '*':
-        c = tracked_classes.keys()
-        c.sort()
-        return c
+        return sorted(tracked_classes.keys())
     else:
         return s.split()
 
     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):
 
 # 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
     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):
         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)
         file.write("Callers of %s:%d(%s), %d calls:\n"
                     % (func_shorten(k) + (caller_bases[k],)))
         _dump_one_caller(k, file)
index 2f48d0d3beb42747f7e47eeb8852789b4c48ba51..f532354dcf98670a17a8ae58dd26043e59d21725 100644 (file)
@@ -42,7 +42,6 @@ import errno
 import shutil
 import stat
 import time
 import shutil
 import stat
 import time
-import types
 import sys
 
 import SCons.Action
 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(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))
                 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 = []
         # 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:
             if v is None:
                 l.append(str(k))
             else:
index 8534cf8d5c95d39990d5f6c140c832d299b5c439..99cb120b5ff2dbf12d40d8322e8fa130612e9767 100644 (file)
@@ -27,7 +27,6 @@ import os
 import os.path
 import StringIO
 import sys
 import os.path
 import StringIO
 import sys
-import types
 import unittest
 
 from UserDict import UserDict
 import unittest
 
 from UserDict import UserDict
index 3ebba120b512280bd6ce599b10b92e1f5c8cccb4..267b73dcf0a4237e8b1cabd1ac30ea47358cf6bd 100644 (file)
@@ -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]:
         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)
             toolname = tool[0]
             toolargs = tool[1] # should be a dict of kw args
             tool = env.Tool(toolname, **toolargs)
index b692e96ff41090e99b6ee7d1bf335bf7c2503a37..25404082a0b6311cf122018ae845e419ca39952e 100644 (file)
@@ -128,7 +128,7 @@ class Scanner:
 
 class CLVar(UserList.UserList):
     def __init__(self, seq):
 
 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):
             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"
 
         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
             code = """if 1:
                 nodes = env.arg2nodes(u"Util.py UtilTests.py", Factory)
                 assert len(nodes) == 1, nodes
index 5d6befe6592fe469b616e23086f34e18cecbf423..08e37a5f6150f60403759d2c94a4eeabf3fef8dc 100644 (file)
@@ -189,7 +189,7 @@ class Serial:
         fails to execute (i.e. execute() raises an exception), then the job will
         stop."""
         
         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:
             task = self.taskmaster.next_task()
 
             if task is None:
@@ -242,7 +242,7 @@ else:
             self.start()
 
         def run(self):
             self.start()
 
         def run(self):
-            while 1:
+            while True:
                 task = self.requestQueue.get()
 
                 if task is None:
                 task = self.requestQueue.get()
 
                 if task is None:
@@ -376,7 +376,7 @@ else:
 
             jobs = 0
             
 
             jobs = 0
             
-            while 1:
+            while True:
                 # Start up as many available tasks as we're
                 # allowed to.
                 while jobs < self.maxjobs:
                 # 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.
 
                 # 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
 
                     task, ok = self.tp.get()
                     jobs = jobs - 1
 
index afa00fb01575ccd2990e8320098f2f8454a0d848..85708ad1f701ce74e46c5c75745bc8e9c9c650f9 100644 (file)
@@ -527,8 +527,8 @@ if __name__ == "__main__":
     result = runner.run(suite())
     if (len(result.failures) == 0
         and len(result.errors) == 1
     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)
         sys.exit(2)
     elif not result.wasSuccessful():
         sys.exit(1)
index 705e0bcdf314c68dd95e937ee159242095669af3..e5b81470d397e691199bd07c0d4c7620b0a122e6 100644 (file)
@@ -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 = []
         """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)
 
             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:
         """
         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:
         if has_glob_magic(dirname):
             list = self.glob(dirname, ondisk, source, strings=False)
         else:
index af7638d36905b48f234dfceef1cf927cab07e6d6..e68b389ab23658a663ecf56a080c3ed660e3c612 100644 (file)
@@ -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()
         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'),
         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()
 
         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()
         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
 
         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:
         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
             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:
                 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:
                         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:
                 result = string_expect
                 fmt = lambda n: n
             if r != result:
index 07842375ce7cf0e8ebd6450ebb0fb885d9fd8193..6b76e9a00543c61711b769aecf86a2d73a5af4e9 100644 (file)
@@ -27,7 +27,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
 import os
 import re
 import sys
 import os
 import re
 import sys
-import types
 import unittest
 import UserList
 
 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)
             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'
             all.extend(curr_a)
         else:
             raise 'Cannot Combine Actions'
index c25c955eb248d92086e5684317598c2b58b9b82e..455487ec7423cf9c9c2bcdd5edb2e84e0c0bfb2e 100644 (file)
@@ -136,8 +136,7 @@ class NodeInfoBase:
             try:
                 field_list = self.field_list
             except AttributeError:
             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:
         fields = []
         for field in field_list:
             try:
index bd67ab255c5048b1cbbd07214653f71d1d88322b..e8b6c0eb3b97d681538d4c973fffbb84406683c0 100644 (file)
@@ -33,7 +33,6 @@ import re
 import StringIO
 import sys
 import traceback
 import StringIO
 import sys
 import traceback
-import types
 
 import SCons.Action
 import SCons.Builder
 
 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  |" ) )
 
     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):
     """
 
 class SConfBuildInfo(SCons.Node.FS.FileBuildInfo):
     """
@@ -790,7 +788,7 @@ class CheckContext:
                 text = "yes"
             else:
                 text = "no"
                 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))
             text = res
         else:
             raise TypeError, "Expected string, int or bool, got " + str(type(res))
index d0da84a95efa7d0c6480b7caf463f42d94ee45f8..26f21f398b00b5e5ba82a01fb6ff12cdfa53547a 100644 (file)
@@ -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]
         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()
                     # if this is really a scons module, clear its namespace
                     del sys.modules[n]
                     m.__dict__.clear()
index a87eeeb14479c7e2acc7a72f78b0d24aee600315..bd322780468bf0d37e6736599e8e898094176efb 100644 (file)
@@ -202,7 +202,7 @@ class DB(Base):
         else:
             try:
                 self.entries = cPickle.loads(rawentries)
         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:
                     self.entries = {}
                     raise TypeError
             except KeyboardInterrupt:
@@ -261,7 +261,7 @@ class Dir(Base):
             return
 
         self.entries = cPickle.load(fp)
             return
 
         self.entries = cPickle.load(fp)
-        if type(self.entries) is not type({}):
+        if not isinstance(self.entries, dict):
             self.entries = {}
             raise TypeError
 
             self.entries = {}
             raise TypeError
 
index e92af2489cbedd5c66a99fcaee88819d0a1cced0..2869d3be145f4471d8f3897a845ce7d3fd36b241 100644 (file)
@@ -190,7 +190,7 @@ class DummyEnvironment(UserDict.UserDict):
         return [[strSubst]]
 
     def subst_path(self, path, target=None, source=None, conv=None):
         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))
 
             path = [path]
         return list(map(self.subst, path))
 
index 6b7f05b9d957b4f127fcaa13fe9ae5600fc2793f..3a0767af935f1119a79e49fe5f8e5028cc096daf 100644 (file)
@@ -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 []
         # 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:
     return [entries[n] for n in entry_list]
 
 # Local Variables:
index 0ad1cfe7e5d27f62ef57be60da840064d148cfa7..1e45e2652f70b8d6a53165bc2d844ee9faeb6a79 100644 (file)
@@ -25,7 +25,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
 
 import os.path
 import sys
 
 import os.path
 import sys
-import types
 import unittest
 
 import TestCmd
 import unittest
 
 import TestCmd
index fd6a0148a7c7e942e25118271d7365f30b0ad3bb..74f44bc1e89518126a56ab65f1c2544ab71c5850 100644 (file)
@@ -123,9 +123,7 @@ class F90Scanner(SCons.Scanner.Classic):
                 sortkey = self.sort_key(dep)
                 nodes.append((sortkey, n))
 
                 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
 
 def FortranScan(path_variable="FORTRANPATH"):
     """Return a prototype Scanner instance for scanning source files
index 0380e87fdb7ae4fd8a975f7be99aae0b176fc031..b75da5809211b9508d6e25cabd2a1b7d17a18285 100644 (file)
@@ -238,7 +238,7 @@ class DummyEnvironment:
         return arg
 
     def subst_path(self, path, target=None, source=None, conv=None):
         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))
 
             path = [path]
         return list(map(self.subst, path))
 
index 26b3956b3d695785d30408428bb88533ed7250af..096fc9fac9f39c7f6f060b68dd50690844efc205 100644 (file)
@@ -203,7 +203,7 @@ class DummyEnvironment:
         return arg
 
     def subst_path(self, path, target=None, source=None, conv=None):
         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))
 
             path = [path]
         return list(map(self.subst, path))
 
index f3085d1bfa3d1a3f29b0761d3722778281dcf6eb..622f2a3c53ce5a11dc769571fdcbc3ccf67f4368 100644 (file)
@@ -365,10 +365,7 @@ class LaTeX(SCons.Scanner.Base):
                 # recurse down 
                 queue.extend( self.scan(n) )
 
                 # 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
 
 # Local Variables:
 # tab-width:4
index ac978cf9637fbab7d7caeb8a214bd378921acb74..4ded0b8444a68511715ce443fd56879200cf2d41 100644 (file)
@@ -25,7 +25,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
 
 import os.path
 import sys
 
 import os.path
 import sys
-import types
 import unittest
 import UserDict
 
 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):
         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))
 
             path = [path]
         return list(map(self.subst, path))
 
index ee62ca750a82f851b41b22c9ece95e7b25df786d..2b02c9082e75836d147dd3659f4a7e16a2434d7e 100644 (file)
@@ -25,7 +25,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
 
 import os.path
 import sys
 
 import os.path
 import sys
-import types
 import unittest
 
 import TestCmd
 import unittest
 
 import TestCmd
@@ -79,7 +78,7 @@ class DummyEnvironment:
         return s
 
     def subst_path(self, path, target=None, source=None, conv=None):
         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))
 
             path = [path]
         return list(map(self.subst, path))
 
@@ -101,8 +100,7 @@ class DummyNode:
         return self.name
     
 def deps_match(deps, libs):
         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))
 
     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())
     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):
         code = """if 1:
             class ProgramScannerTestCase4(unittest.TestCase):
                 def runTest(self):
index a20c9199f0d0c4374e8c46f3b95889ae2052a4b5..60af3b4fa37a8583be12f153724ade1a02b5f480 100644 (file)
@@ -86,7 +86,7 @@ class DummyEnvironment(UserDict.UserDict):
         return strSubst
 
     def subst_path(self, path, target=None, source=None, conv=None):
         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))
 
             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):
     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:
     self.failUnless(scanned == expect, "expect %s != scanned %s" % (expect, scanned))
 
 # define some tests:
index d89fb149dbd1601bd6337916d0390268be3ece99..500ce1ae338e4854a09cbca450968afc5a8a9fa2 100644 (file)
@@ -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):
             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):
             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(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")
 
         if len(args) > 0:
             self.failUnless(self.arg == args[0], "the argument was passed incorrectly")
index be08256db137dc429088f4ba7f74e3f0ca099cf1..3cfe4b7fe0ed2779a3d363b441a51b6170f868f8 100644 (file)
@@ -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:
                 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):
     """
 
 class ClassicCPP(Classic):
     """
index 7173f1b4fb682d962d65ff49ad7f8ff13aa7429d..55ac5982c3619e4ff8c81b2054ffe401ec11dcaa 100644 (file)
@@ -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
                     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):
                         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
             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"]
         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]))
         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))
 
             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)
 
 
     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:
         import pdb
         pdb.Pdb().runcall(_main, parser)
     elif options.profile_file:
index 10219210789995c6fac9b22ffe8f12ee3ed6d837..c55d22038b3ebb3c514c5b4d6ee5c0884406b9a5 100644 (file)
@@ -51,7 +51,6 @@ import os.path
 import re
 import sys
 import traceback
 import re
 import sys
 import traceback
-import types
 import UserList
 
 # The following variables used to live in this module.  Some
 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)):
         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]
 
         for m in filter(not_a_module, dir(SCons.Script)):
              GlobalDict[m] = d[m]
 
index 936348a2062a51d04e7ea727276876d698628643..9888e8db782d9c5c57e4e962d856fa7a4927072a 100644 (file)
@@ -31,7 +31,6 @@ from __future__ import generators  ### KEEP FOR COMPATIBILITY FIXERS
 __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
 
 import re
 __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
 
 import re
-import types
 import UserList
 import UserString
 
 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.
     """
     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:
         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...
     """
 
     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 + '}']
         return strSubst
 
     matchlist = ['$' + key, '${' + key + '}']
index b587dfae029902d8a92902578151703c5feec2ac..2eb91cae0ab5dda7144c82c74cdb5c8bdbca2e47 100644 (file)
@@ -29,7 +29,6 @@ import os
 import os.path
 import StringIO
 import sys
 import os.path
 import StringIO
 import sys
-import types
 import unittest
 
 from UserDict import UserDict
 import unittest
 
 from UserDict import UserDict
@@ -150,7 +149,7 @@ class SubstTestCase(unittest.TestCase):
     def _defines(defs):
         l = []
         for d in defs:
     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))
                 l.append(str(d[0]) + '=' + str(d[1]))
             else:
                 l.append(str(d))
index 66bcdfaf0a1225b282fae00a8e17b41051ecf795..b2c4204e9de1e1637dd76adbcf676f073482e068 100644 (file)
@@ -737,7 +737,7 @@ class Taskmaster:
         T = self.trace
         if T: T.write('\n' + self.trace_message('Looking for a node to evaluate'))
 
         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')
             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:
                 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:
                 try:
                     node = to_visit.pop()
                 except AttributeError:
index 4a0e13a8f70a803ab73a6481547e526cd1698771..65d10b59ebafc032c02e60ca424363a709d31156 100644 (file)
@@ -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 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"
 
         else:
             raise TestFailed, "did not catch expected BuildError"
 
index e19369520d249ec075798548bb6529b3330e4259..1cc13127533d23fd83fe2861503f52edc4f8cae2 100644 (file)
@@ -243,9 +243,7 @@ def get_all_compiler_versions():
             m = re.search(r'([0-9.]+)$', d)
             if m:
                 versions.append(m.group(1))
             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):
     """
 
 def get_intel_compiler_top(version, abi):
     """
index d080af5f10120b02fefe31fa5c726eb2b95027d3..ef4bd5bae02613ba597cc8a5e2f710acc48ec92f 100644 (file)
@@ -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()):
         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:
                 mydir = dirnode.Dir(dirname)
                 java_paths = [mydir.File(f) for f in java_files]
                 for jp in java_paths:
index 57098a8064d682cd4967b46afeb3d43607147ee5..c5e93ac68bee8119c85a47a87308844a05f8f259 100644 (file)
@@ -291,8 +291,6 @@ class _DSPGenerator:
                         self.sources[t[0]].append(self.env[t[1]])
 
         for n in sourcenames:
                         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):
             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
 
     def PrintHeader(self):
         # pick a default config
-        confkeys = self.configs.keys()
-        confkeys.sort()
+        confkeys = sorted(self.configs.keys())
 
         name = self.name
         confkey = confkeys[0]
 
         name = self.name
         confkey = confkeys[0]
@@ -373,8 +370,7 @@ class _GenerateV6DSP(_DSPGenerator):
                         '# PROP Scc_LocalPath ""\n\n')
 
         first = 1
                         '# 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
         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()
                       '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]:
         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<Configurations>\n')
 
     def PrintProject(self):
         self.file.write('\t<Configurations>\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
         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()
 
     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
         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<Files>\n')
 
         cats = categories.keys()
         self.file.write('\t<Files>\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:
         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')
 
         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
         cnt = 0
         for name in confkeys:
             variant = self.configs[name].variant
index c720956e73f6e34e84b1978dcd554cfc5f8ce5e2..8f1201a022ba3bd0dd8fe9260b72a481c4dd2557 100644 (file)
@@ -99,7 +99,7 @@ def find_versions():
             product_key = SCons.Util.RegOpenKeyEx(HLM, product)
 
             i = 0
             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)
 
                 name = product + '\\' + SCons.Util.RegEnumKey(product_key, i)
                 name_key = SCons.Util.RegOpenKeyEx(HLM, name)
 
index a373863d0ec7ea821caf85441293b6764c34ab2e..f8bac89cf547be07f001c5185ceeba0e2184b29e 100644 (file)
@@ -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.
 
 # 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
 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):
 
 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
 
         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 \
         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.
     #
     # 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)
         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
         # 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))
 
 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))
 
 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__'):
 
 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:
     # 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:
     except TypeError:
         pass    # move on to the next method
     else:
@@ -1291,7 +1292,7 @@ class LogicalLines:
 
     def readline(self):
         result = []
 
     def readline(self):
         result = []
-        while 1:
+        while True:
             line = self.fileobj.readline()
             if not line:
                 break
             line = self.fileobj.readline()
             if not line:
                 break
@@ -1304,7 +1305,7 @@ class LogicalLines:
 
     def readlines(self):
         result = []
 
     def readlines(self):
         result = []
-        while 1:
+        while True:
             line = self.readline()
             if not line:
                 break
             line = self.readline()
             if not line:
                 break
@@ -1545,7 +1546,7 @@ else:
         def MD5filesignature(fname, chunksize=65536):
             m = hashlib.md5()
             f = open(fname, "rb")
         def MD5filesignature(fname, chunksize=65536):
             m = hashlib.md5()
             f = open(fname, "rb")
-            while 1:
+            while True:
                 blck = f.read(chunksize)
                 if not blck:
                     break
                 blck = f.read(chunksize)
                 if not blck:
                     break
index 670fc83c1173ddbf24b51acdfe4abbe381005567..ad271278505247a7c28c09c4cac9951b5587330f 100644 (file)
@@ -27,7 +27,6 @@ import os
 import os.path
 import StringIO
 import sys
 import os.path
 import StringIO
 import sys
-import types
 import unittest
 
 from UserDict import UserDict
 import unittest
 
 from UserDict import UserDict
@@ -38,6 +37,10 @@ import SCons.Errors
 
 from SCons.Util import *
 
 
 from SCons.Util import *
 
+try: unicode
+except NameError: HasUnicode = False
+else:             HasUnicode = True
+
 class OutBuffer:
     def __init__(self):
         self.buffer = ""
 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("")
         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):
             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("")
         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("")
             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
             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("")
         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):
             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
 
             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
                 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
 
                        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)
             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):
                    type(to_String(s4))
 
     def test_WhereIs(self):
index 36b530a9cacb1363cb56ada802885acc3f903c32..5980f331a0e9ac433c5a2f7f46352e14f92c6c62 100644 (file)
@@ -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])
 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
 
     def __cmp__(self, other):
         raise NotImplementedError
index 27f694fe943c841f538491209d2eb6c659229945..09d4e29af7948cdacb23cb7d224b74994739c0a9 100644 (file)
@@ -123,7 +123,7 @@ class Variables:
                     putting it in the environment.
         """
 
                     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
 
             self._do_add(*key)
             return
 
@@ -284,8 +284,7 @@ class Variables:
         """
 
         if sort:
         """
 
         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
 
         else:
             options = self.options
 
index 785a260a1308800831cf106f049336e449753d45..dfc2b3037ab7dbe8d14142f791806c1dac28039c 100644 (file)
@@ -33,17 +33,13 @@ In particular, it does not necessarily contain all of the methods found
 in later versions.
 """
 
 in later versions.
 """
 
-import types
-
-StringType = types.StringType
-
-if hasattr(types, 'UnicodeType'):
-    UnicodeType = types.UnicodeType
+try: unicode
+except NameError:
     def is_String(obj):
     def is_String(obj):
-        return type(obj) in (StringType, UnicodeType)
+        return type(obj) is str
 else:
     def is_String(obj):
 else:
     def is_String(obj):
-        return type(obj) is StringType
+        return type(obj) in (str, unicode)
 
 class UserString:
     def __init__(self, seq):
 
 class UserString:
     def __init__(self, seq):
index 5db4c90b0403e0722669e5dacb4de79140c3b7fa..ac5b448033e953eb4a87ef548834155f81161f63 100644 (file)
@@ -643,8 +643,7 @@ class Option:
                 else:
                     setattr(self, attr, None)
         if attrs:
                 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)
             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)
             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)
                 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
                 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
                 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)
                 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)
 
 except NameError:
     (True, False) = (1, 0)
 
-try:
-    types.UnicodeType
-except AttributeError:
+try: unicode
+except NameError:
     def isbasestring(x):
     def isbasestring(x):
-        return isinstance(x, types.StringType)
+        return isinstance(x, str)
 else:
     def isbasestring(x):
 else:
     def isbasestring(x):
-        return isinstance(x, types.StringType) or isinstance(x, types.UnicodeType)
+        return isinstance(x, str) or isinstance(x, unicode)
 
 class Values:
 
 
 class Values:
 
@@ -879,7 +877,7 @@ class Values:
     def __cmp__(self, other):
         if isinstance(other, Values):
             return cmp(self.__dict__, other.__dict__)
     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
             return cmp(self.__dict__, other)
         else:
             return -1
@@ -1040,7 +1038,7 @@ class OptionContainer:
         """add_option(Option)
            add_option(opt_str, ..., kwarg=val, ...)
         """
         """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]
             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()
 
     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]
             group = apply(OptionGroup, (self,) + args, kwargs)
         elif len(args) == 1 and not kwargs:
             group = args[0]
index 12dbeadc800c04105847409e588ef16a0f8650b4..713d6e9903bd83cb0be555f6595b91df497e53a5 100644 (file)
@@ -110,9 +110,9 @@ class BaseSet(object):
     # __str__ is the same as __repr__
     __str__ = __repr__
 
     # __str__ is the same as __repr__
     __str__ = __repr__
 
-    def _repr(self, sorted=False):
+    def _repr(self, sort_them=False):
         elements = self._data.keys()
         elements = self._data.keys()
-        if sorted:
+        if sort_them:
             elements.sort()
         return '%s(%r)' % (self.__class__.__name__, elements)
 
             elements.sort()
         return '%s(%r)' % (self.__class__.__name__, elements)
 
index 064415ecfa5fab16bf478e053123a1cb08bd9d19..02b94f3e83f612743df06d0f086c49c3c50c9436 100644 (file)
@@ -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):
     # 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[:]
         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
 
         return result
     __builtin__.sorted = sorted
 
index 5ccc00e14ac6123cddcc231f309398dee7f0b51b..5e159eca9b6cd3cd2dff7926bc66ed9704eae40c 100644 (file)
@@ -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?
 # 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.
 
 # Turn the list of keys into one regular expression that will allow us
 # to substitute all of the operators at once.
index bcb2aa00ad451fdfc7d23279ab7bb742025c4a7e..2383f1df0452349c573dcb21fea1bdf42d96ea47 100644 (file)
@@ -5,7 +5,6 @@ import cPickle
 import time
 import shutil
 import os
 import time
 import shutil
 import os
-import types
 import __builtin__
 
 keep_all_files = 00000
 import __builtin__
 
 keep_all_files = 00000
@@ -14,13 +13,13 @@ ignore_corrupt_dbfiles = 0
 def corruption_warning(filename):
     print "Warning: Discarding corrupt database:", filename
 
 def corruption_warning(filename):
     print "Warning: Discarding corrupt database:", filename
 
-if hasattr(types, 'UnicodeType'):
+try: unicode
+except NameError:
     def is_string(s):
     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):
 else:
     def is_string(s):
-        return type(s) is types.StringType
+        return type(s) in (str, unicode)
 
 try:
     unicode('a')
 
 try:
     unicode('a')
index c75bc1338f3cdd5000e2d31b70eb546cdce5b91d..04fa5730f4d8f9739a9b865e6bcb1a8cb90b9392 100644 (file)
@@ -59,6 +59,32 @@ except NameError:
     import __builtin__
     __builtin__.True = not 0
 
     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)
 def make_temp_file(**kw):
     try:
         result = tempfile.mktemp(**kw)
@@ -505,9 +531,7 @@ class SConsTimer:
         """
         files = []
         for a in args:
         """
         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:]
 
         if tail:
             files = files[-tail:]
@@ -589,10 +613,7 @@ class SConsTimer:
         """
         gp = Gnuplotter(self.title, self.key_location)
 
         """
         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:
             try:
                 t = self.run_titles[i]
             except IndexError:
index fb3bd5e1a047106af5a2e940f3bffc31052ace7c..ac619a58b4694fd5bf0e6de2c8ced18991f6a16b 100644 (file)
@@ -282,8 +282,7 @@ def nodeinfo_raw(name, ninfo, prefix=""):
     try:
         keys = ninfo.field_list + ['_version_id']
     except AttributeError:
     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))))
     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:
                     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
             entry = entries[name]
             try:
                 ninfo = entry.ninfo
@@ -402,9 +399,7 @@ class Do_SConsignDB:
                 else:
                     self.printentries(dir, val)
         else:
                 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):
                 self.printentries(dir, db[dir])
 
     def printentries(self, dir, val):
index 69e7a80fce2ec99d3ccb0232f4d1ad6518a15f48..21b0dea43152ea3b8a79ef0579f304ed2eb8bae6 100644 (file)
@@ -90,7 +90,7 @@ for f in files:
     contents = open(os.path.join(scons_lib_dir, f)).read()
     try_except_lines = {}
     lastend = 0
     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
         match = tryexc_pat.search( contents, lastend )
         if match is None:
             break
index fb60646a6e18900d80a363d604f208079249099c..ad689658929120611f4109de9124cc1b33f66b33 100644 (file)
@@ -90,10 +90,7 @@ for file in ignore:
         del u[file]
     except KeyError:
         pass
         del u[file]
     except KeyError:
         pass
-
-files = u.keys()
-
-files.sort()
+files = sorted(u.keys())
 
 mismatches = []
 
 
 mismatches = []
 
index c028372e9ab188ea76b747b1ca829a5e8a7311d3..801d83ada2ba8d64747a51bd13e2e23f9ff0fa11 100644 (file)
@@ -30,9 +30,7 @@ test = TestSCons.TestSCons()
 
 test.write('SConstruct', """
 foo = open('foo.out', 'wb')
 
 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()
 """)
     foo.write(k + " = " + ARGUMENTS[k] + "\\n")
 foo.close()
 """)
index fec90771a9b28e6e34aa109293ae375e380cc007..673920c8f0401a5a3b8219825b4dd1e3a2eafe07 100644 (file)
@@ -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])
 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()
         f = os.path.join(dir, f)
         out.write(open(f, 'r').read())
     out.close()
index f3be46ae3be8e2ae06d02358168ed7cc6bdffe05..74046b1029178558d6a479d5f6e825d1b9f9f0c2 100644 (file)
@@ -58,9 +58,7 @@ def sub(env, target, source):
     target = str(target[0])
     source = str(source[0])
     t = open(target, 'wb')
     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
         t.write(open(os.path.join(source, f), 'rb').read())
     t.close()
     return 0
index f64defea7493445699297e486830fb34e61fd9af..51635c51ebe9dfd0e1c43ba523466a2978ce0168 100644 (file)
@@ -153,9 +153,9 @@ errors = 0
 
 def must_be_same(f1, f2):
     global errors
 
 def must_be_same(f1, f2):
     global errors
-    if type(f1) is type([]):
+    if isinstance(f1, list):
         f1 = os.path.join(*f1)
         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)
         f2 = os.path.join(*f2)
     s1 = os.stat(f1)
     s2 = os.stat(f2)
index 532c379218ab765e19213411a51ad57affb0fe61..53b57ff89a19a23864d7af06fb2863484a9c656a 100644 (file)
@@ -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
 
 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:
         print "%%s failed:  %%s" %% (bf.node, bf.errstr)
 
 try:
index 6ee5cc35f525970ff8be967cc811d0c02ab1768f..e250486a32f5c9fa18ef50180fda9fc8519a6310 100644 (file)
@@ -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
 
 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:
         print "%%s failed:  %%s" %% (bf.node, bf.errstr)
 
 try:
index a240d1ef678824845d20693c71515f9b27c20669..752b3486ba87e7b1e806f51c9e5f6ccd692e940e 100644 (file)
@@ -89,9 +89,7 @@ Command('f15', 'f15.in', returnExcAction(SCons.Errors.InternalError("My Internal
 
 def print_build_failures():
     from SCons.Script import GetBuildFailures
 
 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:
         assert( isinstance(bf, SCons.Errors.BuildError) )
         print "BF: %%s failed (%%s):  %%s" %% (bf.node, bf.status, bf.errstr)
         if bf.command:
index 5783443a897b24ee0b4568c4ee3f7cf9403ae6c1..0a2e32670f23249215deaceed35db267f062c7cb 100644 (file)
@@ -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'))
 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")
 """)
 
 test.write(['repository', 'src', 'xxx.in'], "repository/src/xxx.in\n")
index 62226ce0b12d593df54fb28c64d34b3633af35b9..175e5b9c7af78e3a0a2ff077759219d14fc7336a 100644 (file)
@@ -54,9 +54,7 @@ def concatenate(target, source, env):
 
 env['BUILDERS']['Concatenate'] = Builder(action=concatenate)
 
 
 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")
 """)
 
 test.write(['src', 'f1.in'], "src/f1.in\n")
index d985a7359ed18772aa34463ac5b4cb1a11022b75..9afbbc69f8b1fdaaaadbee69cb640a221cae56c8 100644 (file)
@@ -43,9 +43,7 @@ def concatenate(target, source, env):
 
 env['BUILDERS']['Concatenate'] = Builder(action=concatenate)
 
 
 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")
 """)
 
 test.write('f1.in', "f1.in\n")
index 33baf3713e27134bef795b5d7a5baa79510ffa4d..afa17f565058654065349b551c4b2e4aa72dde4f 100644 (file)
@@ -59,16 +59,14 @@ SConscript('var2/SConscript')
 test.write(['var1', 'SConscript'], """\
 Import("env")
 
 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")
 
 """)
 
 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)
 """)
 
 env.Concatenate('f.out', f_in)
 """)
 
index 1ef04214a0800a5b36a1b5ac4c823c1afe41c704..3e47d103e7447086e8b21cd2e2f88aa453b4a844 100644 (file)
@@ -55,9 +55,7 @@ def concatenate(target, source, env):
 
 env['BUILDERS']['Concatenate'] = Builder(action=concatenate)
 
 
 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")
 """)
 
 test.write(['src', 'f1.in'], "src/f1.in\n")
index 0255ff836cf7031b31788bc8d58fbec2e9250a7d..6fc00f630bf8371d08b11e75ad45c2348d59a654 100644 (file)
@@ -46,9 +46,7 @@ def concatenate(target, source, env):
 
 env['BUILDERS']['Concatenate'] = Builder(action=concatenate)
 
 
 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")
 """)
 
 test.write(['subdir', 'file.in'], "subdir/file.in\n")
index abf2bb4fddbab9160a8ec092c874701f78d87758..e21da815ab6244ecee74f1dcef6a83451fd697b5 100644 (file)
@@ -44,9 +44,7 @@ def copy(target, source, env):
 
 env['BUILDERS']['Copy'] = Builder(action=copy)
 
 
 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")
 """)
 
 test.write('f1.in', "f1.in\n")
index 094e6ed756fb23dd542efb1939f57a82e27eae31..dbeecb7a3b622d5be08c780b275f234158b63c68 100644 (file)
@@ -129,9 +129,7 @@ def catdir(env, source, target):
     outfp = open(target, "wb")
     for src in source:
         s = str(src)
     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())
             f = os.path.join(s, f)
             if os.path.isfile(f):
                 outfp.write(open(f, "rb").read())
index 8c90df4538a60bfa85d88e85a93958a8765ad2b0..021204358626aa6ef8a5620c9b653a3e265a3c08 100644 (file)
@@ -301,10 +301,8 @@ import os
 Scanned = {}
 
 def write_out(file, dict):
 Scanned = {}
 
 def write_out(file, dict):
-    keys = dict.keys()
-    keys.sort()
     f = open(file, 'wb')
     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()
         file = os.path.split(k)[1]
         f.write(file + ": " + str(dict[k]) + "\\n")
     f.close()
index 9a47c018915dab117c7998cc3179560256bb42cd..3a918bff345ab0b7a95fcbeead47b3fbd90a5fec 100644 (file)
@@ -81,10 +81,8 @@ sys.exit(0)
 
 test.write('SConstruct', """\
 def foo(target, source, env):
 
 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')
     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)
         fp.write('%s\\n' % c)
     fp.close()
 Command('list.out', 'subdir', foo, source_scanner = DirScanner)
index ac8d7913dda23e9b2494060ff8e6b596626f5755..5a19a98fe5f4fc2e9f410a031a33061a916d2437 100644 (file)
@@ -44,6 +44,8 @@ for opt, arg in opts:
     if opt == '-f': out = arg
 def process(outfile, name):
     if os.path.isdir(name):
     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:
         list = os.listdir(name)
         list.sort()
         for entry in list:
index f349b3a67c8aa764a0915710bb7971726b925001..96d61fe7d3b2fb84b6b207d078f7c0688b89fe94 100644 (file)
@@ -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):
     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:
         entries = os.listdir(name)
         entries.sort()
         for entry in entries:
index 73e781059e809ea96f8493dc31d8ee9007f78d01..f9ba417a4991011172345f8d952b0ad461178cbf 100644 (file)
@@ -49,6 +49,8 @@ import os.path
 import sys
 def process(outfile, name):
     if os.path.isdir(name):
 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:
         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")
     test.write('SConstruct', """\
 def marker(target, source, env):
     open(r'%s', 'wb').write("marker\\n")
-import types
 f1 = Environment()
 zipcom = f1.Dictionary('ZIPCOM')
 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')
     zipcom = [zipcom]
 f2 = Environment(ZIPCOM = [Action(marker)] + zipcom)
 f3 = Environment(ZIPSUFFIX = '.xyzzy')
index 1a9a72b7f854421b9ba5328243952216d3e10226..27f4950e33abcd6673e1ca625e8b1818158dc81b 100644 (file)
 __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
 
 import os
 __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
 
 import os
-import types
 
 import TestSCons
 
 def match_normcase(lines, matches):
 
 import TestSCons
 
 def match_normcase(lines, matches):
-    if not type(lines) is types.ListType:
+    if not isinstance(lines, list):
         lines = lines.split("\n")
         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
         matches = matches.split("\n")
     if len(lines) != len(matches):
         return
index 0f4dd4d6d06a9da78b6285bc666f30cb0985b688..2b48a66fc6a4070f491bf959942dec10d87d7ecc 100644 (file)
@@ -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]
 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 "lowered =", lowered
-    print "sorted =", sorted
+    print "sorted =", ordered
     test.fail_test()
 
 test.pass_test()
     test.fail_test()
 
 test.pass_test()
index 66374e3a0b40aeb642df7365d0ea3c0bda060c71..2fc6aeeac4397e3a41b3e65e80bcbb8e9e691b1e 100644 (file)
@@ -43,10 +43,8 @@ env  = Environment(tools=['default', 'packaging'])
 prog = env.Install( 'bin/', ["f1", "f2"] )
 env.File( "f3" )
 
 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
 
 print src_files
 print oth_files
index 820d3ce627f8170d4e6f066e337c02832c6bbb35..2b677e94f0d1baad16eb7fcc34781289574c4f62 100644 (file)
@@ -42,8 +42,7 @@ class Bars(dict):
         if color is None:
             color = self.color
         if revs is None:
         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:
         if labels:
             result = [ (r, color, None, self[r]) for r in revs ]
         else: