summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorGreg Noel <GregNoel@tigris.org>2010-03-27 07:39:52 (GMT)
committerGreg Noel <GregNoel@tigris.org>2010-03-27 07:39:52 (GMT)
commit59ed0a109bf5add2efcef459080837b11066c6fb (patch)
treefff879b4f9676a72e16c0f7b4dd969f050038b4f /src
parent00a3188193ba1feef927cf18e7f5fc20ad71b848 (diff)
downloadSCons-59ed0a109bf5add2efcef459080837b11066c6fb.zip
SCons-59ed0a109bf5add2efcef459080837b11066c6fb.tar.gz
SCons-59ed0a109bf5add2efcef459080837b11066c6fb.tar.bz2
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()'.
Diffstat (limited to 'src')
-rw-r--r--src/engine/SCons/Action.py2
-rw-r--r--src/engine/SCons/ActionTests.py16
-rw-r--r--src/engine/SCons/BuilderTests.py4
-rw-r--r--src/engine/SCons/Conftest.py2
-rw-r--r--src/engine/SCons/Debug.py14
-rw-r--r--src/engine/SCons/Defaults.py8
-rw-r--r--src/engine/SCons/DefaultsTests.py1
-rw-r--r--src/engine/SCons/Environment.py2
-rw-r--r--src/engine/SCons/EnvironmentTests.py7
-rw-r--r--src/engine/SCons/Job.py8
-rw-r--r--src/engine/SCons/JobTests.py4
-rw-r--r--src/engine/SCons/Node/FS.py10
-rw-r--r--src/engine/SCons/Node/FSTests.py17
-rw-r--r--src/engine/SCons/Node/NodeTests.py3
-rw-r--r--src/engine/SCons/Node/__init__.py3
-rw-r--r--src/engine/SCons/SConf.py8
-rw-r--r--src/engine/SCons/SConfTests.py2
-rw-r--r--src/engine/SCons/SConsign.py4
-rw-r--r--src/engine/SCons/Scanner/CTests.py2
-rw-r--r--src/engine/SCons/Scanner/Dir.py3
-rw-r--r--src/engine/SCons/Scanner/DirTests.py1
-rw-r--r--src/engine/SCons/Scanner/Fortran.py4
-rw-r--r--src/engine/SCons/Scanner/FortranTests.py2
-rw-r--r--src/engine/SCons/Scanner/IDLTests.py2
-rw-r--r--src/engine/SCons/Scanner/LaTeX.py5
-rw-r--r--src/engine/SCons/Scanner/LaTeXTests.py3
-rw-r--r--src/engine/SCons/Scanner/ProgTests.py10
-rw-r--r--src/engine/SCons/Scanner/RCTests.py8
-rw-r--r--src/engine/SCons/Scanner/ScannerTests.py4
-rw-r--r--src/engine/SCons/Scanner/__init__.py7
-rw-r--r--src/engine/SCons/Script/Main.py12
-rw-r--r--src/engine/SCons/Script/SConscript.py3
-rw-r--r--src/engine/SCons/Subst.py5
-rw-r--r--src/engine/SCons/SubstTests.py3
-rw-r--r--src/engine/SCons/Taskmaster.py4
-rw-r--r--src/engine/SCons/TaskmasterTests.py2
-rw-r--r--src/engine/SCons/Tool/intelc.py4
-rw-r--r--src/engine/SCons/Tool/javac.py5
-rw-r--r--src/engine/SCons/Tool/msvs.py20
-rw-r--r--src/engine/SCons/Tool/mwcc.py2
-rw-r--r--src/engine/SCons/Util.py31
-rw-r--r--src/engine/SCons/UtilTests.py21
-rw-r--r--src/engine/SCons/Variables/ListVariable.py3
-rw-r--r--src/engine/SCons/Variables/__init__.py5
-rw-r--r--src/engine/SCons/compat/_scons_UserString.py12
-rw-r--r--src/engine/SCons/compat/_scons_optparse.py24
-rw-r--r--src/engine/SCons/compat/_scons_sets.py4
-rw-r--r--src/engine/SCons/compat/builtins.py28
-rw-r--r--src/engine/SCons/cpp.py3
-rw-r--r--src/engine/SCons/dblite.py9
-rw-r--r--src/script/scons-time.py35
-rw-r--r--src/script/sconsign.py11
-rw-r--r--src/test_interrupts.py2
-rw-r--r--src/test_pychecker.py5
54 files changed, 179 insertions, 240 deletions
diff --git a/src/engine/SCons/Action.py b/src/engine/SCons/Action.py
index 35c7316..9d49752 100644
--- a/src/engine/SCons/Action.py
+++ b/src/engine/SCons/Action.py
@@ -704,7 +704,7 @@ class CommandAction(_ActionAction):
result = env.subst_list(self.cmd_list, 0, target, source)
silent = None
ignore = None
- while 1:
+ while True:
try: c = result[0][0][0]
except IndexError: c = None
if c == '@': silent = 1
diff --git a/src/engine/SCons/ActionTests.py b/src/engine/SCons/ActionTests.py
index 12756e5..052582b 100644
--- a/src/engine/SCons/ActionTests.py
+++ b/src/engine/SCons/ActionTests.py
@@ -304,7 +304,9 @@ class ActionTestCase(unittest.TestCase):
# a singleton list returns the contained action
test_positional_args(cmd_action, ["string"])
- if hasattr(types, 'UnicodeType'):
+ try: unicode
+ except NameError: pass
+ else:
a2 = eval("SCons.Action.Action(u'string')")
assert isinstance(a2, SCons.Action.CommandAction), a2
@@ -540,18 +542,18 @@ class _ActionActionTestCase(unittest.TestCase):
env = Environment()
def execfunc(target, source, env):
- assert type(target) is type([]), type(target)
- assert type(source) is type([]), type(source)
+ assert isinstance(target, list), type(target)
+ assert isinstance(source, list), type(source)
return 7
a = SCons.Action.Action(execfunc)
def firstfunc(target, source, env):
- assert type(target) is type([]), type(target)
- assert type(source) is type([]), type(source)
+ assert isinstance(target, list), type(target)
+ assert isinstance(source, list), type(source)
return 0
def lastfunc(target, source, env):
- assert type(target) is type([]), type(target)
- assert type(source) is type([]), type(source)
+ assert isinstance(target, list), type(target)
+ assert isinstance(source, list), type(source)
return 9
b = SCons.Action.Action([firstfunc, execfunc, lastfunc])
diff --git a/src/engine/SCons/BuilderTests.py b/src/engine/SCons/BuilderTests.py
index f26aa67..e4ddaec 100644
--- a/src/engine/SCons/BuilderTests.py
+++ b/src/engine/SCons/BuilderTests.py
@@ -35,7 +35,6 @@ def Func():
import os.path
import re
import sys
-import types
import StringIO
import unittest
import UserList
@@ -306,7 +305,8 @@ class BuilderTestCase(unittest.TestCase):
#be = target.get_build_env()
#assert be['VAR'] == 'foo', be['VAR']
- if not hasattr(types, 'UnicodeType'):
+ try: unicode
+ except NameError:
uni = str
else:
uni = unicode
diff --git a/src/engine/SCons/Conftest.py b/src/engine/SCons/Conftest.py
index 9221e2f..04a6bc2 100644
--- a/src/engine/SCons/Conftest.py
+++ b/src/engine/SCons/Conftest.py
@@ -729,7 +729,7 @@ def _Have(context, key, have, comment = None):
line = "#define %s 1\n" % key_up
elif have == 0:
line = "/* #undef %s */\n" % key_up
- elif type(have) == IntType:
+ elif isinstance(have, IntType):
line = "#define %s %d\n" % (key_up, have)
else:
line = "#define %s %s\n" % (key_up, str(have))
diff --git a/src/engine/SCons/Debug.py b/src/engine/SCons/Debug.py
index a6c0cb5..18e6546 100644
--- a/src/engine/SCons/Debug.py
+++ b/src/engine/SCons/Debug.py
@@ -55,9 +55,7 @@ tracked_classes = {}
def string_to_classes(s):
if s == '*':
- c = tracked_classes.keys()
- c.sort()
- return c
+ return sorted(tracked_classes.keys())
else:
return s.split()
@@ -148,21 +146,15 @@ def caller_trace(back=0):
# print a single caller and its callers, if any
def _dump_one_caller(key, file, level=0):
- l = []
- for c,v in caller_dicts[key].items():
- l.append((-v,c))
- l.sort()
leader = ' '*level
- for v,c in l:
+ for v,c in sorted([(-v,c) for c,v in caller_dicts[key].items()]):
file.write("%s %6d %s:%d(%s)\n" % ((leader,-v) + func_shorten(c[-3:])))
if c in caller_dicts:
_dump_one_caller(c, file, level+1)
# print each call tree
def dump_caller_counts(file=sys.stdout):
- keys = caller_bases.keys()
- keys.sort()
- for k in keys:
+ for k in sorted(caller_bases.keys()):
file.write("Callers of %s:%d(%s), %d calls:\n"
% (func_shorten(k) + (caller_bases[k],)))
_dump_one_caller(k, file)
diff --git a/src/engine/SCons/Defaults.py b/src/engine/SCons/Defaults.py
index 2f48d0d..f532354 100644
--- a/src/engine/SCons/Defaults.py
+++ b/src/engine/SCons/Defaults.py
@@ -42,7 +42,6 @@ import errno
import shutil
import stat
import time
-import types
import sys
import SCons.Action
@@ -373,7 +372,7 @@ def processDefines(defs):
if SCons.Util.is_List(defs):
l = []
for d in defs:
- if SCons.Util.is_List(d) or type(d) is types.TupleType:
+ if SCons.Util.is_List(d) or isinstance(d, tuple):
l.append(str(d[0]) + '=' + str(d[1]))
else:
l.append(str(d))
@@ -385,10 +384,7 @@ def processDefines(defs):
# Consequently, we have to sort the keys to ensure a
# consistent order...
l = []
- keys = defs.keys()
- keys.sort()
- for k in keys:
- v = defs[k]
+ for k,v in sorted(defs.items()):
if v is None:
l.append(str(k))
else:
diff --git a/src/engine/SCons/DefaultsTests.py b/src/engine/SCons/DefaultsTests.py
index 8534cf8..99cb120 100644
--- a/src/engine/SCons/DefaultsTests.py
+++ b/src/engine/SCons/DefaultsTests.py
@@ -27,7 +27,6 @@ import os
import os.path
import StringIO
import sys
-import types
import unittest
from UserDict import UserDict
diff --git a/src/engine/SCons/Environment.py b/src/engine/SCons/Environment.py
index 3ebba12..267b73d 100644
--- a/src/engine/SCons/Environment.py
+++ b/src/engine/SCons/Environment.py
@@ -99,7 +99,7 @@ def apply_tools(env, tools, toolpath):
return
# Filter out null tools from the list.
for tool in [_f for _f in tools if _f]:
- if SCons.Util.is_List(tool) or type(tool)==type(()):
+ if SCons.Util.is_List(tool) or isinstance(tool, tuple):
toolname = tool[0]
toolargs = tool[1] # should be a dict of kw args
tool = env.Tool(toolname, **toolargs)
diff --git a/src/engine/SCons/EnvironmentTests.py b/src/engine/SCons/EnvironmentTests.py
index b692e96..2540408 100644
--- a/src/engine/SCons/EnvironmentTests.py
+++ b/src/engine/SCons/EnvironmentTests.py
@@ -128,7 +128,7 @@ class Scanner:
class CLVar(UserList.UserList):
def __init__(self, seq):
- if type(seq) == type(''):
+ if isinstance(seq, str):
seq = seq.split()
UserList.UserList.__init__(self, seq)
def __add__(self, other):
@@ -271,8 +271,9 @@ class SubstitutionTestCase(unittest.TestCase):
assert isinstance(nodes[0], X)
assert nodes[0].name == "Util.py UtilTests.py"
- import types
- if hasattr(types, 'UnicodeType'):
+ try: unicode
+ except NameError: pass
+ else:
code = """if 1:
nodes = env.arg2nodes(u"Util.py UtilTests.py", Factory)
assert len(nodes) == 1, nodes
diff --git a/src/engine/SCons/Job.py b/src/engine/SCons/Job.py
index 5d6befe..08e37a5 100644
--- a/src/engine/SCons/Job.py
+++ b/src/engine/SCons/Job.py
@@ -189,7 +189,7 @@ class Serial:
fails to execute (i.e. execute() raises an exception), then the job will
stop."""
- while 1:
+ while True:
task = self.taskmaster.next_task()
if task is None:
@@ -242,7 +242,7 @@ else:
self.start()
def run(self):
- while 1:
+ while True:
task = self.requestQueue.get()
if task is None:
@@ -376,7 +376,7 @@ else:
jobs = 0
- while 1:
+ while True:
# Start up as many available tasks as we're
# allowed to.
while jobs < self.maxjobs:
@@ -404,7 +404,7 @@ else:
# Let any/all completed tasks finish up before we go
# back and put the next batch of tasks on the queue.
- while 1:
+ while True:
task, ok = self.tp.get()
jobs = jobs - 1
diff --git a/src/engine/SCons/JobTests.py b/src/engine/SCons/JobTests.py
index afa00fb..85708ad 100644
--- a/src/engine/SCons/JobTests.py
+++ b/src/engine/SCons/JobTests.py
@@ -527,8 +527,8 @@ if __name__ == "__main__":
result = runner.run(suite())
if (len(result.failures) == 0
and len(result.errors) == 1
- and type(result.errors[0][0]) == SerialTestCase
- and type(result.errors[0][1][0]) == NoThreadsException):
+ and isinstance(result.errors[0][0], SerialTestCase)
+ and isinstance(result.errors[0][1][0], NoThreadsException)):
sys.exit(2)
elif not result.wasSuccessful():
sys.exit(1)
diff --git a/src/engine/SCons/Node/FS.py b/src/engine/SCons/Node/FS.py
index 705e0bc..e5b8147 100644
--- a/src/engine/SCons/Node/FS.py
+++ b/src/engine/SCons/Node/FS.py
@@ -1682,10 +1682,7 @@ class Dir(Base):
"""Return content signatures and names of all our children
separated by new-lines. Ensure that the nodes are sorted."""
contents = []
- name_cmp = lambda a, b: cmp(a.name, b.name)
- sorted_children = self.children()[:]
- sorted_children.sort(name_cmp)
- for node in sorted_children:
+ for node in sorted(self.children(), key=lambda t: t.name):
contents.append('%s %s\n' % (node.get_csig(), node.name))
return ''.join(contents)
@@ -1952,9 +1949,8 @@ class Dir(Base):
"""
dirname, basename = os.path.split(pathname)
if not dirname:
- result = self._glob1(basename, ondisk, source, strings)
- result.sort(lambda a, b: cmp(str(a), str(b)))
- return result
+ return sorted(self._glob1(basename, ondisk, source, strings),
+ key=lambda t: str(t))
if has_glob_magic(dirname):
list = self.glob(dirname, ondisk, source, strings=False)
else:
diff --git a/src/engine/SCons/Node/FSTests.py b/src/engine/SCons/Node/FSTests.py
index af7638d..e68b389 100644
--- a/src/engine/SCons/Node/FSTests.py
+++ b/src/engine/SCons/Node/FSTests.py
@@ -1722,8 +1722,7 @@ class DirTestCase(_tempdirTestCase):
fs.Dir(os.path.join('ddd', 'd1', 'f4'))
fs.Dir(os.path.join('ddd', 'd1', 'f5'))
dir.scan()
- kids = [x.path for x in dir.children(None)]
- kids.sort()
+ kids = sorted([x.path for x in dir.children(None)])
assert kids == [os.path.join('ddd', 'd1'),
os.path.join('ddd', 'f1'),
os.path.join('ddd', 'f2'),
@@ -1768,14 +1767,12 @@ class DirTestCase(_tempdirTestCase):
fs.File(os.path.join('ddd', 'f1'))
dir.scan()
- kids = [x.path for x in dir.children()]
- kids.sort()
+ kids = sorted([x.path for x in dir.children()])
assert kids == [os.path.join('ddd', 'f1')], kids
fs.File(os.path.join('ddd', 'f2'))
dir.scan()
- kids = [x.path for x in dir.children()]
- kids.sort()
+ kids = sorted([x.path for x in dir.children()])
assert kids == [os.path.join('ddd', 'f1'),
os.path.join('ddd', 'f2')], kids
@@ -2240,8 +2237,7 @@ class GlobTestCase(_tempdirTestCase):
strings_kwargs = copy.copy(kwargs)
strings_kwargs['strings'] = True
for input, string_expect, node_expect in cases:
- r = self.fs.Glob(input, **strings_kwargs)
- r.sort()
+ r = sorted(self.fs.Glob(input, **strings_kwargs))
assert r == string_expect, "Glob(%s, strings=True) expected %s, got %s" % (input, string_expect, r)
# Now execute all of the cases without string=True and look for
@@ -2256,13 +2252,12 @@ class GlobTestCase(_tempdirTestCase):
r.sort(lambda a,b: cmp(a.path, b.path))
result = []
for n in node_expect:
- if type(n) == type(''):
+ if isinstance(n, str):
n = self.fs.Entry(n)
result.append(n)
fmt = lambda n: "%s %s" % (repr(n), repr(str(n)))
else:
- r = list(map(str, r))
- r.sort()
+ r = sorted(map(str, r))
result = string_expect
fmt = lambda n: n
if r != result:
diff --git a/src/engine/SCons/Node/NodeTests.py b/src/engine/SCons/Node/NodeTests.py
index 0784237..6b76e9a 100644
--- a/src/engine/SCons/Node/NodeTests.py
+++ b/src/engine/SCons/Node/NodeTests.py
@@ -27,7 +27,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import os
import re
import sys
-import types
import unittest
import UserList
@@ -50,7 +49,7 @@ def _actionAppend(a1, a2):
all.append(curr_a)
elif isinstance(curr_a, MyListAction):
all.extend(curr_a.list)
- elif type(curr_a) == type([1,2]):
+ elif isinstance(curr_a, list):
all.extend(curr_a)
else:
raise 'Cannot Combine Actions'
diff --git a/src/engine/SCons/Node/__init__.py b/src/engine/SCons/Node/__init__.py
index c25c955..455487e 100644
--- a/src/engine/SCons/Node/__init__.py
+++ b/src/engine/SCons/Node/__init__.py
@@ -136,8 +136,7 @@ class NodeInfoBase:
try:
field_list = self.field_list
except AttributeError:
- field_list = self.__dict__.keys()
- field_list.sort()
+ field_list = sorted(self.__dict__.keys())
fields = []
for field in field_list:
try:
diff --git a/src/engine/SCons/SConf.py b/src/engine/SCons/SConf.py
index bd67ab2..e8b6c0e 100644
--- a/src/engine/SCons/SConf.py
+++ b/src/engine/SCons/SConf.py
@@ -33,7 +33,6 @@ import re
import StringIO
import sys
import traceback
-import types
import SCons.Action
import SCons.Builder
@@ -154,9 +153,8 @@ def _stringSource( target, source, env ):
return (str(target[0]) + ' <-\n |' +
source[0].get_contents().replace( '\n', "\n |" ) )
-# python 2.2 introduces types.BooleanType
-BooleanTypes = [types.IntType]
-if hasattr(types, 'BooleanType'): BooleanTypes.append(types.BooleanType)
+# python 2.2 introduces bool
+BooleanTypes = [int, bool]
class SConfBuildInfo(SCons.Node.FS.FileBuildInfo):
"""
@@ -790,7 +788,7 @@ class CheckContext:
text = "yes"
else:
text = "no"
- elif type(res) == types.StringType:
+ elif isinstance(res, str):
text = res
else:
raise TypeError, "Expected string, int or bool, got " + str(type(res))
diff --git a/src/engine/SCons/SConfTests.py b/src/engine/SCons/SConfTests.py
index d0da84a..26f21f3 100644
--- a/src/engine/SCons/SConfTests.py
+++ b/src/engine/SCons/SConfTests.py
@@ -61,7 +61,7 @@ class SConfTestCase(unittest.TestCase):
for n in sys.modules.keys():
if n.split('.')[0] == 'SCons' and n[:12] != 'SCons.compat':
m = sys.modules[n]
- if type(m) is ModuleType:
+ if isinstance(m, ModuleType):
# if this is really a scons module, clear its namespace
del sys.modules[n]
m.__dict__.clear()
diff --git a/src/engine/SCons/SConsign.py b/src/engine/SCons/SConsign.py
index a87eeeb..bd32278 100644
--- a/src/engine/SCons/SConsign.py
+++ b/src/engine/SCons/SConsign.py
@@ -202,7 +202,7 @@ class DB(Base):
else:
try:
self.entries = cPickle.loads(rawentries)
- if type(self.entries) is not type({}):
+ if not isinstance(self.entries, dict):
self.entries = {}
raise TypeError
except KeyboardInterrupt:
@@ -261,7 +261,7 @@ class Dir(Base):
return
self.entries = cPickle.load(fp)
- if type(self.entries) is not type({}):
+ if not isinstance(self.entries, dict):
self.entries = {}
raise TypeError
diff --git a/src/engine/SCons/Scanner/CTests.py b/src/engine/SCons/Scanner/CTests.py
index e92af24..2869d3b 100644
--- a/src/engine/SCons/Scanner/CTests.py
+++ b/src/engine/SCons/Scanner/CTests.py
@@ -190,7 +190,7 @@ class DummyEnvironment(UserDict.UserDict):
return [[strSubst]]
def subst_path(self, path, target=None, source=None, conv=None):
- if type(path) != type([]):
+ if not isinstance(path, list):
path = [path]
return list(map(self.subst, path))
diff --git a/src/engine/SCons/Scanner/Dir.py b/src/engine/SCons/Scanner/Dir.py
index 6b7f05b..3a0767a 100644
--- a/src/engine/SCons/Scanner/Dir.py
+++ b/src/engine/SCons/Scanner/Dir.py
@@ -101,8 +101,7 @@ def scan_in_memory(node, env, path=()):
# mixed Node types (Dirs and Files, for example) has a Dir as
# the first entry.
return []
- entry_list = list(filter(do_not_scan, entries.keys()))
- entry_list.sort()
+ entry_list = sorted(filter(do_not_scan, entries.keys()))
return [entries[n] for n in entry_list]
# Local Variables:
diff --git a/src/engine/SCons/Scanner/DirTests.py b/src/engine/SCons/Scanner/DirTests.py
index 0ad1cfe..1e45e26 100644
--- a/src/engine/SCons/Scanner/DirTests.py
+++ b/src/engine/SCons/Scanner/DirTests.py
@@ -25,7 +25,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import os.path
import sys
-import types
import unittest
import TestCmd
diff --git a/src/engine/SCons/Scanner/Fortran.py b/src/engine/SCons/Scanner/Fortran.py
index fd6a014..74f44bc 100644
--- a/src/engine/SCons/Scanner/Fortran.py
+++ b/src/engine/SCons/Scanner/Fortran.py
@@ -123,9 +123,7 @@ class F90Scanner(SCons.Scanner.Classic):
sortkey = self.sort_key(dep)
nodes.append((sortkey, n))
- nodes.sort()
- nodes = [pair[1] for pair in nodes]
- return nodes
+ return [pair[1] for pair in sorted(nodes)]
def FortranScan(path_variable="FORTRANPATH"):
"""Return a prototype Scanner instance for scanning source files
diff --git a/src/engine/SCons/Scanner/FortranTests.py b/src/engine/SCons/Scanner/FortranTests.py
index 0380e87..b75da58 100644
--- a/src/engine/SCons/Scanner/FortranTests.py
+++ b/src/engine/SCons/Scanner/FortranTests.py
@@ -238,7 +238,7 @@ class DummyEnvironment:
return arg
def subst_path(self, path, target=None, source=None, conv=None):
- if type(path) != type([]):
+ if not isinstance(path, list):
path = [path]
return list(map(self.subst, path))
diff --git a/src/engine/SCons/Scanner/IDLTests.py b/src/engine/SCons/Scanner/IDLTests.py
index 26b3956..096fc9f 100644
--- a/src/engine/SCons/Scanner/IDLTests.py
+++ b/src/engine/SCons/Scanner/IDLTests.py
@@ -203,7 +203,7 @@ class DummyEnvironment:
return arg
def subst_path(self, path, target=None, source=None, conv=None):
- if type(path) != type([]):
+ if not isinstance(path, list):
path = [path]
return list(map(self.subst, path))
diff --git a/src/engine/SCons/Scanner/LaTeX.py b/src/engine/SCons/Scanner/LaTeX.py
index f3085d1..622f2a3 100644
--- a/src/engine/SCons/Scanner/LaTeX.py
+++ b/src/engine/SCons/Scanner/LaTeX.py
@@ -365,10 +365,7 @@ class LaTeX(SCons.Scanner.Base):
# recurse down
queue.extend( self.scan(n) )
- #
- nodes.sort()
- nodes = [pair[1] for pair in nodes]
- return nodes
+ return [pair[1] for pair in sorted(nodes)]
# Local Variables:
# tab-width:4
diff --git a/src/engine/SCons/Scanner/LaTeXTests.py b/src/engine/SCons/Scanner/LaTeXTests.py
index ac978cf..4ded0b8 100644
--- a/src/engine/SCons/Scanner/LaTeXTests.py
+++ b/src/engine/SCons/Scanner/LaTeXTests.py
@@ -25,7 +25,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import os.path
import sys
-import types
import unittest
import UserDict
@@ -85,7 +84,7 @@ class DummyEnvironment(UserDict.UserDict):
return [[strSubst]]
def subst_path(self, path, target=None, source=None, conv=None):
- if type(path) != type([]):
+ if not isinstance(path, list):
path = [path]
return list(map(self.subst, path))
diff --git a/src/engine/SCons/Scanner/ProgTests.py b/src/engine/SCons/Scanner/ProgTests.py
index ee62ca7..2b02c90 100644
--- a/src/engine/SCons/Scanner/ProgTests.py
+++ b/src/engine/SCons/Scanner/ProgTests.py
@@ -25,7 +25,6 @@ __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import os.path
import sys
-import types
import unittest
import TestCmd
@@ -79,7 +78,7 @@ class DummyEnvironment:
return s
def subst_path(self, path, target=None, source=None, conv=None):
- if type(path) != type([]):
+ if not isinstance(path, list):
path = [path]
return list(map(self.subst, path))
@@ -101,8 +100,7 @@ class DummyNode:
return self.name
def deps_match(deps, libs):
- deps=list(map(str, deps))
- deps.sort()
+ deps=sorted(map(str, deps))
libs.sort()
return list(map(os.path.normpath, deps)) == list(map(os.path.normpath, libs))
@@ -232,7 +230,9 @@ def suite():
suite.addTest(ProgramScannerTestCase6())
suite.addTest(ProgramScannerTestCase7())
suite.addTest(ProgramScannerTestCase8())
- if hasattr(types, 'UnicodeType'):
+ try: unicode
+ except NameError: pass
+ else:
code = """if 1:
class ProgramScannerTestCase4(unittest.TestCase):
def runTest(self):
diff --git a/src/engine/SCons/Scanner/RCTests.py b/src/engine/SCons/Scanner/RCTests.py
index a20c919..60af3b4 100644
--- a/src/engine/SCons/Scanner/RCTests.py
+++ b/src/engine/SCons/Scanner/RCTests.py
@@ -86,7 +86,7 @@ class DummyEnvironment(UserDict.UserDict):
return strSubst
def subst_path(self, path, target=None, source=None, conv=None):
- if type(path) != type([]):
+ if not isinstance(path, list):
path = [path]
return list(map(self.subst, path))
@@ -112,10 +112,8 @@ if os.path.normcase('foo') == os.path.normcase('FOO'):
my_normpath = os.path.normcase
def deps_match(self, deps, headers):
- scanned = list(map(my_normpath, list(map(str, deps))))
- expect = list(map(my_normpath, headers))
- scanned.sort()
- expect.sort()
+ scanned = sorted(map(my_normpath, list(map(str, deps))))
+ expect = sorted(map(my_normpath, headers))
self.failUnless(scanned == expect, "expect %s != scanned %s" % (expect, scanned))
# define some tests:
diff --git a/src/engine/SCons/Scanner/ScannerTests.py b/src/engine/SCons/Scanner/ScannerTests.py
index d89fb14..500ce1a 100644
--- a/src/engine/SCons/Scanner/ScannerTests.py
+++ b/src/engine/SCons/Scanner/ScannerTests.py
@@ -48,7 +48,7 @@ class DummyEnvironment(UserDict.UserDict):
return [self.data[strSubst[1:]]]
return [[strSubst]]
def subst_path(self, path, target=None, source=None, conv=None):
- if type(path) != type([]):
+ if not isinstance(path, list):
path = [path]
return list(map(self.subst, path))
def get_factory(self, factory):
@@ -134,7 +134,7 @@ class BaseTestCase(unittest.TestCase):
self.failUnless(self.env == env, "the environment was passed incorrectly")
self.failUnless(scanned_strs == deps, "the dependencies were returned incorrectly")
for d in scanned:
- self.failUnless(type(d) != type(""), "got a string in the dependencies")
+ self.failUnless(not isinstance(d, str), "got a string in the dependencies")
if len(args) > 0:
self.failUnless(self.arg == args[0], "the argument was passed incorrectly")
diff --git a/src/engine/SCons/Scanner/__init__.py b/src/engine/SCons/Scanner/__init__.py
index be08256..3cfe4b7 100644
--- a/src/engine/SCons/Scanner/__init__.py
+++ b/src/engine/SCons/Scanner/__init__.py
@@ -378,12 +378,9 @@ class Classic(Current):
SCons.Warnings.warn(SCons.Warnings.DependencyWarning,
"No dependency generated for file: %s (included from: %s) -- file not found" % (i, node))
else:
- sortkey = self.sort_key(include)
- nodes.append((sortkey, n))
+ nodes.append((self.sort_key(include), n))
- nodes.sort()
- nodes = [pair[1] for pair in nodes]
- return nodes
+ return [pair[1] for pair in sorted(nodes)]
class ClassicCPP(Classic):
"""
diff --git a/src/engine/SCons/Script/Main.py b/src/engine/SCons/Script/Main.py
index 7173f1b..55ac598 100644
--- a/src/engine/SCons/Script/Main.py
+++ b/src/engine/SCons/Script/Main.py
@@ -316,11 +316,7 @@ class CleanTask(SCons.Taskmaster.AlwaysTask):
display("Removed " + pathstr)
elif os.path.isdir(path) and not os.path.islink(path):
# delete everything in the dir
- entries = os.listdir(path)
- # Sort for deterministic output (os.listdir() Can
- # return entries in a random order).
- entries.sort()
- for e in entries:
+ for e in sorted(os.listdir(path)):
p = os.path.join(path, e)
s = os.path.join(pathstr, e)
if os.path.isfile(p):
@@ -508,8 +504,6 @@ class CountStats(Stats):
for n, c in s:
stats_table[n][i] = c
i = i + 1
- keys = stats_table.keys()
- keys.sort()
self.outfp.write("Object counts:\n")
pre = [" "]
post = [" %s\n"]
@@ -520,7 +514,7 @@ class CountStats(Stats):
labels.append(("", "Class"))
self.outfp.write(fmt1 % tuple([x[0] for x in labels]))
self.outfp.write(fmt1 % tuple([x[1] for x in labels]))
- for k in keys:
+ for k in sorted(stats_table.keys()):
r = stats_table[k][:l] + [k]
self.outfp.write(fmt2 % tuple(r))
@@ -1228,7 +1222,7 @@ def _exec_main(parser, values):
options, args = parser.parse_args(all_args, values)
- if type(options.debug) == type([]) and "pdb" in options.debug:
+ if isinstance(options.debug, list) and "pdb" in options.debug:
import pdb
pdb.Pdb().runcall(_main, parser)
elif options.profile_file:
diff --git a/src/engine/SCons/Script/SConscript.py b/src/engine/SCons/Script/SConscript.py
index 1021921..c55d220 100644
--- a/src/engine/SCons/Script/SConscript.py
+++ b/src/engine/SCons/Script/SConscript.py
@@ -51,7 +51,6 @@ import os.path
import re
import sys
import traceback
-import types
import UserList
# The following variables used to live in this module. Some
@@ -629,7 +628,7 @@ def BuildDefaultGlobals():
import SCons.Script
d = SCons.Script.__dict__
def not_a_module(m, d=d, mtype=type(SCons.Script)):
- return type(d[m]) != mtype
+ return not isinstance(d[m], mtype)
for m in filter(not_a_module, dir(SCons.Script)):
GlobalDict[m] = d[m]
diff --git a/src/engine/SCons/Subst.py b/src/engine/SCons/Subst.py
index 936348a..9888e8d 100644
--- a/src/engine/SCons/Subst.py
+++ b/src/engine/SCons/Subst.py
@@ -31,7 +31,6 @@ from __future__ import generators ### KEEP FOR COMPATIBILITY FIXERS
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import re
-import types
import UserList
import UserString
@@ -399,7 +398,7 @@ def scons_subst(strSubst, env, mode=SUBST_RAW, target=None, source=None, gvars={
handles separating command lines into lists of arguments, so see
that function if that's what you're looking for.
"""
- if type(strSubst) == types.StringType and strSubst.find('$') < 0:
+ if isinstance(strSubst, str) and strSubst.find('$') < 0:
return strSubst
class StringSubber:
@@ -870,7 +869,7 @@ def scons_subst_once(strSubst, env, key):
We do this with some straightforward, brute-force code here...
"""
- if type(strSubst) == types.StringType and strSubst.find('$') < 0:
+ if isinstance(strSubst, str) and strSubst.find('$') < 0:
return strSubst
matchlist = ['$' + key, '${' + key + '}']
diff --git a/src/engine/SCons/SubstTests.py b/src/engine/SCons/SubstTests.py
index b587dfa..2eb91ca 100644
--- a/src/engine/SCons/SubstTests.py
+++ b/src/engine/SCons/SubstTests.py
@@ -29,7 +29,6 @@ import os
import os.path
import StringIO
import sys
-import types
import unittest
from UserDict import UserDict
@@ -150,7 +149,7 @@ class SubstTestCase(unittest.TestCase):
def _defines(defs):
l = []
for d in defs:
- if SCons.Util.is_List(d) or type(d) is types.TupleType:
+ if SCons.Util.is_List(d) or isinstance(d, tuple):
l.append(str(d[0]) + '=' + str(d[1]))
else:
l.append(str(d))
diff --git a/src/engine/SCons/Taskmaster.py b/src/engine/SCons/Taskmaster.py
index 66bcdfa..b2c4204 100644
--- a/src/engine/SCons/Taskmaster.py
+++ b/src/engine/SCons/Taskmaster.py
@@ -737,7 +737,7 @@ class Taskmaster:
T = self.trace
if T: T.write('\n' + self.trace_message('Looking for a node to evaluate'))
- while 1:
+ while True:
node = self.next_candidate()
if node is None:
if T: T.write(self.trace_message('No candidate anymore.') + '\n')
@@ -952,7 +952,7 @@ class Taskmaster:
T.write(self.trace_message(' removing node %s from the pending children set\n' %
self.trace_node(n)))
try:
- while 1:
+ while True:
try:
node = to_visit.pop()
except AttributeError:
diff --git a/src/engine/SCons/TaskmasterTests.py b/src/engine/SCons/TaskmasterTests.py
index 4a0e13a..65d10b5 100644
--- a/src/engine/SCons/TaskmasterTests.py
+++ b/src/engine/SCons/TaskmasterTests.py
@@ -910,7 +910,7 @@ class TaskmasterTestCase(unittest.TestCase):
assert e.errstr == "OtherError : ", e.errstr
assert len(e.exc_info) == 3, e.exc_info
exc_traceback = sys.exc_info()[2]
- assert type(e.exc_info[2]) == type(exc_traceback), e.exc_info[2]
+ assert isinstance(e.exc_info[2], type(exc_traceback)), e.exc_info[2]
else:
raise TestFailed, "did not catch expected BuildError"
diff --git a/src/engine/SCons/Tool/intelc.py b/src/engine/SCons/Tool/intelc.py
index e193695..1cc1312 100644
--- a/src/engine/SCons/Tool/intelc.py
+++ b/src/engine/SCons/Tool/intelc.py
@@ -243,9 +243,7 @@ def get_all_compiler_versions():
m = re.search(r'([0-9.]+)$', d)
if m:
versions.append(m.group(1))
- versions = uniquify(versions) # remove dups
- versions.sort(vercmp)
- return versions
+ return sorted(uniquify(versions)) # remove dups
def get_intel_compiler_top(version, abi):
"""
diff --git a/src/engine/SCons/Tool/javac.py b/src/engine/SCons/Tool/javac.py
index d080af5..ef4bd5b 100644
--- a/src/engine/SCons/Tool/javac.py
+++ b/src/engine/SCons/Tool/javac.py
@@ -74,10 +74,7 @@ def emit_java_classes(target, source, env):
elif isinstance(entry, SCons.Node.FS.Dir):
result = SCons.Util.OrderedDict()
def visit(arg, dirname, names, dirnode=entry.rdir()):
- java_files = [n for n in names if _my_normcase(n[-len(js):]) == js]
- # The on-disk entries come back in arbitrary order. Sort
- # them so our target and source lists are determinate.
- java_files.sort()
+ java_files = sorted([n for n in names if _my_normcase(n[-len(js):]) == js])
mydir = dirnode.Dir(dirname)
java_paths = [mydir.File(f) for f in java_files]
for jp in java_paths:
diff --git a/src/engine/SCons/Tool/msvs.py b/src/engine/SCons/Tool/msvs.py
index 57098a8..c5e93ac 100644
--- a/src/engine/SCons/Tool/msvs.py
+++ b/src/engine/SCons/Tool/msvs.py
@@ -291,8 +291,6 @@ class _DSPGenerator:
self.sources[t[0]].append(self.env[t[1]])
for n in sourcenames:
- # TODO(1.5):
- #self.sources[n].sort(lambda a, b: cmp(a.lower(), b.lower()))
self.sources[n].sort(lambda a, b: cmp(a.lower(), b.lower()))
def AddConfig(self, variant, buildtarget, outdir, runfile, cmdargs, dspfile=dspfile):
@@ -352,8 +350,7 @@ class _GenerateV6DSP(_DSPGenerator):
def PrintHeader(self):
# pick a default config
- confkeys = self.configs.keys()
- confkeys.sort()
+ confkeys = sorted(self.configs.keys())
name = self.name
confkey = confkeys[0]
@@ -373,8 +370,7 @@ class _GenerateV6DSP(_DSPGenerator):
'# PROP Scc_LocalPath ""\n\n')
first = 1
- confkeys = self.configs.keys()
- confkeys.sort()
+ confkeys = sorted(self.configs.keys())
for kind in confkeys:
outdir = self.configs[kind].outdir
buildtarget = self.configs[kind].buildtarget
@@ -445,8 +441,6 @@ class _GenerateV6DSP(_DSPGenerator):
'Other Files': ''}
cats = categories.keys()
- # TODO(1.5):
- #cats.sort(lambda a, b: cmp(a.lower(), b.lower()))
cats.sort(lambda a, b: cmp(a.lower(), b.lower()))
for kind in cats:
if not self.sources[kind]:
@@ -649,8 +643,7 @@ class _GenerateV7DSP(_DSPGenerator):
def PrintProject(self):
self.file.write('\t<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
@@ -704,8 +697,6 @@ class _GenerateV7DSP(_DSPGenerator):
def printSources(self, hierarchy, commonprefix):
sorteditems = hierarchy.items()
- # TODO(1.5):
- #sorteditems.sort(lambda a, b: cmp(a[0].lower(), b[0].lower()))
sorteditems.sort(lambda a, b: cmp(a[0].lower(), b[0].lower()))
# First folders, then files
@@ -737,8 +728,6 @@ class _GenerateV7DSP(_DSPGenerator):
self.file.write('\t<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:
@@ -1007,8 +996,7 @@ class _GenerateV7DSW(_DSWGenerator):
else:
self.file.write('\tGlobalSection(SolutionConfiguration) = preSolution\n')
- confkeys = self.configs.keys()
- confkeys.sort()
+ confkeys = sorted(self.configs.keys())
cnt = 0
for name in confkeys:
variant = self.configs[name].variant
diff --git a/src/engine/SCons/Tool/mwcc.py b/src/engine/SCons/Tool/mwcc.py
index c720956..8f1201a 100644
--- a/src/engine/SCons/Tool/mwcc.py
+++ b/src/engine/SCons/Tool/mwcc.py
@@ -99,7 +99,7 @@ def find_versions():
product_key = SCons.Util.RegOpenKeyEx(HLM, product)
i = 0
- while 1:
+ while True:
name = product + '\\' + SCons.Util.RegEnumKey(product_key, i)
name_key = SCons.Util.RegOpenKeyEx(HLM, name)
diff --git a/src/engine/SCons/Util.py b/src/engine/SCons/Util.py
index a373863..f8bac89 100644
--- a/src/engine/SCons/Util.py
+++ b/src/engine/SCons/Util.py
@@ -42,11 +42,14 @@ from UserString import UserString
# Don't "from types import ..." these because we need to get at the
# types module later to look for UnicodeType.
-DictType = types.DictType
+DictType = dict
InstanceType = types.InstanceType
-ListType = types.ListType
-StringType = types.StringType
-TupleType = types.TupleType
+ListType = list
+StringType = str
+TupleType = tuple
+try: unicode
+except NameError: UnicodeType = None
+else: UnicodeType = unicode
def dictify(keys, values, result={}):
for k, v in zip(keys, values):
@@ -343,7 +346,7 @@ except TypeError:
t = type(obj)
return t is TupleType
- if hasattr(types, 'UnicodeType'):
+ if UnicodeType is not None:
def is_String(obj):
t = type(obj)
return t is StringType \
@@ -398,8 +401,7 @@ except TypeError:
# to_String_for_signature() will use a for_signature() method if the
# specified object has one.
#
- if hasattr(types, 'UnicodeType'):
- UnicodeType = types.UnicodeType
+ if UnicodeType is not None:
def to_String(s):
if isinstance(s, UserString):
t = type(s.data)
@@ -595,15 +597,15 @@ def _semi_deepcopy_dict(x):
# Doesn't seem like we need to, but we'll comment it just in case.
copy[key] = semi_deepcopy(val)
return copy
-d[types.DictionaryType] = _semi_deepcopy_dict
+d[dict] = _semi_deepcopy_dict
def _semi_deepcopy_list(x):
return list(map(semi_deepcopy, x))
-d[types.ListType] = _semi_deepcopy_list
+d[list] = _semi_deepcopy_list
def _semi_deepcopy_tuple(x):
return tuple(map(semi_deepcopy, x))
-d[types.TupleType] = _semi_deepcopy_tuple
+d[tuple] = _semi_deepcopy_tuple
def _semi_deepcopy_inst(x):
if hasattr(x, '__semi_deepcopy__'):
@@ -1220,8 +1222,7 @@ def unique(s):
# sort functions in all languages or libraries, so this approach
# is more effective in Python than it may be elsewhere.
try:
- t = list(s)
- t.sort()
+ t = sorted(s)
except TypeError:
pass # move on to the next method
else:
@@ -1291,7 +1292,7 @@ class LogicalLines:
def readline(self):
result = []
- while 1:
+ while True:
line = self.fileobj.readline()
if not line:
break
@@ -1304,7 +1305,7 @@ class LogicalLines:
def readlines(self):
result = []
- while 1:
+ while True:
line = self.readline()
if not line:
break
@@ -1545,7 +1546,7 @@ else:
def MD5filesignature(fname, chunksize=65536):
m = hashlib.md5()
f = open(fname, "rb")
- while 1:
+ while True:
blck = f.read(chunksize)
if not blck:
break
diff --git a/src/engine/SCons/UtilTests.py b/src/engine/SCons/UtilTests.py
index 670fc83..ad27127 100644
--- a/src/engine/SCons/UtilTests.py
+++ b/src/engine/SCons/UtilTests.py
@@ -27,7 +27,6 @@ import os
import os.path
import StringIO
import sys
-import types
import unittest
from UserDict import UserDict
@@ -38,6 +37,10 @@ import SCons.Errors
from SCons.Util import *
+try: unicode
+except NameError: HasUnicode = False
+else: HasUnicode = True
+
class OutBuffer:
def __init__(self):
self.buffer = ""
@@ -214,7 +217,7 @@ class UtilTestCase(unittest.TestCase):
assert not is_Dict([])
assert not is_Dict(())
assert not is_Dict("")
- if hasattr(types, 'UnicodeType'):
+ if HasUnicode:
exec "assert not is_Dict(u'')"
def test_is_List(self):
@@ -231,12 +234,12 @@ class UtilTestCase(unittest.TestCase):
assert not is_List(())
assert not is_List({})
assert not is_List("")
- if hasattr(types, 'UnicodeType'):
+ if HasUnicode:
exec "assert not is_List(u'')"
def test_is_String(self):
assert is_String("")
- if hasattr(types, 'UnicodeType'):
+ if HasUnicode:
exec "assert is_String(u'')"
try:
import UserString
@@ -267,7 +270,7 @@ class UtilTestCase(unittest.TestCase):
assert not is_Tuple([])
assert not is_Tuple({})
assert not is_Tuple("")
- if hasattr(types, 'UnicodeType'):
+ if HasUnicode:
exec "assert not is_Tuple(u'')"
def test_to_String(self):
@@ -289,19 +292,19 @@ class UtilTestCase(unittest.TestCase):
assert to_String(s2) == s2, s2
assert to_String(s2) == 'foo', s2
- if hasattr(types, 'UnicodeType'):
+ if HasUnicode:
s3=UserString.UserString(unicode('bar'))
assert to_String(s3) == s3, s3
assert to_String(s3) == unicode('bar'), s3
- assert type(to_String(s3)) is types.UnicodeType, \
+ assert isinstance(to_String(s3), unicode), \
type(to_String(s3))
except ImportError:
pass
- if hasattr(types, 'UnicodeType'):
+ if HasUnicode:
s4 = unicode('baz')
assert to_String(s4) == unicode('baz'), to_String(s4)
- assert type(to_String(s4)) is types.UnicodeType, \
+ assert isinstance(to_String(s4), unicode), \
type(to_String(s4))
def test_WhereIs(self):
diff --git a/src/engine/SCons/Variables/ListVariable.py b/src/engine/SCons/Variables/ListVariable.py
index 36b530a..5980f33 100644
--- a/src/engine/SCons/Variables/ListVariable.py
+++ b/src/engine/SCons/Variables/ListVariable.py
@@ -63,8 +63,7 @@ import SCons.Util
class _ListVariable(UserList.UserList):
def __init__(self, initlist=[], allowedElems=[]):
UserList.UserList.__init__(self, [_f for _f in initlist if _f])
- self.allowedElems = allowedElems[:]
- self.allowedElems.sort()
+ self.allowedElems = sorted(allowedElems)
def __cmp__(self, other):
raise NotImplementedError
diff --git a/src/engine/SCons/Variables/__init__.py b/src/engine/SCons/Variables/__init__.py
index 27f694f..09d4e29 100644
--- a/src/engine/SCons/Variables/__init__.py
+++ b/src/engine/SCons/Variables/__init__.py
@@ -123,7 +123,7 @@ class Variables:
putting it in the environment.
"""
- if SCons.Util.is_List(key) or type(key) == type(()):
+ if SCons.Util.is_List(key) or isinstance(key, tuple):
self._do_add(*key)
return
@@ -284,8 +284,7 @@ class Variables:
"""
if sort:
- options = self.options[:]
- options.sort(lambda x,y: sort(x.key,y.key))
+ options = sorted(self.options, cmp=lambda x,y: sort(x.key,y.key))
else:
options = self.options
diff --git a/src/engine/SCons/compat/_scons_UserString.py b/src/engine/SCons/compat/_scons_UserString.py
index 785a260..dfc2b30 100644
--- a/src/engine/SCons/compat/_scons_UserString.py
+++ b/src/engine/SCons/compat/_scons_UserString.py
@@ -33,17 +33,13 @@ In particular, it does not necessarily contain all of the methods found
in later versions.
"""
-import types
-
-StringType = types.StringType
-
-if hasattr(types, 'UnicodeType'):
- UnicodeType = types.UnicodeType
+try: unicode
+except NameError:
def is_String(obj):
- return type(obj) in (StringType, UnicodeType)
+ return type(obj) is str
else:
def is_String(obj):
- return type(obj) is StringType
+ return type(obj) in (str, unicode)
class UserString:
def __init__(self, seq):
diff --git a/src/engine/SCons/compat/_scons_optparse.py b/src/engine/SCons/compat/_scons_optparse.py
index 5db4c90..ac5b448 100644
--- a/src/engine/SCons/compat/_scons_optparse.py
+++ b/src/engine/SCons/compat/_scons_optparse.py
@@ -643,8 +643,7 @@ class Option:
else:
setattr(self, attr, None)
if attrs:
- attrs = attrs.keys()
- attrs.sort()
+ attrs = sorted(attrs.keys())
raise OptionError(
"invalid keyword arguments: %s" % string.join(attrs, ", "),
self)
@@ -693,7 +692,7 @@ class Option:
if self.choices is None:
raise OptionError(
"must supply a list of choices for type 'choice'", self)
- elif type(self.choices) not in (types.TupleType, types.ListType):
+ elif type(self.choices) not in (tuple, list):
raise OptionError(
"choices must be a list of strings ('%s' supplied)"
% string.split(str(type(self.choices)), "'")[1], self)
@@ -737,12 +736,12 @@ class Option:
raise OptionError(
"callback not callable: %r" % self.callback, self)
if (self.callback_args is not None and
- type(self.callback_args) is not types.TupleType):
+ type(self.callback_args) is not tuple):
raise OptionError(
"callback_args, if supplied, must be a tuple: not %r"
% self.callback_args, self)
if (self.callback_kwargs is not None and
- type(self.callback_kwargs) is not types.DictType):
+ type(self.callback_kwargs) is not dict):
raise OptionError(
"callback_kwargs, if supplied, must be a dict: not %r"
% self.callback_kwargs, self)
@@ -855,14 +854,13 @@ try:
except NameError:
(True, False) = (1, 0)
-try:
- types.UnicodeType
-except AttributeError:
+try: unicode
+except NameError:
def isbasestring(x):
- return isinstance(x, types.StringType)
+ return isinstance(x, str)
else:
def isbasestring(x):
- return isinstance(x, types.StringType) or isinstance(x, types.UnicodeType)
+ return isinstance(x, str) or isinstance(x, unicode)
class Values:
@@ -879,7 +877,7 @@ class Values:
def __cmp__(self, other):
if isinstance(other, Values):
return cmp(self.__dict__, other.__dict__)
- elif isinstance(other, types.DictType):
+ elif isinstance(other, dict):
return cmp(self.__dict__, other)
else:
return -1
@@ -1040,7 +1038,7 @@ class OptionContainer:
"""add_option(Option)
add_option(opt_str, ..., kwarg=val, ...)
"""
- if type(args[0]) is types.StringType:
+ if type(args[0]) is str:
option = apply(self.option_class, args, kwargs)
elif len(args) == 1 and not kwargs:
option = args[0]
@@ -1351,7 +1349,7 @@ class OptionParser (OptionContainer):
def add_option_group(self, *args, **kwargs):
# XXX lots of overlap with OptionContainer.add_option()
- if type(args[0]) is types.StringType:
+ if type(args[0]) is str:
group = apply(OptionGroup, (self,) + args, kwargs)
elif len(args) == 1 and not kwargs:
group = args[0]
diff --git a/src/engine/SCons/compat/_scons_sets.py b/src/engine/SCons/compat/_scons_sets.py
index 12dbead..713d6e9 100644
--- a/src/engine/SCons/compat/_scons_sets.py
+++ b/src/engine/SCons/compat/_scons_sets.py
@@ -110,9 +110,9 @@ class BaseSet(object):
# __str__ is the same as __repr__
__str__ = __repr__
- def _repr(self, sorted=False):
+ def _repr(self, sort_them=False):
elements = self._data.keys()
- if sorted:
+ if sort_them:
elements.sort()
return '%s(%r)' % (self.__class__.__name__, elements)
diff --git a/src/engine/SCons/compat/builtins.py b/src/engine/SCons/compat/builtins.py
index 064415e..02b94f3 100644
--- a/src/engine/SCons/compat/builtins.py
+++ b/src/engine/SCons/compat/builtins.py
@@ -152,25 +152,19 @@ except NameError:
# we must implement the functionality of those keyword arguments
# by hand instead of passing them to list.sort().
def sorted(iterable, cmp=None, key=None, reverse=False):
- if key:
- decorated = [ (key(x), x) for x in iterable ]
- if cmp is None:
- # Pre-2.3 Python does not support list.sort(None).
- decorated.sort()
- else:
- decorated.sort(cmp)
- if reverse:
- decorated.reverse()
- result = [ t[1] for t in decorated ]
+ if key is not None:
+ result = [(key(x), x) for x in iterable]
else:
result = iterable[:]
- if cmp is None:
- # Pre-2.3 Python does not support list.sort(None).
- result.sort()
- else:
- result.sort(cmp)
- if reverse:
- result.reverse()
+ if cmp is None:
+ # Pre-2.3 Python does not support list.sort(None).
+ result.sort()
+ else:
+ result.sort(cmp)
+ if key is not None:
+ result = [t1 for t0,t1 in result]
+ if reverse:
+ result.reverse()
return result
__builtin__.sorted = sorted
diff --git a/src/engine/SCons/cpp.py b/src/engine/SCons/cpp.py
index 5ccc00e..5e159ec 100644
--- a/src/engine/SCons/cpp.py
+++ b/src/engine/SCons/cpp.py
@@ -133,8 +133,7 @@ CPP_to_Python_Ops_Sub = lambda m: CPP_to_Python_Ops_Dict[m.group(0)]
# re module, as late as version 2.2.2, empirically matches the
# "!" in "!=" first, instead of finding the longest match.
# What's up with that?
-l = CPP_to_Python_Ops_Dict.keys()
-l.sort(lambda a, b: cmp(len(b), len(a)))
+l = sorted(CPP_to_Python_Ops_Dict.keys(), cmp=lambda a, b: cmp(len(b), len(a)))
# Turn the list of keys into one regular expression that will allow us
# to substitute all of the operators at once.
diff --git a/src/engine/SCons/dblite.py b/src/engine/SCons/dblite.py
index bcb2aa0..2383f1d 100644
--- a/src/engine/SCons/dblite.py
+++ b/src/engine/SCons/dblite.py
@@ -5,7 +5,6 @@ import cPickle
import time
import shutil
import os
-import types
import __builtin__
keep_all_files = 00000
@@ -14,13 +13,13 @@ ignore_corrupt_dbfiles = 0
def corruption_warning(filename):
print "Warning: Discarding corrupt database:", filename
-if hasattr(types, 'UnicodeType'):
+try: unicode
+except NameError:
def is_string(s):
- t = type(s)
- return t is types.StringType or t is types.UnicodeType
+ return isinstance(s, str)
else:
def is_string(s):
- return type(s) is types.StringType
+ return type(s) in (str, unicode)
try:
unicode('a')
diff --git a/src/script/scons-time.py b/src/script/scons-time.py
index c75bc13..04fa573 100644
--- a/src/script/scons-time.py
+++ b/src/script/scons-time.py
@@ -59,6 +59,32 @@ except NameError:
import __builtin__
__builtin__.True = not 0
+try:
+ sorted
+except NameError:
+ # Pre-2.4 Python has no sorted() function.
+ #
+ # The pre-2.4 Python list.sort() method does not support
+ # list.sort(key=) nor list.sort(reverse=) keyword arguments, so
+ # we must implement the functionality of those keyword arguments
+ # by hand instead of passing them to list.sort().
+ def sorted(iterable, cmp=None, key=None, reverse=False):
+ if key is not None:
+ result = [(key(x), x) for x in iterable]
+ else:
+ result = iterable[:]
+ if cmp is None:
+ # Pre-2.3 Python does not support list.sort(None).
+ result.sort()
+ else:
+ result.sort(cmp)
+ if key is not None:
+ result = [t1 for t0,t1 in result]
+ if reverse:
+ result.reverse()
+ return result
+ __builtin__.sorted = sorted
+
def make_temp_file(**kw):
try:
result = tempfile.mktemp(**kw)
@@ -505,9 +531,7 @@ class SConsTimer:
"""
files = []
for a in args:
- g = glob.glob(a)
- g.sort()
- files.extend(g)
+ files.extend(sorted(glob.glob(a)))
if tail:
files = files[-tail:]
@@ -589,10 +613,7 @@ class SConsTimer:
"""
gp = Gnuplotter(self.title, self.key_location)
- indices = results.keys()
- indices.sort()
-
- for i in indices:
+ for i in sorted(results.keys()):
try:
t = self.run_titles[i]
except IndexError:
diff --git a/src/script/sconsign.py b/src/script/sconsign.py
index fb3bd5e..ac619a5 100644
--- a/src/script/sconsign.py
+++ b/src/script/sconsign.py
@@ -282,8 +282,7 @@ def nodeinfo_raw(name, ninfo, prefix=""):
try:
keys = ninfo.field_list + ['_version_id']
except AttributeError:
- keys = d.keys()
- keys.sort()
+ keys = sorted(d.keys())
l = []
for k in keys:
l.append('%s: %s' % (repr(k), repr(d.get(k))))
@@ -336,9 +335,7 @@ def printentries(entries, location):
print nodeinfo_string(name, entry.ninfo)
printfield(name, entry.binfo)
else:
- names = entries.keys()
- names.sort()
- for name in names:
+ for name in sorted(entries.keys()):
entry = entries[name]
try:
ninfo = entry.ninfo
@@ -402,9 +399,7 @@ class Do_SConsignDB:
else:
self.printentries(dir, val)
else:
- keys = db.keys()
- keys.sort()
- for dir in keys:
+ for dir in sorted(db.keys()):
self.printentries(dir, db[dir])
def printentries(self, dir, val):
diff --git a/src/test_interrupts.py b/src/test_interrupts.py
index 69e7a80..21b0dea 100644
--- a/src/test_interrupts.py
+++ b/src/test_interrupts.py
@@ -90,7 +90,7 @@ for f in files:
contents = open(os.path.join(scons_lib_dir, f)).read()
try_except_lines = {}
lastend = 0
- while 1:
+ while True:
match = tryexc_pat.search( contents, lastend )
if match is None:
break
diff --git a/src/test_pychecker.py b/src/test_pychecker.py
index fb60646..ad68965 100644
--- a/src/test_pychecker.py
+++ b/src/test_pychecker.py
@@ -90,10 +90,7 @@ for file in ignore:
del u[file]
except KeyError:
pass
-
-files = u.keys()
-
-files.sort()
+files = sorted(u.keys())
mismatches = []