Commits

Anonymous committed 2395d93

http://scons.tigris.org/issues/show_bug.cgi?id=2329

Applied a number of idiomatic changes.

Uses of the 'sort()' method were converted into calls of 'sorted()' when
possible and the sorted() expression was inserted into a subsequent statement
whenever that made sense.

The statement 'while 1:' was changed to 'while True:'.

Names from the 'types' module (e.g., 'types.FooType') were converted to the
equivalent build-in type (e.g., 'foo').

Comparisons between types were changed to use 'isinstance()'.

Comments (0)

Files changed (102)

 import tempfile
 import time
 import traceback
-import types
 import UserList
 
 __all__ = [
     __all__.append('simple_diff')
 
 def is_List(e):
-    return type(e) is types.ListType \
+    return isinstance(e, list) \
         or isinstance(e, UserList.UserList)
 
 try:
     class UserString:
         pass
 
-if hasattr(types, 'UnicodeType'):
+try: unicode
+except NameError:
     def is_String(e):
-        return type(e) is types.StringType \
-            or type(e) is types.UnicodeType \
-            or isinstance(e, UserString)
+        return isinstance(e, str) or isinstance(e, UserString)
 else:
     def is_String(e):
-        return type(e) is types.StringType or isinstance(e, UserString)
+        return isinstance(e, str) \
+            or isinstance(e, unicode) \
+            or isinstance(e, UserString)
 
 tempfile.template = 'testcmd.'
 if os.name in ('posix', 'nt'):
 def match_re_dotall(lines = None, res = None):
     """
     """
-    if not type(lines) is type(""):
+    if not isinstance(lines, str):
         lines = "\n".join(lines)
-    if not type(res) is type(""):
+    if not isinstance(res, str):
         res = "\n".join(res)
     s = "^" + res + "$"
     try:
                            interpreter = None,
                            arguments = None):
         if program:
-            if type(program) == type('') and not os.path.isabs(program):
+            if isinstance(program, str) and not os.path.isabs(program):
                 program = os.path.join(self._cwd, program)
         else:
             program = self.program
             if not interpreter:
                 interpreter = self.interpreter
-        if not type(program) in [type([]), type(())]:
+        if not type(program) in [list, tuple]:
             program = [program]
         cmd = list(program)
         if interpreter:
-            if not type(interpreter) in [type([]), type(())]:
+            if not type(interpreter) in [list, tuple]:
                 interpreter = [interpreter]
             cmd = list(interpreter) + cmd
         if arguments:
-            if type(arguments) == type(''):
+            if isinstance(arguments, str):
                 arguments = arguments.split()
             cmd.extend(arguments)
         return cmd
 import os.path
 import stat
 import sys
-import types
 import UserList
 
 from TestCmd import *
     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):
         import glob
         result = []
         for p in patterns:
-            paths = glob.glob(p)
-            paths.sort()
-            result.extend(paths)
+            result.extend(sorted(glob.glob(p)))
         return result
 
 
         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
         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)
 """
     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)
 
 """)
 
-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(
 try:
     FunctionList
 except NameError:
-    function_names = [x for x in locals().keys() if x[:4] == FunctionPrefix]
-    function_names.sort()
+    function_names = sorted([x for x in locals().keys() if x[:4] == FunctionPrefix])
     l = [locals()[f] for f in function_names]
-    FunctionList = [f for f in l if type(f) == types.FunctionType]
+    FunctionList = [f for f in l if isinstance(f, types.FunctionType)]
 
 IterationList = [None] * Iterations
 

bench/env.__setitem__.py

         t = Timing(n, num, init, s)
         t.timeit()
         timings.append(t)
-    
+
     print
     print title
-    l = []
-    for i in timings: l.append((i.getResult(),i.name))
-    l.sort()
-    for i in l: print "  %9.3f s   %s" % i
+    for i in sorted([(i.getResult(),i.name) for i in timings]):
+        print "  %9.3f s   %s" % i
 
 # Import the necessary local SCons.* modules used by some of our
 # alternative implementations below, first manipulating sys.path so
     # 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[:]
         __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
 # User* type.
 
 def original_is_Dict(e):
-    return type(e) is types.DictType or isinstance(e, UserDict)
+    return isinstance(e, dict) or isinstance(e, UserDict)
 
 def original_is_List(e):
-    return type(e) is types.ListType or isinstance(e, UserList)
+    return isinstance(e, list) or isinstance(e, UserList)
 
-if hasattr(types, 'UnicodeType'):
+if UnicodeType is not None:
     def original_is_String(e):
-        return type(e) is types.StringType \
-            or type(e) is types.UnicodeType \
+        return isinstance(e, str) \
+            or isinstance(e, unicode) \
             or isinstance(e, UserString)
 else:
     def original_is_String(e):
-        return type(e) is types.StringType or isinstance(e, UserString)
+        return isinstance(e, str) or isinstance(e, UserString)
 
 
 
 # type.
 
 def checkInstanceType_is_Dict(e):
-    return type(e) is types.DictType or \
-           (type(e) is types.InstanceType and isinstance(e, UserDict))
+    return isinstance(e, dict) or \
+           (isinstance(e, types.InstanceType) and isinstance(e, UserDict))
 
 def checkInstanceType_is_List(e):
-    return type(e) is types.ListType \
-        or (type(e) is types.InstanceType and isinstance(e, UserList))
+    return isinstance(e, list) \
+        or (isinstance(e, types.InstanceType) and isinstance(e, UserList))
 
-if hasattr(types, 'UnicodeType'):
+if UnicodeType is not None:
     def checkInstanceType_is_String(e):
-        return type(e) is types.StringType \
-            or type(e) is types.UnicodeType \
-            or (type(e) is types.InstanceType and isinstance(e, UserString))
+        return isinstance(e, str) \
+            or isinstance(e, unicode) \
+            or (isinstance(e, types.InstanceType) and isinstance(e, UserString))
 else:
     def checkInstanceType_is_String(e):
-        return type(e) is types.StringType \
-            or (type(e) is types.InstanceType and isinstance(e, UserString))
+        return isinstance(e, str) \
+            or (isinstance(e, types.InstanceType) and isinstance(e, UserString))
 
 
 
 
 def cache_type_e_is_Dict(e):
     t = type(e)
-    return t is types.DictType or \
+    return t is dict or \
            (t is types.InstanceType and isinstance(e, UserDict))
 
 def cache_type_e_is_List(e):
     t = type(e)
-    return t is types.ListType \
+    return t is list \
         or (t is types.InstanceType and isinstance(e, UserList))
 
-if hasattr(types, 'UnicodeType'):
+if UnicodeType is not None:
     def cache_type_e_is_String(e):
         t = type(e)
-        return t is types.StringType \
-            or t is types.UnicodeType \
+        return t is str \
+            or t is unicode \
             or (t is types.InstanceType and isinstance(e, UserString))
 else:
     def cache_type_e_is_String(e):
         t = type(e)
-        return t is types.StringType \
+        return t is str \
             or (t is types.InstanceType and isinstance(e, UserString))
 
 
     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 \
 # to their corresponding underlying types.
 
 instanceTypeMap = {
-    UserDict : types.DictType,
-    UserList : types.ListType,
-    UserString : types.StringType,
+    UserDict : dict,
+    UserList : list,
+    UserString : str,
 }
 
-if hasattr(types, 'UnicodeType'):
+if UnicodeType is not None:
     def myType(obj):
         t = type(obj)
         if t is types.InstanceType:
             t = instanceTypeMap.get(obj.__class__, t)
-        elif t is types.UnicodeType:
-            t = types.StringType
+        elif t is unicode:
+            t = str
         return t
 else:
     def myType(obj):
         return t
 
 def myType_is_Dict(e):
-    return myType(e) is types.DictType
+    return myType(e) is dict
 
 def myType_is_List(e):
-    return myType(e) is types.ListType
+    return myType(e) is list
 
 def myType_is_String(e):
-    return myType(e) is types.StringType
+    return myType(e) is str
 
 
 
         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)))
         pass
 
     def do_execute(self, command):
-        if type(command) == type(''):
+        if isinstance(command, str):
             command = self.subst(command)
             cmdargs = shlex.split(command)
             if cmdargs[0] == 'cd':
                  command = (os.chdir,) + tuple(cmdargs[1:])
             elif cmdargs[0] == 'mkdir':
                  command = (os.mkdir,) + tuple(cmdargs[1:])
-        if type(command) == type(()):
+        if isinstance(command, tuple):
             func = command[0]
             args = command[1:]
             return func(*args)
     def start_uses(self, attrs):
         self.begin_collecting([])
     def end_uses(self):
-        self.current_object.uses = ''.join(self.collect).split()
-        self.current_object.uses.sort()
+        self.current_object.uses = sorted(''.join(self.collect).split())
         self.end_collecting()
 
     def start_sets(self, attrs):
         self.begin_collecting([])
     def end_sets(self):
-        self.current_object.sets = ''.join(self.collect).split()
-        self.current_object.sets.sort()
+        self.current_object.sets = sorted(''.join(self.collect).split())
         self.end_collecting()
 
     # Stuff for the ErrorHandler portion.
         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
           diffstr(c1[3], c2[3]) + \
           ' ' + classname
 
-keys = common.keys()
-keys.sort()
-for k in keys:
+for k in sorted(common.keys()):
     c = common[k]
     printline(c[0], c[1], k)
 
-keys = c1.keys()
-keys.sort()
-for k in keys:
+for k in sorted(list(c1.keys())):
     printline(c1[k], ['--']*4, k)
 
-keys = c2.keys()
-keys.sort()
-for k in keys:
+for k in sorted(list(c2.keys())):
     printline(['--']*4, c2[k], k)
 
 # Local Variables:
         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),
 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
 
 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:
 
 def outname(n, outdir=outdir):
     l = []
-    while 1:
+    while True:
         n, tail = os.path.split(n)
         if not n:
             break
     ]
 
     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>"
 
 def outname(n, outdir=outdir):
     l = []
-    while 1:
+    while True:
         n, tail = os.path.split(n)
         if not n:
             break
     def display(self, command, stdout=None, stderr=None):
         if not self.verbose:
             return
-        if type(command) == type(()):
+        if isinstance(command, tuple):
             func = command[0]
             args = command[1:]
             s = '%s(%s)' % (func.__name__, ', '.join(map(repr, args)))
-        if type(command) == type([]):
+        if isinstance(command, list):
             # TODO:    quote arguments containing spaces
             # TODO:    handle meta characters?
             s = ' '.join(command)
         """
         if not self.active:
             return 0
-        if type(command) == type(''):
+        if isinstance(command, str):
             command = self.subst(command)
             cmdargs = shlex.split(command)
             if cmdargs[0] == 'cd':
                  command = (os.chdir,) + tuple(cmdargs[1:])
-        if type(command) == type(()):
+        if isinstance(command, tuple):
             func = command[0]
             args = command[1:]
             return func(*args)
 
 # 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 = [

doc/user/environments.in

 
       <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>
       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>

doc/user/environments.xml

 
       <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>
       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>

doc/user/parseflags.in

    <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)
    <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)
    <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)
    <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)

doc/user/parseflags.xml

  <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)
  <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)
  <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)
  <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
 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
                         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:
                 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:

src/engine/SCons/Action.py

             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

src/engine/SCons/ActionTests.py

         # 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
 
             env = Environment()
 
             def execfunc(target, source, env):
-                assert type(target) is type([]), type(target)
-                assert type(source) is type([]), type(source)
+                assert isinstance(target, list), type(target)
+                assert isinstance(source, list), type(source)
                 return 7
             a = SCons.Action.Action(execfunc)
 
             def firstfunc(target, source, env):
-                assert type(target) is type([]), type(target)
-                assert type(source) is type([]), type(source)
+                assert isinstance(target, list), type(target)
+                assert isinstance(source, list), type(source)
                 return 0
             def lastfunc(target, source, env):
-                assert type(target) is type([]), type(target)
-                assert type(source) is type([]), type(source)
+                assert isinstance(target, list), type(target)
+                assert isinstance(source, list), type(source)
                 return 9
             b = SCons.Action.Action([firstfunc, execfunc, lastfunc])
             

src/engine/SCons/BuilderTests.py

 import os.path
 import re
 import sys
-import types
 import StringIO
 import unittest
 import UserList
         #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

src/engine/SCons/Conftest.py

         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))

src/engine/SCons/Debug.py

 
 def string_to_classes(s):
     if s == '*':
-        c = tracked_classes.keys()
-        c.sort()
-        return c
+        return sorted(tracked_classes.keys())
     else:
         return s.split()
 
 
 # print a single caller and its callers, if any
 def _dump_one_caller(key, file, level=0):
-    l = []
-    for c,v in caller_dicts[key].items():
-        l.append((-v,c))
-    l.sort()
     leader = '      '*level
-    for v,c in l:
+    for v,c in sorted([(-v,c) for c,v in caller_dicts[key].items()]):
         file.write("%s  %6d %s:%d(%s)\n" % ((leader,-v) + func_shorten(c[-3:])))
         if c in caller_dicts:
             _dump_one_caller(c, file, level+1)
 
 # print each call tree
 def dump_caller_counts(file=sys.stdout):
-    keys = caller_bases.keys()
-    keys.sort()
-    for k in keys:
+    for k in sorted(caller_bases.keys()):
         file.write("Callers of %s:%d(%s), %d calls:\n"
                     % (func_shorten(k) + (caller_bases[k],)))
         _dump_one_caller(k, file)

src/engine/SCons/Defaults.py

 import shutil
 import stat
 import time
-import types
 import sys
 
 import SCons.Action
     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))
         # 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:

src/engine/SCons/DefaultsTests.py

 import os.path
 import StringIO
 import sys
-import types
 import unittest
 
 from UserDict import UserDict

src/engine/SCons/Environment.py

         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)

src/engine/SCons/EnvironmentTests.py

 
 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):
         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

src/engine/SCons/Job.py

         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:
             self.start()
 
         def run(self):
-            while 1:
+            while True:
                 task = self.requestQueue.get()
 
                 if task is None:
 
             jobs = 0
             
-            while 1:
+            while True:
                 # Start up as many available tasks as we're
                 # allowed to.
                 while jobs < self.maxjobs:
 
                 # 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
 

src/engine/SCons/JobTests.py

     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)

src/engine/SCons/Node/FS.py

         """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)
 
         """
         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:

src/engine/SCons/Node/FSTests.py

         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'),
 
         fs.File(os.path.join('ddd', 'f1'))
         dir.scan()
-        kids = [x.path for x in dir.children()]
-        kids.sort()
+        kids = sorted([x.path for x in dir.children()])
         assert kids == [os.path.join('ddd', 'f1')], kids
 
         fs.File(os.path.join('ddd', 'f2'))
         dir.scan()
-        kids = [x.path for x in dir.children()]
-        kids.sort()
+        kids = sorted([x.path for x in dir.children()])
         assert kids == [os.path.join('ddd', 'f1'),
                         os.path.join('ddd', 'f2')], kids
 
         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
                 r.sort(lambda a,b: cmp(a.path, b.path))
                 result = []
                 for n in node_expect:
-                    if type(n) == type(''):
+                    if isinstance(n, str):
                         n = self.fs.Entry(n)
                     result.append(n)
                 fmt = lambda n: "%s %s" % (repr(n), repr(str(n)))
             else:
-                r = list(map(str, r))
-                r.sort()
+                r = sorted(map(str, r))
                 result = string_expect
                 fmt = lambda n: n
             if r != result:

src/engine/SCons/Node/NodeTests.py

 import os
 import re
 import sys
-import types
 import unittest
 import UserList
 
             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'

src/engine/SCons/Node/__init__.py

             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:

src/engine/SCons/SConf.py

 import StringIO
 import sys
 import traceback
-import types
 
 import SCons.Action
 import SCons.Builder
     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):
     """
                 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))

src/engine/SCons/SConfTests.py

         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()

src/engine/SCons/SConsign.py

         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:
             return
 
         self.entries = cPickle.load(fp)
-        if type(self.entries) is not type({}):
+        if not isinstance(self.entries, dict):
             self.entries = {}
             raise TypeError
 

src/engine/SCons/Scanner/CTests.py

         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))
 

src/engine/SCons/Scanner/Dir.py

         # 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:

src/engine/SCons/Scanner/DirTests.py

 
 import os.path
 import sys
-import types
 import unittest
 
 import TestCmd

src/engine/SCons/Scanner/Fortran.py

                 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

src/engine/SCons/Scanner/FortranTests.py

         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))
 

src/engine/SCons/Scanner/IDLTests.py

         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))
 

src/engine/SCons/Scanner/LaTeX.py

                 # 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

src/engine/SCons/Scanner/LaTeXTests.py

 
 import os.path
 import sys
-import types
 import unittest
 import UserDict
 
         return [[strSubst]]
 
     def subst_path(self, path, target=None, source=None, conv=None):
-        if type(path) != type([]):
+        if not isinstance(path, list):
             path = [path]
         return list(map(self.subst, path))
 

src/engine/SCons/Scanner/ProgTests.py

 
 import os.path
 import sys
-import types
 import unittest
 
 import TestCmd
         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))
 
         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))
 
     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):

src/engine/SCons/Scanner/RCTests.py

         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))
 
     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:

src/engine/SCons/Scanner/ScannerTests.py

             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):
         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")

src/engine/SCons/Scanner/__init__.py

                 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):
     """

src/engine/SCons/Script/Main.py

                     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):
             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"]
         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))
 
 
     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:

src/engine/SCons/Script/SConscript.py

 import re
 import sys
 import traceback
-import types
 import UserList
 
 # The following variables used to live in this module.  Some
         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]
 

src/engine/SCons/Subst.py

 __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
 
 import re
-import types
 import UserList
 import UserString
 
     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:
 
     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 + '}']

src/engine/SCons/SubstTests.py

 import os.path
 import StringIO
 import sys
-import types
 import unittest
 
 from UserDict import UserDict
     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))

src/engine/SCons/Taskmaster.py

         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')
                 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:

src/engine/SCons/TaskmasterTests.py

             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"
 

src/engine/SCons/Tool/intelc.py

             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):
     """

src/engine/SCons/Tool/javac.py

         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:

src/engine/SCons/Tool/msvs.py

                         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):
 
     def PrintHeader(self):
         # pick a default config
-        confkeys = self.configs.keys()
-        confkeys.sort()
+        confkeys = sorted(self.configs.keys())
 
         name = self.name
         confkey = confkeys[0]
                         '# 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
                       '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]:
     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
 
     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
         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:
         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

src/engine/SCons/Tool/mwcc.py

             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)
 

src/engine/SCons/Util.py

 
 # Don't "from types import ..." these because we need to get at the
 # types module later to look for UnicodeType.
-DictType        = types.DictType
+DictType        = dict
 InstanceType    = types.InstanceType
-ListType        = types.ListType
-StringType      = types.StringType
-TupleType       = types.TupleType
+ListType        = list
+StringType      = str
+TupleType       = tuple
+try: unicode
+except NameError: UnicodeType = None
+else:             UnicodeType = unicode
 
 def dictify(keys, values, result={}):
     for k, v in zip(keys, values):
         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 \
     # 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)
         # Doesn't seem like we need to, but we'll comment it just in case.
         copy[key] = semi_deepcopy(val)
     return copy
-d[types.DictionaryType] = _semi_deepcopy_dict
+d[dict] = _semi_deepcopy_dict
 
 def _semi_deepcopy_list(x):
     return list(map(semi_deepcopy, x))
-d[types.ListType] = _semi_deepcopy_list
+d[list] = _semi_deepcopy_list
 
 def _semi_deepcopy_tuple(x):
     return tuple(map(semi_deepcopy, x))
-d[types.TupleType] = _semi_deepcopy_tuple
+d[tuple] = _semi_deepcopy_tuple
 
 def _semi_deepcopy_inst(x):
     if hasattr(x, '__semi_deepcopy__'):
     # 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:
 
     def readline(self):
         result = []
-        while 1:
+        while True:
             line = self.fileobj.readline()
             if not line:
                 break
 
     def readlines(self):
         result = []
-        while 1:
+        while True:
             line = self.readline()
             if not line:
                 break
         def MD5filesignature(fname, chunksize=65536):
             m = hashlib.md5()
             f = open(fname, "rb")
-            while 1:
+            while True:
                 blck = f.read(chunksize)
                 if not blck:
                     break

src/engine/SCons/UtilTests.py

 import os.path
 import StringIO
 import sys
-import types
 import unittest
 
 from UserDict import UserDict
 
 from SCons.Util import *
 
+try: unicode
+except NameError: HasUnicode = False
+else:             HasUnicode = True
+
 class OutBuffer:
     def __init__(self):
         self.buffer = ""
         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):
         assert not is_List(())
         assert not is_List({})
         assert not is_List("")
-        if hasattr(types, 'UnicodeType'):
+        if HasUnicode:
             exec "assert not is_List(u'')"
 
     def test_is_String(self):
         assert is_String("")
-        if hasattr(types, 'UnicodeType'):
+        if HasUnicode:
             exec "assert is_String(u'')"
         try:
             import UserString
         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):
             assert to_String(s2) == s2, s2
             assert to_String(s2) == 'foo', s2
 
-            if hasattr(types, 'UnicodeType'):
+            if HasUnicode:
                 s3=UserString.UserString(unicode('bar'))
                 assert to_String(s3) == s3, s3
                 assert to_String(s3) == unicode('bar'), s3
-                assert type(to_String(s3)) is types.UnicodeType, \
+                assert isinstance(to_String(s3), unicode), \
                        type(to_String(s3))
         except ImportError:
             pass
 
-        if hasattr(types, 'UnicodeType'):
+        if HasUnicode:
             s4 = unicode('baz')
             assert to_String(s4) == unicode('baz'), to_String(s4)
-            assert type(to_String(s4)) is types.UnicodeType, \
+            assert isinstance(to_String(s4), unicode), \
                    type(to_String(s4))
 
     def test_WhereIs(self):

src/engine/SCons/Variables/ListVariable.py

 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

src/engine/SCons/Variables/__init__.py

                     putting it in the environment.
         """