Applied a number of idiomatic changes.
Uses of the 'sort()' method were converted into calls of 'sorted()' when
possible and the sorted() expression was inserted into a subsequent statement
whenever that made sense.
The statement 'while 1:' was changed to 'while True:'.
Names from the 'types' module (e.g., 'types.FooType') were converted to the
equivalent build-in type (e.g., 'foo').
Comparisons between types were changed to use 'isinstance()'.
git-svn-id: http://scons.tigris.org/svn/scons/trunk@4733
fdb21ef1-2011-0410-befe-
b5e4ea1792b1
102 files changed:
import tempfile
import time
import traceback
import tempfile
import time
import traceback
import UserList
__all__ = [
import UserList
__all__ = [
__all__.append('simple_diff')
def is_List(e):
__all__.append('simple_diff')
def is_List(e):
- return type(e) is types.ListType \
+ return isinstance(e, list) \
or isinstance(e, UserList.UserList)
try:
or isinstance(e, UserList.UserList)
try:
-if hasattr(types, 'UnicodeType'):
+try: unicode
+except NameError:
- return type(e) is types.StringType \
- or type(e) is types.UnicodeType \
- or isinstance(e, UserString)
+ return isinstance(e, str) or isinstance(e, UserString)
- return type(e) is types.StringType or isinstance(e, UserString)
+ return isinstance(e, str) \
+ or isinstance(e, unicode) \
+ or isinstance(e, UserString)
tempfile.template = 'testcmd.'
if os.name in ('posix', 'nt'):
tempfile.template = 'testcmd.'
if os.name in ('posix', 'nt'):
def match_re_dotall(lines = None, res = None):
"""
"""
def match_re_dotall(lines = None, res = None):
"""
"""
- if not type(lines) is type(""):
+ if not isinstance(lines, str):
- if not type(res) is type(""):
+ if not isinstance(res, str):
res = "\n".join(res)
s = "^" + res + "$"
try:
res = "\n".join(res)
s = "^" + res + "$"
try:
interpreter = None,
arguments = None):
if program:
interpreter = None,
arguments = None):
if program:
- if type(program) == type('') and not os.path.isabs(program):
+ if isinstance(program, str) and not os.path.isabs(program):
program = os.path.join(self._cwd, program)
else:
program = self.program
if not interpreter:
interpreter = self.interpreter
program = os.path.join(self._cwd, program)
else:
program = self.program
if not interpreter:
interpreter = self.interpreter
- if not type(program) in [type([]), type(())]:
+ if not type(program) in [list, tuple]:
program = [program]
cmd = list(program)
if interpreter:
program = [program]
cmd = list(program)
if interpreter:
- if not type(interpreter) in [type([]), type(())]:
+ if not type(interpreter) in [list, tuple]:
interpreter = [interpreter]
cmd = list(interpreter) + cmd
if arguments:
interpreter = [interpreter]
cmd = list(interpreter) + cmd
if arguments:
- if type(arguments) == type(''):
+ if isinstance(arguments, str):
arguments = arguments.split()
cmd.extend(arguments)
return cmd
arguments = arguments.split()
cmd.extend(arguments)
return cmd
import os.path
import stat
import sys
import os.path
import stat
import sys
import UserList
from TestCmd import *
import UserList
from TestCmd import *
dll_suffix = '.so'
def is_List(e):
dll_suffix = '.so'
def is_List(e):
- return type(e) is types.ListType \
+ return isinstance(e, list) \
or isinstance(e, UserList.UserList)
def is_writable(f):
or isinstance(e, UserList.UserList)
def is_writable(f):
import glob
result = []
for p in patterns:
import glob
result = []
for p in patterns:
- paths = glob.glob(p)
- paths.sort()
- result.extend(paths)
+ result.extend(sorted(glob.glob(p)))
self.QT_LIB_DIR = self.workpath(dir, 'lib')
def Qt_create_SConstruct(self, place):
self.QT_LIB_DIR = self.workpath(dir, 'lib')
def Qt_create_SConstruct(self, place):
- if type(place) is type([]):
+ if isinstance(place, list):
place = test.workpath(*place)
self.write(place, """\
if ARGUMENTS.get('noqtdir', 0): QTDIR=None
place = test.workpath(*place)
self.write(place, """\
if ARGUMENTS.get('noqtdir', 0): QTDIR=None
self._outcomes[test_id] = exit_status
def Summarize(self):
self.file.write('test_result = [\n')
self._outcomes[test_id] = exit_status
def Summarize(self):
self.file.write('test_result = [\n')
- file_names = self._outcomes.keys()
- file_names.sort()
- for file_name in file_names:
+ for file_name in sorted(self._outcomes.keys()):
exit_status = self._outcomes[file_name]
file_name = file_name.replace('\\', '/')
self.file.write(' { file_name = "%s";\n' % file_name)
exit_status = self._outcomes[file_name]
file_name = file_name.replace('\\', '/')
self.file.write(' { file_name = "%s";\n' % file_name)
"""
def __init__(self, module='__main__', defaultTest=None,
argv=None, testRunner=None):
"""
def __init__(self, module='__main__', defaultTest=None,
argv=None, testRunner=None):
- if type(module) == type(''):
+ if isinstance(module, str):
self.module = __import__(module)
for part in module.split('.')[1:]:
self.module = getattr(self.module, part)
self.module = __import__(module)
for part in module.split('.')[1:]:
self.module = getattr(self.module, part)
-aliases = packaging_flavors + [('doc', 'The SCons documentation.')]
-aliases.sort()
+aliases = sorted(packaging_flavors + [('doc', 'The SCons documentation.')])
for alias, help_text in aliases:
tw = textwrap.TextWrapper(
for alias, help_text in aliases:
tw = textwrap.TextWrapper(
try:
FunctionList
except NameError:
try:
FunctionList
except NameError:
- function_names = [x for x in locals().keys() if x[:4] == FunctionPrefix]
- function_names.sort()
+ function_names = sorted([x for x in locals().keys() if x[:4] == FunctionPrefix])
l = [locals()[f] for f in function_names]
l = [locals()[f] for f in function_names]
- FunctionList = [f for f in l if type(f) == types.FunctionType]
+ FunctionList = [f for f in l if isinstance(f, types.FunctionType)]
IterationList = [None] * Iterations
IterationList = [None] * Iterations
t = Timing(n, num, init, s)
t.timeit()
timings.append(t)
t = Timing(n, num, init, s)
t.timeit()
timings.append(t)
- l = []
- for i in timings: l.append((i.getResult(),i.name))
- l.sort()
- for i in l: print " %9.3f s %s" % i
+ for i in sorted([(i.getResult(),i.name) for i in timings]):
+ print " %9.3f s %s" % i
# Import the necessary local SCons.* modules used by some of our
# alternative implementations below, first manipulating sys.path so
# Import the necessary local SCons.* modules used by some of our
# alternative implementations below, first manipulating sys.path so
# and modified slightly for use with SCons.
class UserString:
def __init__(self, seq):
# and modified slightly for use with SCons.
class UserString:
def __init__(self, seq):
- if type(seq) == type(''):
+ if isinstance(seq, str):
self.data = seq
elif isinstance(seq, UserString):
self.data = seq.data[:]
self.data = seq
elif isinstance(seq, UserString):
self.data = seq.data[:]
__rmul__ = __mul__
InstanceType = types.InstanceType
__rmul__ = __mul__
InstanceType = types.InstanceType
-DictType = types.DictType
-ListType = types.ListType
-StringType = types.StringType
-if hasattr(types, 'UnicodeType'):
- UnicodeType = types.UnicodeType
+DictType = dict
+ListType = list
+StringType = str
+try: unicode
+except NameError:
+ UnicodeType = None
+else:
+ UnicodeType = unicode
# The original implementations, pretty straightforward checks for the
# The original implementations, pretty straightforward checks for the
# User* type.
def original_is_Dict(e):
# User* type.
def original_is_Dict(e):
- return type(e) is types.DictType or isinstance(e, UserDict)
+ return isinstance(e, dict) or isinstance(e, UserDict)
- return type(e) is types.ListType or isinstance(e, UserList)
+ return isinstance(e, list) or isinstance(e, UserList)
-if hasattr(types, 'UnicodeType'):
+if UnicodeType is not None:
def original_is_String(e):
def original_is_String(e):
- return type(e) is types.StringType \
- or type(e) is types.UnicodeType \
+ return isinstance(e, str) \
+ or isinstance(e, unicode) \
or isinstance(e, UserString)
else:
def original_is_String(e):
or isinstance(e, UserString)
else:
def original_is_String(e):
- return type(e) is types.StringType or isinstance(e, UserString)
+ return isinstance(e, str) or isinstance(e, UserString)
# type.
def checkInstanceType_is_Dict(e):
# type.
def checkInstanceType_is_Dict(e):
- return type(e) is types.DictType or \
- (type(e) is types.InstanceType and isinstance(e, UserDict))
+ return isinstance(e, dict) or \
+ (isinstance(e, types.InstanceType) and isinstance(e, UserDict))
def checkInstanceType_is_List(e):
def checkInstanceType_is_List(e):
- return type(e) is types.ListType \
- or (type(e) is types.InstanceType and isinstance(e, UserList))
+ return isinstance(e, list) \
+ or (isinstance(e, types.InstanceType) and isinstance(e, UserList))
-if hasattr(types, 'UnicodeType'):
+if UnicodeType is not None:
def checkInstanceType_is_String(e):
def checkInstanceType_is_String(e):
- return type(e) is types.StringType \
- or type(e) is types.UnicodeType \
- or (type(e) is types.InstanceType and isinstance(e, UserString))
+ return isinstance(e, str) \
+ or isinstance(e, unicode) \
+ or (isinstance(e, types.InstanceType) and isinstance(e, UserString))
else:
def checkInstanceType_is_String(e):
else:
def checkInstanceType_is_String(e):
- return type(e) is types.StringType \
- or (type(e) is types.InstanceType and isinstance(e, UserString))
+ return isinstance(e, str) \
+ or (isinstance(e, types.InstanceType) and isinstance(e, UserString))
def cache_type_e_is_Dict(e):
t = type(e)
def cache_type_e_is_Dict(e):
t = type(e)
- return t is types.DictType or \
(t is types.InstanceType and isinstance(e, UserDict))
def cache_type_e_is_List(e):
t = type(e)
(t is types.InstanceType and isinstance(e, UserDict))
def cache_type_e_is_List(e):
t = type(e)
- return t is types.ListType \
or (t is types.InstanceType and isinstance(e, UserList))
or (t is types.InstanceType and isinstance(e, UserList))
-if hasattr(types, 'UnicodeType'):
+if UnicodeType is not None:
def cache_type_e_is_String(e):
t = type(e)
def cache_type_e_is_String(e):
t = type(e)
- return t is types.StringType \
- or t is types.UnicodeType \
+ return t is str \
+ or t is unicode \
or (t is types.InstanceType and isinstance(e, UserString))
else:
def cache_type_e_is_String(e):
t = type(e)
or (t is types.InstanceType and isinstance(e, UserString))
else:
def cache_type_e_is_String(e):
t = type(e)
- return t is types.StringType \
or (t is types.InstanceType and isinstance(e, UserString))
or (t is types.InstanceType and isinstance(e, UserString))
return t is ListType \
or (t is InstanceType and isinstance(e, UserList))
return t is ListType \
or (t is InstanceType and isinstance(e, UserList))
-if hasattr(types, 'UnicodeType'):
+if UnicodeType is not None:
def global_cache_type_e_is_String(e):
t = type(e)
return t is StringType \
def global_cache_type_e_is_String(e):
t = type(e)
return t is StringType \
# to their corresponding underlying types.
instanceTypeMap = {
# to their corresponding underlying types.
instanceTypeMap = {
- UserDict : types.DictType,
- UserList : types.ListType,
- UserString : types.StringType,
+ UserDict : dict,
+ UserList : list,
+ UserString : str,
-if hasattr(types, 'UnicodeType'):
+if UnicodeType is not None:
def myType(obj):
t = type(obj)
if t is types.InstanceType:
t = instanceTypeMap.get(obj.__class__, t)
def myType(obj):
t = type(obj)
if t is types.InstanceType:
t = instanceTypeMap.get(obj.__class__, t)
- elif t is types.UnicodeType:
- t = types.StringType
+ elif t is unicode:
+ t = str
return t
else:
def myType(obj):
return t
else:
def myType(obj):
return t
def myType_is_Dict(e):
return t
def myType_is_Dict(e):
- return myType(e) is types.DictType
+ return myType(e) is dict
- return myType(e) is types.ListType
+ return myType(e) is list
- return myType(e) is types.StringType
+ return myType(e) is str
return string
def do_display(self, string):
return string
def do_display(self, string):
- if type(string) == type(()):
+ if isinstance(string, tuple):
func = string[0]
args = string[1:]
s = '%s(%s)' % (func.__name__, ', '.join(map(repr, args)))
func = string[0]
args = string[1:]
s = '%s(%s)' % (func.__name__, ', '.join(map(repr, args)))
pass
def do_execute(self, command):
pass
def do_execute(self, command):
- if type(command) == type(''):
+ if isinstance(command, str):
command = self.subst(command)
cmdargs = shlex.split(command)
if cmdargs[0] == 'cd':
command = (os.chdir,) + tuple(cmdargs[1:])
elif cmdargs[0] == 'mkdir':
command = (os.mkdir,) + tuple(cmdargs[1:])
command = self.subst(command)
cmdargs = shlex.split(command)
if cmdargs[0] == 'cd':
command = (os.chdir,) + tuple(cmdargs[1:])
elif cmdargs[0] == 'mkdir':
command = (os.mkdir,) + tuple(cmdargs[1:])
- if type(command) == type(()):
+ if isinstance(command, tuple):
func = command[0]
args = command[1:]
return func(*args)
func = command[0]
args = command[1:]
return func(*args)
def start_uses(self, attrs):
self.begin_collecting([])
def end_uses(self):
def start_uses(self, attrs):
self.begin_collecting([])
def end_uses(self):
- self.current_object.uses = ''.join(self.collect).split()
- self.current_object.uses.sort()
+ self.current_object.uses = sorted(''.join(self.collect).split())
self.end_collecting()
def start_sets(self, attrs):
self.begin_collecting([])
def end_sets(self):
self.end_collecting()
def start_sets(self, attrs):
self.begin_collecting([])
def end_sets(self):
- self.current_object.sets = ''.join(self.collect).split()
- self.current_object.sets.sort()
+ self.current_object.sets = sorted(''.join(self.collect).split())
self.end_collecting()
# Stuff for the ErrorHandler portion.
self.end_collecting()
# Stuff for the ErrorHandler portion.
self.path = path
self.entries = {}
def call_for_each_entry(self, func):
self.path = path
self.entries = {}
def call_for_each_entry(self, func):
- entries = self.entries
- names = entries.keys()
- names.sort()
- for name in names:
- func(name, entries[name])
+ for name in sorted(self.entries.keys()):
+ func(name, self.entries[name])
def lookup(dirname):
global Top, TopPath
def lookup(dirname):
global Top, TopPath
diffstr(c1[3], c2[3]) + \
' ' + classname
diffstr(c1[3], c2[3]) + \
' ' + classname
-keys = common.keys()
-keys.sort()
-for k in keys:
+for k in sorted(common.keys()):
c = common[k]
printline(c[0], c[1], k)
c = common[k]
printline(c[0], c[1], k)
-keys = c1.keys()
-keys.sort()
-for k in keys:
+for k in sorted(list(c1.keys())):
printline(c1[k], ['--']*4, k)
printline(c1[k], ['--']*4, k)
-keys = c2.keys()
-keys.sort()
-for k in keys:
+for k in sorted(list(c2.keys())):
printline(['--']*4, c2[k], k)
# Local Variables:
printline(['--']*4, c2[k], k)
# Local Variables:
u[l] = 1
for r in rlist:
u[r] = 1
u[l] = 1
for r in rlist:
u[r] = 1
- clist = [ x for x in u.keys() if x[-4:] != '.pyc' ]
- clist.sort()
- for x in clist:
+ for x in sorted([ x for x in u.keys() if x[-4:] != '.pyc' ]):
if x in llist:
if x in rlist:
do_diff(os.path.join(left, x),
if x in llist:
if x in rlist:
do_diff(os.path.join(left, x),
class ToolSurrogate:
def __init__(self, tool, variable, func, varlist):
self.tool = tool
class ToolSurrogate:
def __init__(self, tool, variable, func, varlist):
self.tool = tool
- if not type(variable) is type([]):
+ if not isinstance(variable, list):
variable = [variable]
self.variable = variable
self.func = func
variable = [variable]
self.variable = variable
self.func = func
def command_ls(args, c, test, dict):
def ls(a):
def command_ls(args, c, test, dict):
def ls(a):
- files = os.listdir(a)
- files = [x for x in files if x[0] != '.']
- files.sort()
- return [' '.join(files)]
+ return [' '.join(sorted([x for x in os.listdir(a) if x[0] != '.']))]
if args:
l = []
for a in args:
if args:
l = []
for a in args:
def outname(n, outdir=outdir):
l = []
def outname(n, outdir=outdir):
l = []
n, tail = os.path.split(n)
if not n:
break
n, tail = os.path.split(n)
if not n:
break
- #keys = os.environ.keys()
- keys = environ_keys
- keys.sort()
- for key in keys:
+ for key in sorted(environ_keys):
value = os.environ.get(key)
if value:
print " <variable>"
value = os.environ.get(key)
if value:
print " <variable>"
def outname(n, outdir=outdir):
l = []
def outname(n, outdir=outdir):
l = []
n, tail = os.path.split(n)
if not n:
break
n, tail = os.path.split(n)
if not n:
break
def display(self, command, stdout=None, stderr=None):
if not self.verbose:
return
def display(self, command, stdout=None, stderr=None):
if not self.verbose:
return
- if type(command) == type(()):
+ if isinstance(command, tuple):
func = command[0]
args = command[1:]
s = '%s(%s)' % (func.__name__, ', '.join(map(repr, args)))
func = command[0]
args = command[1:]
s = '%s(%s)' % (func.__name__, ', '.join(map(repr, args)))
- if type(command) == type([]):
+ if isinstance(command, list):
# TODO: quote arguments containing spaces
# TODO: handle meta characters?
s = ' '.join(command)
# TODO: quote arguments containing spaces
# TODO: handle meta characters?
s = ' '.join(command)
"""
if not self.active:
return 0
"""
if not self.active:
return 0
- if type(command) == type(''):
+ if isinstance(command, str):
command = self.subst(command)
cmdargs = shlex.split(command)
if cmdargs[0] == 'cd':
command = (os.chdir,) + tuple(cmdargs[1:])
command = self.subst(command)
cmdargs = shlex.split(command)
if cmdargs[0] == 'cd':
command = (os.chdir,) + tuple(cmdargs[1:])
- if type(command) == type(()):
+ if isinstance(command, tuple):
func = command[0]
args = command[1:]
return func(*args)
func = command[0]
args = command[1:]
return func(*args)
# The team members
# FIXME: These names really should be external to this script
# The team members
# FIXME: These names really should be external to this script
-team = 'Bill Greg Steven Gary Ken Brandon Sohail Jim David'.split()
-team.sort()
+team = sorted('Steven Gary Greg Ken Jim David Bill Sergey Jason'.split())
# The elements to be picked out of the issue
PickList = [
# The elements to be picked out of the issue
PickList = [
<sconstruct>
env = Environment()
<sconstruct>
env = Environment()
- dict = env.Dictionary()
- keys = dict.keys()
- keys.sort()
- for key in keys:
- print "construction variable = '%s', value = '%s'" % (key, dict[key])
+ for item in sorted(env.Dictionary().items()):
+ print "construction variable = '%s', value = '%s'" % item
if len(sys.argv) > 1:
keys = sys.argv[1:]
else:
if len(sys.argv) > 1:
keys = sys.argv[1:]
else:
- keys = os.environ.keys()
- keys.sort()
+ keys = sorted(os.environ.keys())
for key in keys:
print " " + key + "=" + os.environ[key]
</file>
for key in keys:
print " " + key + "=" + os.environ[key]
</file>
<programlisting>
env = Environment()
<programlisting>
env = Environment()
- dict = env.Dictionary()
- keys = dict.keys()
- keys.sort()
- for key in keys:
- print "construction variable = '%s', value = '%s'" % (key, dict[key])
+ for item in sorted(env.Dictionary().items()):
+ print "construction variable = '%s', value = '%s'" % item
</programlisting>
</section>
</programlisting>
</section>
if len(sys.argv) > 1:
keys = sys.argv[1:]
else:
if len(sys.argv) > 1:
keys = sys.argv[1:]
else:
- keys = os.environ.keys()
- keys.sort()
+ keys = sorted(os.environ.keys())
for key in keys:
print " " + key + "=" + os.environ[key]
</file>
for key in keys:
print " " + key + "=" + os.environ[key]
</file>
<file name="SConstruct" printme="1">
env = Environment()
d = env.ParseFlags("-I/opt/include -L/opt/lib -lfoo")
<file name="SConstruct" printme="1">
env = Environment()
d = env.ParseFlags("-I/opt/include -L/opt/lib -lfoo")
- l = d.items()
- l.sort()
- for k,v in l:
+ for k,v in sorted(d.items()):
if v:
print k, v
env.MergeFlags(d)
if v:
print k, v
env.MergeFlags(d)
<file name="SConstruct" printme="1">
env = Environment()
d = env.ParseFlags("-whatever")
<file name="SConstruct" printme="1">
env = Environment()
d = env.ParseFlags("-whatever")
- l = d.items()
- l.sort()
- for k,v in l:
+ for k,v in sorted(d.items()):
if v:
print k, v
env.MergeFlags(d)
if v:
print k, v
env.MergeFlags(d)
<file name="SConstruct" printme="1">
env = Environment()
d = env.ParseFlags(["-I/opt/include", ["-L/opt/lib", "-lfoo"]])
<file name="SConstruct" printme="1">
env = Environment()
d = env.ParseFlags(["-I/opt/include", ["-L/opt/lib", "-lfoo"]])
- l = d.items()
- l.sort()
- for k,v in l:
+ for k,v in sorted(d.items()):
if v:
print k, v
env.MergeFlags(d)
if v:
print k, v
env.MergeFlags(d)
<file name="SConstruct" printme="1">
env = Environment()
d = env.ParseFlags(["!echo -I/opt/include", "!echo -L/opt/lib", "-lfoo"])
<file name="SConstruct" printme="1">
env = Environment()
d = env.ParseFlags(["!echo -I/opt/include", "!echo -L/opt/lib", "-lfoo"])
- l = d.items()
- l.sort()
- for k,v in l:
+ for k,v in sorted(d.items()):
if v:
print k, v
env.MergeFlags(d)
if v:
print k, v
env.MergeFlags(d)
<programlisting>
env = Environment()
d = env.ParseFlags("-I/opt/include -L/opt/lib -lfoo")
<programlisting>
env = Environment()
d = env.ParseFlags("-I/opt/include -L/opt/lib -lfoo")
- l = d.items()
- l.sort()
- for k,v in l:
+ for k,v in sorted(d.items()):
if v:
print k, v
env.MergeFlags(d)
if v:
print k, v
env.MergeFlags(d)
<programlisting>
env = Environment()
d = env.ParseFlags("-whatever")
<programlisting>
env = Environment()
d = env.ParseFlags("-whatever")
- l = d.items()
- l.sort()
- for k,v in l:
+ for k,v in sorted(d.items()):
if v:
print k, v
env.MergeFlags(d)
if v:
print k, v
env.MergeFlags(d)
<programlisting>
env = Environment()
d = env.ParseFlags(["-I/opt/include", ["-L/opt/lib", "-lfoo"]])
<programlisting>
env = Environment()
d = env.ParseFlags(["-I/opt/include", ["-L/opt/lib", "-lfoo"]])
- l = d.items()
- l.sort()
- for k,v in l:
+ for k,v in sorted(d.items()):
if v:
print k, v
env.MergeFlags(d)
if v:
print k, v
env.MergeFlags(d)
<programlisting>
env = Environment()
d = env.ParseFlags(["!echo -I/opt/include", "!echo -L/opt/lib", "-lfoo"])
<programlisting>
env = Environment()
d = env.ParseFlags(["!echo -I/opt/include", "!echo -L/opt/lib", "-lfoo"])
- l = d.items()
- l.sort()
for k,v in l:
if v:
print k, v
for k,v in l:
if v:
print k, v
if not hasattr(os, 'WEXITSTATUS'):
os.WEXITSTATUS = lambda x: x
if not hasattr(os, 'WEXITSTATUS'):
os.WEXITSTATUS = lambda x: x
+try:
+ sorted
+except NameError:
+ # Pre-2.4 Python has no sorted() function.
+ #
+ # The pre-2.4 Python list.sort() method does not support
+ # list.sort(key=) nor list.sort(reverse=) keyword arguments, so
+ # we must implement the functionality of those keyword arguments
+ # by hand instead of passing them to list.sort().
+ def sorted(iterable, cmp=None, key=None, reverse=0):
+ if key is not None:
+ result = [(key(x), x) for x in iterable]
+ else:
+ result = iterable[:]
+ if cmp is None:
+ # Pre-2.3 Python does not support list.sort(None).
+ result.sort()
+ else:
+ result.sort(cmp)
+ if key is not None:
+ result = [t1 for t0,t1 in result]
+ if reverse:
+ result.reverse()
+ return result
+
cwd = os.getcwd()
all = 0
cwd = os.getcwd()
all = 0
os.path.walk(path, find_Tests_py, tdict)
elif path[:4] == 'test':
os.path.walk(path, find_py, tdict)
os.path.walk(path, find_Tests_py, tdict)
elif path[:4] == 'test':
os.path.walk(path, find_py, tdict)
- t = tdict.keys()
- t.sort()
- tests.extend(t)
+ tests.extend(sorted(tdict.keys()))
else:
tests.append(path)
elif testlistfile:
else:
tests.append(path)
elif testlistfile:
elif a[-1] not in tdict:
tdict[a[-1]] = Test(a[-1], spe)
elif a[-1] not in tdict:
tdict[a[-1]] = Test(a[-1], spe)
- tests = tdict.keys()
- tests.sort()
+ tests = sorted(tdict.keys())
result = env.subst_list(self.cmd_list, 0, target, source)
silent = None
ignore = None
result = env.subst_list(self.cmd_list, 0, target, source)
silent = None
ignore = None
try: c = result[0][0][0]
except IndexError: c = None
if c == '@': silent = 1
try: c = result[0][0][0]
except IndexError: c = None
if c == '@': silent = 1
# a singleton list returns the contained action
test_positional_args(cmd_action, ["string"])
# a singleton list returns the contained action
test_positional_args(cmd_action, ["string"])
- if hasattr(types, 'UnicodeType'):
+ try: unicode
+ except NameError: pass
+ else:
a2 = eval("SCons.Action.Action(u'string')")
assert isinstance(a2, SCons.Action.CommandAction), a2
a2 = eval("SCons.Action.Action(u'string')")
assert isinstance(a2, SCons.Action.CommandAction), a2
env = Environment()
def execfunc(target, source, env):
env = Environment()
def execfunc(target, source, env):
- assert type(target) is type([]), type(target)
- assert type(source) is type([]), type(source)
+ assert isinstance(target, list), type(target)
+ assert isinstance(source, list), type(source)
return 7
a = SCons.Action.Action(execfunc)
def firstfunc(target, source, env):
return 7
a = SCons.Action.Action(execfunc)
def firstfunc(target, source, env):
- assert type(target) is type([]), type(target)
- assert type(source) is type([]), type(source)
+ assert isinstance(target, list), type(target)
+ assert isinstance(source, list), type(source)
return 0
def lastfunc(target, source, env):
return 0
def lastfunc(target, source, env):
- assert type(target) is type([]), type(target)
- assert type(source) is type([]), type(source)
+ assert isinstance(target, list), type(target)
+ assert isinstance(source, list), type(source)
return 9
b = SCons.Action.Action([firstfunc, execfunc, lastfunc])
return 9
b = SCons.Action.Action([firstfunc, execfunc, lastfunc])
import os.path
import re
import sys
import os.path
import re
import sys
import StringIO
import unittest
import UserList
import StringIO
import unittest
import UserList
#be = target.get_build_env()
#assert be['VAR'] == 'foo', be['VAR']
#be = target.get_build_env()
#assert be['VAR'] == 'foo', be['VAR']
- if not hasattr(types, 'UnicodeType'):
+ try: unicode
+ except NameError:
uni = str
else:
uni = unicode
uni = str
else:
uni = unicode
line = "#define %s 1\n" % key_up
elif have == 0:
line = "/* #undef %s */\n" % key_up
line = "#define %s 1\n" % key_up
elif have == 0:
line = "/* #undef %s */\n" % key_up
- elif type(have) == IntType:
+ elif isinstance(have, IntType):
line = "#define %s %d\n" % (key_up, have)
else:
line = "#define %s %s\n" % (key_up, str(have))
line = "#define %s %d\n" % (key_up, have)
else:
line = "#define %s %s\n" % (key_up, str(have))
def string_to_classes(s):
if s == '*':
def string_to_classes(s):
if s == '*':
- c = tracked_classes.keys()
- c.sort()
- return c
+ return sorted(tracked_classes.keys())
# print a single caller and its callers, if any
def _dump_one_caller(key, file, level=0):
# print a single caller and its callers, if any
def _dump_one_caller(key, file, level=0):
- l = []
- for c,v in caller_dicts[key].items():
- l.append((-v,c))
- l.sort()
+ for v,c in sorted([(-v,c) for c,v in caller_dicts[key].items()]):
file.write("%s %6d %s:%d(%s)\n" % ((leader,-v) + func_shorten(c[-3:])))
if c in caller_dicts:
_dump_one_caller(c, file, level+1)
# print each call tree
def dump_caller_counts(file=sys.stdout):
file.write("%s %6d %s:%d(%s)\n" % ((leader,-v) + func_shorten(c[-3:])))
if c in caller_dicts:
_dump_one_caller(c, file, level+1)
# print each call tree
def dump_caller_counts(file=sys.stdout):
- keys = caller_bases.keys()
- keys.sort()
- for k in keys:
+ for k in sorted(caller_bases.keys()):
file.write("Callers of %s:%d(%s), %d calls:\n"
% (func_shorten(k) + (caller_bases[k],)))
_dump_one_caller(k, file)
file.write("Callers of %s:%d(%s), %d calls:\n"
% (func_shorten(k) + (caller_bases[k],)))
_dump_one_caller(k, file)
import shutil
import stat
import time
import shutil
import stat
import time
import sys
import SCons.Action
import sys
import SCons.Action
if SCons.Util.is_List(defs):
l = []
for d in defs:
if SCons.Util.is_List(defs):
l = []
for d in defs:
- if SCons.Util.is_List(d) or type(d) is types.TupleType:
+ if SCons.Util.is_List(d) or isinstance(d, tuple):
l.append(str(d[0]) + '=' + str(d[1]))
else:
l.append(str(d))
l.append(str(d[0]) + '=' + str(d[1]))
else:
l.append(str(d))
# Consequently, we have to sort the keys to ensure a
# consistent order...
l = []
# Consequently, we have to sort the keys to ensure a
# consistent order...
l = []
- keys = defs.keys()
- keys.sort()
- for k in keys:
- v = defs[k]
+ for k,v in sorted(defs.items()):
if v is None:
l.append(str(k))
else:
if v is None:
l.append(str(k))
else:
import os.path
import StringIO
import sys
import os.path
import StringIO
import sys
import unittest
from UserDict import UserDict
import unittest
from UserDict import UserDict
return
# Filter out null tools from the list.
for tool in [_f for _f in tools if _f]:
return
# Filter out null tools from the list.
for tool in [_f for _f in tools if _f]:
- if SCons.Util.is_List(tool) or type(tool)==type(()):
+ if SCons.Util.is_List(tool) or isinstance(tool, tuple):
toolname = tool[0]
toolargs = tool[1] # should be a dict of kw args
tool = env.Tool(toolname, **toolargs)
toolname = tool[0]
toolargs = tool[1] # should be a dict of kw args
tool = env.Tool(toolname, **toolargs)
class CLVar(UserList.UserList):
def __init__(self, seq):
class CLVar(UserList.UserList):
def __init__(self, seq):
- if type(seq) == type(''):
+ if isinstance(seq, str):
seq = seq.split()
UserList.UserList.__init__(self, seq)
def __add__(self, other):
seq = seq.split()
UserList.UserList.__init__(self, seq)
def __add__(self, other):
assert isinstance(nodes[0], X)
assert nodes[0].name == "Util.py UtilTests.py"
assert isinstance(nodes[0], X)
assert nodes[0].name == "Util.py UtilTests.py"
- import types
- if hasattr(types, 'UnicodeType'):
+ try: unicode
+ except NameError: pass
+ else:
code = """if 1:
nodes = env.arg2nodes(u"Util.py UtilTests.py", Factory)
assert len(nodes) == 1, nodes
code = """if 1:
nodes = env.arg2nodes(u"Util.py UtilTests.py", Factory)
assert len(nodes) == 1, nodes
fails to execute (i.e. execute() raises an exception), then the job will
stop."""
fails to execute (i.e. execute() raises an exception), then the job will
stop."""
task = self.taskmaster.next_task()
if task is None:
task = self.taskmaster.next_task()
if task is None:
self.start()
def run(self):
self.start()
def run(self):
task = self.requestQueue.get()
if task is None:
task = self.requestQueue.get()
if task is None:
# Start up as many available tasks as we're
# allowed to.
while jobs < self.maxjobs:
# Start up as many available tasks as we're
# allowed to.
while jobs < self.maxjobs:
# Let any/all completed tasks finish up before we go
# back and put the next batch of tasks on the queue.
# Let any/all completed tasks finish up before we go
# back and put the next batch of tasks on the queue.
task, ok = self.tp.get()
jobs = jobs - 1
task, ok = self.tp.get()
jobs = jobs - 1
result = runner.run(suite())
if (len(result.failures) == 0
and len(result.errors) == 1
result = runner.run(suite())
if (len(result.failures) == 0
and len(result.errors) == 1
- and type(result.errors[0][0]) == SerialTestCase
- and type(result.errors[0][1][0]) == NoThreadsException):
+ and isinstance(result.errors[0][0], SerialTestCase)
+ and isinstance(result.errors[0][1][0], NoThreadsException)):
sys.exit(2)
elif not result.wasSuccessful():
sys.exit(1)
sys.exit(2)
elif not result.wasSuccessful():
sys.exit(1)
"""Return content signatures and names of all our children
separated by new-lines. Ensure that the nodes are sorted."""
contents = []
"""Return content signatures and names of all our children
separated by new-lines. Ensure that the nodes are sorted."""
contents = []
- name_cmp = lambda a, b: cmp(a.name, b.name)
- sorted_children = self.children()[:]
- sorted_children.sort(name_cmp)
- for node in sorted_children:
+ for node in sorted(self.children(), key=lambda t: t.name):
contents.append('%s %s\n' % (node.get_csig(), node.name))
return ''.join(contents)
contents.append('%s %s\n' % (node.get_csig(), node.name))
return ''.join(contents)
"""
dirname, basename = os.path.split(pathname)
if not dirname:
"""
dirname, basename = os.path.split(pathname)
if not dirname:
- result = self._glob1(basename, ondisk, source, strings)
- result.sort(lambda a, b: cmp(str(a), str(b)))
- return result
+ return sorted(self._glob1(basename, ondisk, source, strings),
+ key=lambda t: str(t))
if has_glob_magic(dirname):
list = self.glob(dirname, ondisk, source, strings=False)
else:
if has_glob_magic(dirname):
list = self.glob(dirname, ondisk, source, strings=False)
else:
fs.Dir(os.path.join('ddd', 'd1', 'f4'))
fs.Dir(os.path.join('ddd', 'd1', 'f5'))
dir.scan()
fs.Dir(os.path.join('ddd', 'd1', 'f4'))
fs.Dir(os.path.join('ddd', 'd1', 'f5'))
dir.scan()
- kids = [x.path for x in dir.children(None)]
- kids.sort()
+ kids = sorted([x.path for x in dir.children(None)])
assert kids == [os.path.join('ddd', 'd1'),
os.path.join('ddd', 'f1'),
os.path.join('ddd', 'f2'),
assert kids == [os.path.join('ddd', 'd1'),
os.path.join('ddd', 'f1'),
os.path.join('ddd', 'f2'),
fs.File(os.path.join('ddd', 'f1'))
dir.scan()
fs.File(os.path.join('ddd', 'f1'))
dir.scan()
- kids = [x.path for x in dir.children()]
- kids.sort()
+ kids = sorted([x.path for x in dir.children()])
assert kids == [os.path.join('ddd', 'f1')], kids
fs.File(os.path.join('ddd', 'f2'))
dir.scan()
assert kids == [os.path.join('ddd', 'f1')], kids
fs.File(os.path.join('ddd', 'f2'))
dir.scan()
- kids = [x.path for x in dir.children()]
- kids.sort()
+ kids = sorted([x.path for x in dir.children()])
assert kids == [os.path.join('ddd', 'f1'),
os.path.join('ddd', 'f2')], kids
assert kids == [os.path.join('ddd', 'f1'),
os.path.join('ddd', 'f2')], kids
strings_kwargs = copy.copy(kwargs)
strings_kwargs['strings'] = True
for input, string_expect, node_expect in cases:
strings_kwargs = copy.copy(kwargs)
strings_kwargs['strings'] = True
for input, string_expect, node_expect in cases:
- r = self.fs.Glob(input, **strings_kwargs)
- r.sort()
+ r = sorted(self.fs.Glob(input, **strings_kwargs))
assert r == string_expect, "Glob(%s, strings=True) expected %s, got %s" % (input, string_expect, r)
# Now execute all of the cases without string=True and look for
assert r == string_expect, "Glob(%s, strings=True) expected %s, got %s" % (input, string_expect, r)
# Now execute all of the cases without string=True and look for
r.sort(lambda a,b: cmp(a.path, b.path))
result = []
for n in node_expect:
r.sort(lambda a,b: cmp(a.path, b.path))
result = []
for n in node_expect:
- if type(n) == type(''):
n = self.fs.Entry(n)
result.append(n)
fmt = lambda n: "%s %s" % (repr(n), repr(str(n)))
else:
n = self.fs.Entry(n)
result.append(n)
fmt = lambda n: "%s %s" % (repr(n), repr(str(n)))
else:
- r = list(map(str, r))
- r.sort()
+ r = sorted(map(str, r))
result = string_expect
fmt = lambda n: n
if r != result:
result = string_expect
fmt = lambda n: n
if r != result:
import os
import re
import sys
import os
import re
import sys
import unittest
import UserList
import unittest
import UserList
all.append(curr_a)
elif isinstance(curr_a, MyListAction):
all.extend(curr_a.list)
all.append(curr_a)
elif isinstance(curr_a, MyListAction):
all.extend(curr_a.list)
- elif type(curr_a) == type([1,2]):
+ elif isinstance(curr_a, list):
all.extend(curr_a)
else:
raise 'Cannot Combine Actions'
all.extend(curr_a)
else:
raise 'Cannot Combine Actions'
try:
field_list = self.field_list
except AttributeError:
try:
field_list = self.field_list
except AttributeError:
- field_list = self.__dict__.keys()
- field_list.sort()
+ field_list = sorted(self.__dict__.keys())
fields = []
for field in field_list:
try:
fields = []
for field in field_list:
try:
import StringIO
import sys
import traceback
import StringIO
import sys
import traceback
import SCons.Action
import SCons.Builder
import SCons.Action
import SCons.Builder
return (str(target[0]) + ' <-\n |' +
source[0].get_contents().replace( '\n', "\n |" ) )
return (str(target[0]) + ' <-\n |' +
source[0].get_contents().replace( '\n', "\n |" ) )
-# python 2.2 introduces types.BooleanType
-BooleanTypes = [types.IntType]
-if hasattr(types, 'BooleanType'): BooleanTypes.append(types.BooleanType)
+# python 2.2 introduces bool
+BooleanTypes = [int, bool]
class SConfBuildInfo(SCons.Node.FS.FileBuildInfo):
"""
class SConfBuildInfo(SCons.Node.FS.FileBuildInfo):
"""
text = "yes"
else:
text = "no"
text = "yes"
else:
text = "no"
- elif type(res) == types.StringType:
+ elif isinstance(res, str):
text = res
else:
raise TypeError, "Expected string, int or bool, got " + str(type(res))
text = res
else:
raise TypeError, "Expected string, int or bool, got " + str(type(res))
for n in sys.modules.keys():
if n.split('.')[0] == 'SCons' and n[:12] != 'SCons.compat':
m = sys.modules[n]
for n in sys.modules.keys():
if n.split('.')[0] == 'SCons' and n[:12] != 'SCons.compat':
m = sys.modules[n]
- if type(m) is ModuleType:
+ if isinstance(m, ModuleType):
# if this is really a scons module, clear its namespace
del sys.modules[n]
m.__dict__.clear()
# if this is really a scons module, clear its namespace
del sys.modules[n]
m.__dict__.clear()
else:
try:
self.entries = cPickle.loads(rawentries)
else:
try:
self.entries = cPickle.loads(rawentries)
- if type(self.entries) is not type({}):
+ if not isinstance(self.entries, dict):
self.entries = {}
raise TypeError
except KeyboardInterrupt:
self.entries = {}
raise TypeError
except KeyboardInterrupt:
return
self.entries = cPickle.load(fp)
return
self.entries = cPickle.load(fp)
- if type(self.entries) is not type({}):
+ if not isinstance(self.entries, dict):
self.entries = {}
raise TypeError
self.entries = {}
raise TypeError
return [[strSubst]]
def subst_path(self, path, target=None, source=None, conv=None):
return [[strSubst]]
def subst_path(self, path, target=None, source=None, conv=None):
- if type(path) != type([]):
+ if not isinstance(path, list):
path = [path]
return list(map(self.subst, path))
path = [path]
return list(map(self.subst, path))
# mixed Node types (Dirs and Files, for example) has a Dir as
# the first entry.
return []
# mixed Node types (Dirs and Files, for example) has a Dir as
# the first entry.
return []
- entry_list = list(filter(do_not_scan, entries.keys()))
- entry_list.sort()
+ entry_list = sorted(filter(do_not_scan, entries.keys()))
return [entries[n] for n in entry_list]
# Local Variables:
return [entries[n] for n in entry_list]
# Local Variables:
import os.path
import sys
import os.path
import sys
import unittest
import TestCmd
import unittest
import TestCmd
sortkey = self.sort_key(dep)
nodes.append((sortkey, n))
sortkey = self.sort_key(dep)
nodes.append((sortkey, n))
- nodes.sort()
- nodes = [pair[1] for pair in nodes]
- return nodes
+ return [pair[1] for pair in sorted(nodes)]
def FortranScan(path_variable="FORTRANPATH"):
"""Return a prototype Scanner instance for scanning source files
def FortranScan(path_variable="FORTRANPATH"):
"""Return a prototype Scanner instance for scanning source files
return arg
def subst_path(self, path, target=None, source=None, conv=None):
return arg
def subst_path(self, path, target=None, source=None, conv=None):
- if type(path) != type([]):
+ if not isinstance(path, list):
path = [path]
return list(map(self.subst, path))
path = [path]
return list(map(self.subst, path))
return arg
def subst_path(self, path, target=None, source=None, conv=None):
return arg
def subst_path(self, path, target=None, source=None, conv=None):
- if type(path) != type([]):
+ if not isinstance(path, list):
path = [path]
return list(map(self.subst, path))
path = [path]
return list(map(self.subst, path))
# recurse down
queue.extend( self.scan(n) )
# recurse down
queue.extend( self.scan(n) )
- #
- nodes.sort()
- nodes = [pair[1] for pair in nodes]
- return nodes
+ return [pair[1] for pair in sorted(nodes)]
# Local Variables:
# tab-width:4
# Local Variables:
# tab-width:4
import os.path
import sys
import os.path
import sys
import unittest
import UserDict
import unittest
import UserDict
return [[strSubst]]
def subst_path(self, path, target=None, source=None, conv=None):
return [[strSubst]]
def subst_path(self, path, target=None, source=None, conv=None):
- if type(path) != type([]):
+ if not isinstance(path, list):
path = [path]
return list(map(self.subst, path))
path = [path]
return list(map(self.subst, path))
import os.path
import sys
import os.path
import sys
import unittest
import TestCmd
import unittest
import TestCmd
return s
def subst_path(self, path, target=None, source=None, conv=None):
return s
def subst_path(self, path, target=None, source=None, conv=None):
- if type(path) != type([]):
+ if not isinstance(path, list):
path = [path]
return list(map(self.subst, path))
path = [path]
return list(map(self.subst, path))
return self.name
def deps_match(deps, libs):
return self.name
def deps_match(deps, libs):
- deps=list(map(str, deps))
- deps.sort()
+ deps=sorted(map(str, deps))
libs.sort()
return list(map(os.path.normpath, deps)) == list(map(os.path.normpath, libs))
libs.sort()
return list(map(os.path.normpath, deps)) == list(map(os.path.normpath, libs))
suite.addTest(ProgramScannerTestCase6())
suite.addTest(ProgramScannerTestCase7())
suite.addTest(ProgramScannerTestCase8())
suite.addTest(ProgramScannerTestCase6())
suite.addTest(ProgramScannerTestCase7())
suite.addTest(ProgramScannerTestCase8())
- if hasattr(types, 'UnicodeType'):
+ try: unicode
+ except NameError: pass
+ else:
code = """if 1:
class ProgramScannerTestCase4(unittest.TestCase):
def runTest(self):
code = """if 1:
class ProgramScannerTestCase4(unittest.TestCase):
def runTest(self):
return strSubst
def subst_path(self, path, target=None, source=None, conv=None):
return strSubst
def subst_path(self, path, target=None, source=None, conv=None):
- if type(path) != type([]):
+ if not isinstance(path, list):
path = [path]
return list(map(self.subst, path))
path = [path]
return list(map(self.subst, path))
my_normpath = os.path.normcase
def deps_match(self, deps, headers):
my_normpath = os.path.normcase
def deps_match(self, deps, headers):
- scanned = list(map(my_normpath, list(map(str, deps))))
- expect = list(map(my_normpath, headers))
- scanned.sort()
- expect.sort()
+ scanned = sorted(map(my_normpath, list(map(str, deps))))
+ expect = sorted(map(my_normpath, headers))
self.failUnless(scanned == expect, "expect %s != scanned %s" % (expect, scanned))
# define some tests:
self.failUnless(scanned == expect, "expect %s != scanned %s" % (expect, scanned))
# define some tests:
return [self.data[strSubst[1:]]]
return [[strSubst]]
def subst_path(self, path, target=None, source=None, conv=None):
return [self.data[strSubst[1:]]]
return [[strSubst]]
def subst_path(self, path, target=None, source=None, conv=None):
- if type(path) != type([]):
+ if not isinstance(path, list):
path = [path]
return list(map(self.subst, path))
def get_factory(self, factory):
path = [path]
return list(map(self.subst, path))
def get_factory(self, factory):
self.failUnless(self.env == env, "the environment was passed incorrectly")
self.failUnless(scanned_strs == deps, "the dependencies were returned incorrectly")
for d in scanned:
self.failUnless(self.env == env, "the environment was passed incorrectly")
self.failUnless(scanned_strs == deps, "the dependencies were returned incorrectly")
for d in scanned:
- self.failUnless(type(d) != type(""), "got a string in the dependencies")
+ self.failUnless(not isinstance(d, str), "got a string in the dependencies")
if len(args) > 0:
self.failUnless(self.arg == args[0], "the argument was passed incorrectly")
if len(args) > 0:
self.failUnless(self.arg == args[0], "the argument was passed incorrectly")
SCons.Warnings.warn(SCons.Warnings.DependencyWarning,
"No dependency generated for file: %s (included from: %s) -- file not found" % (i, node))
else:
SCons.Warnings.warn(SCons.Warnings.DependencyWarning,
"No dependency generated for file: %s (included from: %s) -- file not found" % (i, node))
else:
- sortkey = self.sort_key(include)
- nodes.append((sortkey, n))
+ nodes.append((self.sort_key(include), n))
- nodes.sort()
- nodes = [pair[1] for pair in nodes]
- return nodes
+ return [pair[1] for pair in sorted(nodes)]
class ClassicCPP(Classic):
"""
class ClassicCPP(Classic):
"""
display("Removed " + pathstr)
elif os.path.isdir(path) and not os.path.islink(path):
# delete everything in the dir
display("Removed " + pathstr)
elif os.path.isdir(path) and not os.path.islink(path):
# delete everything in the dir
- entries = os.listdir(path)
- # Sort for deterministic output (os.listdir() Can
- # return entries in a random order).
- entries.sort()
- for e in entries:
+ for e in sorted(os.listdir(path)):
p = os.path.join(path, e)
s = os.path.join(pathstr, e)
if os.path.isfile(p):
p = os.path.join(path, e)
s = os.path.join(pathstr, e)
if os.path.isfile(p):
for n, c in s:
stats_table[n][i] = c
i = i + 1
for n, c in s:
stats_table[n][i] = c
i = i + 1
- keys = stats_table.keys()
- keys.sort()
self.outfp.write("Object counts:\n")
pre = [" "]
post = [" %s\n"]
self.outfp.write("Object counts:\n")
pre = [" "]
post = [" %s\n"]
labels.append(("", "Class"))
self.outfp.write(fmt1 % tuple([x[0] for x in labels]))
self.outfp.write(fmt1 % tuple([x[1] for x in labels]))
labels.append(("", "Class"))
self.outfp.write(fmt1 % tuple([x[0] for x in labels]))
self.outfp.write(fmt1 % tuple([x[1] for x in labels]))
+ for k in sorted(stats_table.keys()):
r = stats_table[k][:l] + [k]
self.outfp.write(fmt2 % tuple(r))
r = stats_table[k][:l] + [k]
self.outfp.write(fmt2 % tuple(r))
options, args = parser.parse_args(all_args, values)
options, args = parser.parse_args(all_args, values)
- if type(options.debug) == type([]) and "pdb" in options.debug:
+ if isinstance(options.debug, list) and "pdb" in options.debug:
import pdb
pdb.Pdb().runcall(_main, parser)
elif options.profile_file:
import pdb
pdb.Pdb().runcall(_main, parser)
elif options.profile_file:
import re
import sys
import traceback
import re
import sys
import traceback
import UserList
# The following variables used to live in this module. Some
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)):
import SCons.Script
d = SCons.Script.__dict__
def not_a_module(m, d=d, mtype=type(SCons.Script)):
- return type(d[m]) != mtype
+ return not isinstance(d[m], mtype)
for m in filter(not_a_module, dir(SCons.Script)):
GlobalDict[m] = d[m]
for m in filter(not_a_module, dir(SCons.Script)):
GlobalDict[m] = d[m]
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import re
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import re
import UserList
import UserString
import UserList
import UserString
handles separating command lines into lists of arguments, so see
that function if that's what you're looking for.
"""
handles separating command lines into lists of arguments, so see
that function if that's what you're looking for.
"""
- if type(strSubst) == types.StringType and strSubst.find('$') < 0:
+ if isinstance(strSubst, str) and strSubst.find('$') < 0:
return strSubst
class StringSubber:
return strSubst
class StringSubber:
We do this with some straightforward, brute-force code here...
"""
We do this with some straightforward, brute-force code here...
"""
- if type(strSubst) == types.StringType and strSubst.find('$') < 0:
+ if isinstance(strSubst, str) and strSubst.find('$') < 0:
return strSubst
matchlist = ['$' + key, '${' + key + '}']
return strSubst
matchlist = ['$' + key, '${' + key + '}']
import os.path
import StringIO
import sys
import os.path
import StringIO
import sys
import unittest
from UserDict import UserDict
import unittest
from UserDict import UserDict
def _defines(defs):
l = []
for d in defs:
def _defines(defs):
l = []
for d in defs:
- if SCons.Util.is_List(d) or type(d) is types.TupleType:
+ if SCons.Util.is_List(d) or isinstance(d, tuple):
l.append(str(d[0]) + '=' + str(d[1]))
else:
l.append(str(d))
l.append(str(d[0]) + '=' + str(d[1]))
else:
l.append(str(d))
T = self.trace
if T: T.write('\n' + self.trace_message('Looking for a node to evaluate'))
T = self.trace
if T: T.write('\n' + self.trace_message('Looking for a node to evaluate'))
node = self.next_candidate()
if node is None:
if T: T.write(self.trace_message('No candidate anymore.') + '\n')
node = self.next_candidate()
if node is None:
if T: T.write(self.trace_message('No candidate anymore.') + '\n')
T.write(self.trace_message(' removing node %s from the pending children set\n' %
self.trace_node(n)))
try:
T.write(self.trace_message(' removing node %s from the pending children set\n' %
self.trace_node(n)))
try:
try:
node = to_visit.pop()
except AttributeError:
try:
node = to_visit.pop()
except AttributeError:
assert e.errstr == "OtherError : ", e.errstr
assert len(e.exc_info) == 3, e.exc_info
exc_traceback = sys.exc_info()[2]
assert e.errstr == "OtherError : ", e.errstr
assert len(e.exc_info) == 3, e.exc_info
exc_traceback = sys.exc_info()[2]
- assert type(e.exc_info[2]) == type(exc_traceback), e.exc_info[2]
+ assert isinstance(e.exc_info[2], type(exc_traceback)), e.exc_info[2]
else:
raise TestFailed, "did not catch expected BuildError"
else:
raise TestFailed, "did not catch expected BuildError"
m = re.search(r'([0-9.]+)$', d)
if m:
versions.append(m.group(1))
m = re.search(r'([0-9.]+)$', d)
if m:
versions.append(m.group(1))
- versions = uniquify(versions) # remove dups
- versions.sort(vercmp)
- return versions
+ return sorted(uniquify(versions)) # remove dups
def get_intel_compiler_top(version, abi):
"""
def get_intel_compiler_top(version, abi):
"""
elif isinstance(entry, SCons.Node.FS.Dir):
result = SCons.Util.OrderedDict()
def visit(arg, dirname, names, dirnode=entry.rdir()):
elif isinstance(entry, SCons.Node.FS.Dir):
result = SCons.Util.OrderedDict()
def visit(arg, dirname, names, dirnode=entry.rdir()):
- java_files = [n for n in names if _my_normcase(n[-len(js):]) == js]
- # The on-disk entries come back in arbitrary order. Sort
- # them so our target and source lists are determinate.
- java_files.sort()
+ java_files = sorted([n for n in names if _my_normcase(n[-len(js):]) == js])
mydir = dirnode.Dir(dirname)
java_paths = [mydir.File(f) for f in java_files]
for jp in java_paths:
mydir = dirnode.Dir(dirname)
java_paths = [mydir.File(f) for f in java_files]
for jp in java_paths:
self.sources[t[0]].append(self.env[t[1]])
for n in sourcenames:
self.sources[t[0]].append(self.env[t[1]])
for n in sourcenames:
- # TODO(1.5):
- #self.sources[n].sort(lambda a, b: cmp(a.lower(), b.lower()))
self.sources[n].sort(lambda a, b: cmp(a.lower(), b.lower()))
def AddConfig(self, variant, buildtarget, outdir, runfile, cmdargs, dspfile=dspfile):
self.sources[n].sort(lambda a, b: cmp(a.lower(), b.lower()))
def AddConfig(self, variant, buildtarget, outdir, runfile, cmdargs, dspfile=dspfile):
def PrintHeader(self):
# pick a default config
def PrintHeader(self):
# pick a default config
- confkeys = self.configs.keys()
- confkeys.sort()
+ confkeys = sorted(self.configs.keys())
name = self.name
confkey = confkeys[0]
name = self.name
confkey = confkeys[0]
'# PROP Scc_LocalPath ""\n\n')
first = 1
'# PROP Scc_LocalPath ""\n\n')
first = 1
- confkeys = self.configs.keys()
- confkeys.sort()
+ confkeys = sorted(self.configs.keys())
for kind in confkeys:
outdir = self.configs[kind].outdir
buildtarget = self.configs[kind].buildtarget
for kind in confkeys:
outdir = self.configs[kind].outdir
buildtarget = self.configs[kind].buildtarget
'Other Files': ''}
cats = categories.keys()
'Other Files': ''}
cats = categories.keys()
- # TODO(1.5):
- #cats.sort(lambda a, b: cmp(a.lower(), b.lower()))
cats.sort(lambda a, b: cmp(a.lower(), b.lower()))
for kind in cats:
if not self.sources[kind]:
cats.sort(lambda a, b: cmp(a.lower(), b.lower()))
for kind in cats:
if not self.sources[kind]:
def PrintProject(self):
self.file.write('\t<Configurations>\n')
def PrintProject(self):
self.file.write('\t<Configurations>\n')
- confkeys = self.configs.keys()
- confkeys.sort()
+ confkeys = sorted(self.configs.keys())
for kind in confkeys:
variant = self.configs[kind].variant
platform = self.configs[kind].platform
for kind in confkeys:
variant = self.configs[kind].variant
platform = self.configs[kind].platform
def printSources(self, hierarchy, commonprefix):
sorteditems = hierarchy.items()
def printSources(self, hierarchy, commonprefix):
sorteditems = hierarchy.items()
- # TODO(1.5):
- #sorteditems.sort(lambda a, b: cmp(a[0].lower(), b[0].lower()))
sorteditems.sort(lambda a, b: cmp(a[0].lower(), b[0].lower()))
# First folders, then files
sorteditems.sort(lambda a, b: cmp(a[0].lower(), b[0].lower()))
# First folders, then files
self.file.write('\t<Files>\n')
cats = categories.keys()
self.file.write('\t<Files>\n')
cats = categories.keys()
- # TODO(1.5)
- #cats.sort(lambda a, b: cmp(a.lower(), b.lower()))
cats.sort(lambda a, b: cmp(a.lower(), b.lower()))
cats = [k for k in cats if self.sources[k]]
for kind in cats:
cats.sort(lambda a, b: cmp(a.lower(), b.lower()))
cats = [k for k in cats if self.sources[k]]
for kind in cats:
else:
self.file.write('\tGlobalSection(SolutionConfiguration) = preSolution\n')
else:
self.file.write('\tGlobalSection(SolutionConfiguration) = preSolution\n')
- confkeys = self.configs.keys()
- confkeys.sort()
+ confkeys = sorted(self.configs.keys())
cnt = 0
for name in confkeys:
variant = self.configs[name].variant
cnt = 0
for name in confkeys:
variant = self.configs[name].variant
product_key = SCons.Util.RegOpenKeyEx(HLM, product)
i = 0
product_key = SCons.Util.RegOpenKeyEx(HLM, product)
i = 0
name = product + '\\' + SCons.Util.RegEnumKey(product_key, i)
name_key = SCons.Util.RegOpenKeyEx(HLM, name)
name = product + '\\' + SCons.Util.RegEnumKey(product_key, i)
name_key = SCons.Util.RegOpenKeyEx(HLM, name)
# Don't "from types import ..." these because we need to get at the
# types module later to look for UnicodeType.
# Don't "from types import ..." these because we need to get at the
# types module later to look for UnicodeType.
-DictType = types.DictType
InstanceType = types.InstanceType
InstanceType = types.InstanceType
-ListType = types.ListType
-StringType = types.StringType
-TupleType = types.TupleType
+ListType = list
+StringType = str
+TupleType = tuple
+try: unicode
+except NameError: UnicodeType = None
+else: UnicodeType = unicode
def dictify(keys, values, result={}):
for k, v in zip(keys, values):
def dictify(keys, values, result={}):
for k, v in zip(keys, values):
t = type(obj)
return t is TupleType
t = type(obj)
return t is TupleType
- if hasattr(types, 'UnicodeType'):
+ if UnicodeType is not None:
def is_String(obj):
t = type(obj)
return t is StringType \
def is_String(obj):
t = type(obj)
return t is StringType \
# to_String_for_signature() will use a for_signature() method if the
# specified object has one.
#
# to_String_for_signature() will use a for_signature() method if the
# specified object has one.
#
- if hasattr(types, 'UnicodeType'):
- UnicodeType = types.UnicodeType
+ if UnicodeType is not None:
def to_String(s):
if isinstance(s, UserString):
t = type(s.data)
def to_String(s):
if isinstance(s, UserString):
t = type(s.data)
# Doesn't seem like we need to, but we'll comment it just in case.
copy[key] = semi_deepcopy(val)
return copy
# Doesn't seem like we need to, but we'll comment it just in case.
copy[key] = semi_deepcopy(val)
return copy
-d[types.DictionaryType] = _semi_deepcopy_dict
+d[dict] = _semi_deepcopy_dict
def _semi_deepcopy_list(x):
return list(map(semi_deepcopy, x))
def _semi_deepcopy_list(x):
return list(map(semi_deepcopy, x))
-d[types.ListType] = _semi_deepcopy_list
+d[list] = _semi_deepcopy_list
def _semi_deepcopy_tuple(x):
return tuple(map(semi_deepcopy, x))
def _semi_deepcopy_tuple(x):
return tuple(map(semi_deepcopy, x))
-d[types.TupleType] = _semi_deepcopy_tuple
+d[tuple] = _semi_deepcopy_tuple
def _semi_deepcopy_inst(x):
if hasattr(x, '__semi_deepcopy__'):
def _semi_deepcopy_inst(x):
if hasattr(x, '__semi_deepcopy__'):
# sort functions in all languages or libraries, so this approach
# is more effective in Python than it may be elsewhere.
try:
# sort functions in all languages or libraries, so this approach
# is more effective in Python than it may be elsewhere.
try:
except TypeError:
pass # move on to the next method
else:
except TypeError:
pass # move on to the next method
else:
def readline(self):
result = []
def readline(self):
result = []
line = self.fileobj.readline()
if not line:
break
line = self.fileobj.readline()
if not line:
break
def readlines(self):
result = []
def readlines(self):
result = []
line = self.readline()
if not line:
break
line = self.readline()
if not line:
break
def MD5filesignature(fname, chunksize=65536):
m = hashlib.md5()
f = open(fname, "rb")
def MD5filesignature(fname, chunksize=65536):
m = hashlib.md5()
f = open(fname, "rb")
blck = f.read(chunksize)
if not blck:
break
blck = f.read(chunksize)
if not blck:
break
import os.path
import StringIO
import sys
import os.path
import StringIO
import sys
import unittest
from UserDict import UserDict
import unittest
from UserDict import UserDict
+try: unicode
+except NameError: HasUnicode = False
+else: HasUnicode = True
+
class OutBuffer:
def __init__(self):
self.buffer = ""
class OutBuffer:
def __init__(self):
self.buffer = ""
assert not is_Dict([])
assert not is_Dict(())
assert not is_Dict("")
assert not is_Dict([])
assert not is_Dict(())
assert not is_Dict("")
- if hasattr(types, 'UnicodeType'):
exec "assert not is_Dict(u'')"
def test_is_List(self):
exec "assert not is_Dict(u'')"
def test_is_List(self):
assert not is_List(())
assert not is_List({})
assert not is_List("")
assert not is_List(())
assert not is_List({})
assert not is_List("")
- if hasattr(types, 'UnicodeType'):
exec "assert not is_List(u'')"
def test_is_String(self):
assert is_String("")
exec "assert not is_List(u'')"
def test_is_String(self):
assert is_String("")
- if hasattr(types, 'UnicodeType'):
exec "assert is_String(u'')"
try:
import UserString
exec "assert is_String(u'')"
try:
import UserString
assert not is_Tuple([])
assert not is_Tuple({})
assert not is_Tuple("")
assert not is_Tuple([])
assert not is_Tuple({})
assert not is_Tuple("")
- if hasattr(types, 'UnicodeType'):
exec "assert not is_Tuple(u'')"
def test_to_String(self):
exec "assert not is_Tuple(u'')"
def test_to_String(self):
assert to_String(s2) == s2, s2
assert to_String(s2) == 'foo', s2
assert to_String(s2) == s2, s2
assert to_String(s2) == 'foo', s2
- if hasattr(types, 'UnicodeType'):
s3=UserString.UserString(unicode('bar'))
assert to_String(s3) == s3, s3
assert to_String(s3) == unicode('bar'), s3
s3=UserString.UserString(unicode('bar'))
assert to_String(s3) == s3, s3
assert to_String(s3) == unicode('bar'), s3
- assert type(to_String(s3)) is types.UnicodeType, \
+ assert isinstance(to_String(s3), unicode), \
type(to_String(s3))
except ImportError:
pass
type(to_String(s3))
except ImportError:
pass
- if hasattr(types, 'UnicodeType'):
s4 = unicode('baz')
assert to_String(s4) == unicode('baz'), to_String(s4)
s4 = unicode('baz')
assert to_String(s4) == unicode('baz'), to_String(s4)
- assert type(to_String(s4)) is types.UnicodeType, \
+ assert isinstance(to_String(s4), unicode), \
type(to_String(s4))
def test_WhereIs(self):
type(to_String(s4))
def test_WhereIs(self):
class _ListVariable(UserList.UserList):
def __init__(self, initlist=[], allowedElems=[]):
UserList.UserList.__init__(self, [_f for _f in initlist if _f])
class _ListVariable(UserList.UserList):
def __init__(self, initlist=[], allowedElems=[]):
UserList.UserList.__init__(self, [_f for _f in initlist if _f])
- self.allowedElems = allowedElems[:]
- self.allowedElems.sort()
+ self.allowedElems = sorted(allowedElems)
def __cmp__(self, other):
raise NotImplementedError
def __cmp__(self, other):
raise NotImplementedError
putting it in the environment.
"""
putting it in the environment.
"""
- if SCons.Util.is_List(key) or type(key) == type(()):
+ if SCons.Util.is_List(key) or isinstance(key, tuple):
self._do_add(*key)
return
self._do_add(*key)
return
- options = self.options[:]
- options.sort(lambda x,y: sort(x.key,y.key))
+ options = sorted(self.options, cmp=lambda x,y: sort(x.key,y.key))
else:
options = self.options
else:
options = self.options
-import types
-
-StringType = types.StringType
-
-if hasattr(types, 'UnicodeType'):
- UnicodeType = types.UnicodeType
+try: unicode
+except NameError:
- return type(obj) in (StringType, UnicodeType)
+ return type(obj) is str
else:
def is_String(obj):
else:
def is_String(obj):
- return type(obj) is StringType
+ return type(obj) in (str, unicode)
class UserString:
def __init__(self, seq):
class UserString:
def __init__(self, seq):
else:
setattr(self, attr, None)
if attrs:
else:
setattr(self, attr, None)
if attrs:
- attrs = attrs.keys()
- attrs.sort()
+ attrs = sorted(attrs.keys())
raise OptionError(
"invalid keyword arguments: %s" % string.join(attrs, ", "),
self)
raise OptionError(
"invalid keyword arguments: %s" % string.join(attrs, ", "),
self)
if self.choices is None:
raise OptionError(
"must supply a list of choices for type 'choice'", self)
if self.choices is None:
raise OptionError(
"must supply a list of choices for type 'choice'", self)
- elif type(self.choices) not in (types.TupleType, types.ListType):
+ elif type(self.choices) not in (tuple, list):
raise OptionError(
"choices must be a list of strings ('%s' supplied)"
% string.split(str(type(self.choices)), "'")[1], self)
raise OptionError(
"choices must be a list of strings ('%s' supplied)"
% string.split(str(type(self.choices)), "'")[1], self)
raise OptionError(
"callback not callable: %r" % self.callback, self)
if (self.callback_args is not None and
raise OptionError(
"callback not callable: %r" % self.callback, self)
if (self.callback_args is not None and
- type(self.callback_args) is not types.TupleType):
+ type(self.callback_args) is not tuple):
raise OptionError(
"callback_args, if supplied, must be a tuple: not %r"
% self.callback_args, self)
if (self.callback_kwargs is not None and
raise OptionError(
"callback_args, if supplied, must be a tuple: not %r"
% self.callback_args, self)
if (self.callback_kwargs is not None and
- type(self.callback_kwargs) is not types.DictType):
+ type(self.callback_kwargs) is not dict):
raise OptionError(
"callback_kwargs, if supplied, must be a dict: not %r"
% self.callback_kwargs, self)
raise OptionError(
"callback_kwargs, if supplied, must be a dict: not %r"
% self.callback_kwargs, self)
except NameError:
(True, False) = (1, 0)
except NameError:
(True, False) = (1, 0)
-try:
- types.UnicodeType
-except AttributeError:
+try: unicode
+except NameError:
- return isinstance(x, types.StringType)
+ return isinstance(x, str)
else:
def isbasestring(x):
else:
def isbasestring(x):
- return isinstance(x, types.StringType) or isinstance(x, types.UnicodeType)
+ return isinstance(x, str) or isinstance(x, unicode)
def __cmp__(self, other):
if isinstance(other, Values):
return cmp(self.__dict__, other.__dict__)
def __cmp__(self, other):
if isinstance(other, Values):
return cmp(self.__dict__, other.__dict__)
- elif isinstance(other, types.DictType):
+ elif isinstance(other, dict):
return cmp(self.__dict__, other)
else:
return -1
return cmp(self.__dict__, other)
else:
return -1
"""add_option(Option)
add_option(opt_str, ..., kwarg=val, ...)
"""
"""add_option(Option)
add_option(opt_str, ..., kwarg=val, ...)
"""
- if type(args[0]) is types.StringType:
+ if type(args[0]) is str:
option = apply(self.option_class, args, kwargs)
elif len(args) == 1 and not kwargs:
option = args[0]
option = apply(self.option_class, args, kwargs)
elif len(args) == 1 and not kwargs:
option = args[0]
def add_option_group(self, *args, **kwargs):
# XXX lots of overlap with OptionContainer.add_option()
def add_option_group(self, *args, **kwargs):
# XXX lots of overlap with OptionContainer.add_option()
- if type(args[0]) is types.StringType:
+ if type(args[0]) is str:
group = apply(OptionGroup, (self,) + args, kwargs)
elif len(args) == 1 and not kwargs:
group = args[0]
group = apply(OptionGroup, (self,) + args, kwargs)
elif len(args) == 1 and not kwargs:
group = args[0]
# __str__ is the same as __repr__
__str__ = __repr__
# __str__ is the same as __repr__
__str__ = __repr__
- def _repr(self, sorted=False):
+ def _repr(self, sort_them=False):
elements = self._data.keys()
elements = self._data.keys()
elements.sort()
return '%s(%r)' % (self.__class__.__name__, elements)
elements.sort()
return '%s(%r)' % (self.__class__.__name__, elements)
# we must implement the functionality of those keyword arguments
# by hand instead of passing them to list.sort().
def sorted(iterable, cmp=None, key=None, reverse=False):
# we must implement the functionality of those keyword arguments
# by hand instead of passing them to list.sort().
def sorted(iterable, cmp=None, key=None, reverse=False):
- if key:
- decorated = [ (key(x), x) for x in iterable ]
- if cmp is None:
- # Pre-2.3 Python does not support list.sort(None).
- decorated.sort()
- else:
- decorated.sort(cmp)
- if reverse:
- decorated.reverse()
- result = [ t[1] for t in decorated ]
+ if key is not None:
+ result = [(key(x), x) for x in iterable]
else:
result = iterable[:]
else:
result = iterable[:]
- if cmp is None:
- # Pre-2.3 Python does not support list.sort(None).
- result.sort()
- else:
- result.sort(cmp)
- if reverse:
- result.reverse()
+ if cmp is None:
+ # Pre-2.3 Python does not support list.sort(None).
+ result.sort()
+ else:
+ result.sort(cmp)
+ if key is not None:
+ result = [t1 for t0,t1 in result]
+ if reverse:
+ result.reverse()
return result
__builtin__.sorted = sorted
return result
__builtin__.sorted = sorted
# re module, as late as version 2.2.2, empirically matches the
# "!" in "!=" first, instead of finding the longest match.
# What's up with that?
# re module, as late as version 2.2.2, empirically matches the
# "!" in "!=" first, instead of finding the longest match.
# What's up with that?
-l = CPP_to_Python_Ops_Dict.keys()
-l.sort(lambda a, b: cmp(len(b), len(a)))
+l = sorted(CPP_to_Python_Ops_Dict.keys(), cmp=lambda a, b: cmp(len(b), len(a)))
# Turn the list of keys into one regular expression that will allow us
# to substitute all of the operators at once.
# Turn the list of keys into one regular expression that will allow us
# to substitute all of the operators at once.
import time
import shutil
import os
import time
import shutil
import os
import __builtin__
keep_all_files = 00000
import __builtin__
keep_all_files = 00000
def corruption_warning(filename):
print "Warning: Discarding corrupt database:", filename
def corruption_warning(filename):
print "Warning: Discarding corrupt database:", filename
-if hasattr(types, 'UnicodeType'):
+try: unicode
+except NameError:
- t = type(s)
- return t is types.StringType or t is types.UnicodeType
+ return isinstance(s, str)
- return type(s) is types.StringType
+ return type(s) in (str, unicode)
import __builtin__
__builtin__.True = not 0
import __builtin__
__builtin__.True = not 0
+try:
+ sorted
+except NameError:
+ # Pre-2.4 Python has no sorted() function.
+ #
+ # The pre-2.4 Python list.sort() method does not support
+ # list.sort(key=) nor list.sort(reverse=) keyword arguments, so
+ # we must implement the functionality of those keyword arguments
+ # by hand instead of passing them to list.sort().
+ def sorted(iterable, cmp=None, key=None, reverse=False):
+ if key is not None:
+ result = [(key(x), x) for x in iterable]
+ else:
+ result = iterable[:]
+ if cmp is None:
+ # Pre-2.3 Python does not support list.sort(None).
+ result.sort()
+ else:
+ result.sort(cmp)
+ if key is not None:
+ result = [t1 for t0,t1 in result]
+ if reverse:
+ result.reverse()
+ return result
+ __builtin__.sorted = sorted
+
def make_temp_file(**kw):
try:
result = tempfile.mktemp(**kw)
def make_temp_file(**kw):
try:
result = tempfile.mktemp(**kw)
"""
files = []
for a in args:
"""
files = []
for a in args:
- g = glob.glob(a)
- g.sort()
- files.extend(g)
+ files.extend(sorted(glob.glob(a)))
if tail:
files = files[-tail:]
if tail:
files = files[-tail:]
"""
gp = Gnuplotter(self.title, self.key_location)
"""
gp = Gnuplotter(self.title, self.key_location)
- indices = results.keys()
- indices.sort()
-
- for i in indices:
+ for i in sorted(results.keys()):
try:
t = self.run_titles[i]
except IndexError:
try:
t = self.run_titles[i]
except IndexError:
try:
keys = ninfo.field_list + ['_version_id']
except AttributeError:
try:
keys = ninfo.field_list + ['_version_id']
except AttributeError:
- keys = d.keys()
- keys.sort()
+ keys = sorted(d.keys())
l = []
for k in keys:
l.append('%s: %s' % (repr(k), repr(d.get(k))))
l = []
for k in keys:
l.append('%s: %s' % (repr(k), repr(d.get(k))))
print nodeinfo_string(name, entry.ninfo)
printfield(name, entry.binfo)
else:
print nodeinfo_string(name, entry.ninfo)
printfield(name, entry.binfo)
else:
- names = entries.keys()
- names.sort()
- for name in names:
+ for name in sorted(entries.keys()):
entry = entries[name]
try:
ninfo = entry.ninfo
entry = entries[name]
try:
ninfo = entry.ninfo
else:
self.printentries(dir, val)
else:
else:
self.printentries(dir, val)
else:
- keys = db.keys()
- keys.sort()
- for dir in keys:
+ for dir in sorted(db.keys()):
self.printentries(dir, db[dir])
def printentries(self, dir, val):
self.printentries(dir, db[dir])
def printentries(self, dir, val):
contents = open(os.path.join(scons_lib_dir, f)).read()
try_except_lines = {}
lastend = 0
contents = open(os.path.join(scons_lib_dir, f)).read()
try_except_lines = {}
lastend = 0
match = tryexc_pat.search( contents, lastend )
if match is None:
break
match = tryexc_pat.search( contents, lastend )
if match is None:
break
del u[file]
except KeyError:
pass
del u[file]
except KeyError:
pass
-
-files = u.keys()
-
-files.sort()
+files = sorted(u.keys())
test.write('SConstruct', """
foo = open('foo.out', 'wb')
test.write('SConstruct', """
foo = open('foo.out', 'wb')
-keys = ARGUMENTS.keys()
-keys.sort()
-for k in keys:
+for k in sorted(list(ARGUMENTS.keys())):
foo.write(k + " = " + ARGUMENTS[k] + "\\n")
foo.close()
""")
foo.write(k + " = " + ARGUMENTS[k] + "\\n")
foo.close()
""")
def collect(env, source, target):
out = open(str(target[0]), 'wb')
dir = str(source[0])
def collect(env, source, target):
out = open(str(target[0]), 'wb')
dir = str(source[0])
- files = os.listdir(dir)
- files.sort()
- for f in files:
+ for f in sorted(os.listdir(dir)):
f = os.path.join(dir, f)
out.write(open(f, 'r').read())
out.close()
f = os.path.join(dir, f)
out.write(open(f, 'r').read())
out.close()
target = str(target[0])
source = str(source[0])
t = open(target, 'wb')
target = str(target[0])
source = str(source[0])
t = open(target, 'wb')
- files = os.listdir(source)
- files.sort()
- for f in files:
+ for f in sorted(os.listdir(source)):
t.write(open(os.path.join(source, f), 'rb').read())
t.close()
return 0
t.write(open(os.path.join(source, f), 'rb').read())
t.close()
return 0
def must_be_same(f1, f2):
global errors
def must_be_same(f1, f2):
global errors
- if type(f1) is type([]):
+ if isinstance(f1, list):
- if type(f2) is type([]):
+ if isinstance(f2, list):
f2 = os.path.join(*f2)
s1 = os.stat(f1)
s2 = os.stat(f2)
f2 = os.path.join(*f2)
s1 = os.stat(f1)
s2 = os.stat(f2)
def print_build_failures():
from SCons.Script import GetBuildFailures
def print_build_failures():
from SCons.Script import GetBuildFailures
- bf_list = GetBuildFailures()
- bf_list.sort(lambda a,b: cmp(a.filename, b.filename))
- for bf in bf_list:
+ for bf in sorted(GetBuildFailures(),
+ cmp=lambda a,b: cmp(a.filename, b.filename)):
print "%%s failed: %%s" %% (bf.node, bf.errstr)
try:
print "%%s failed: %%s" %% (bf.node, bf.errstr)
try:
def print_build_failures():
from SCons.Script import GetBuildFailures
def print_build_failures():
from SCons.Script import GetBuildFailures
- bf_list = GetBuildFailures()
- bf_list.sort(lambda a,b: cmp(a.filename, b.filename))
- for bf in bf_list:
+ for bf in sorted(GetBuildFailures(), key=lambda t: t.filename):
print "%%s failed: %%s" %% (bf.node, bf.errstr)
try:
print "%%s failed: %%s" %% (bf.node, bf.errstr)
try:
def print_build_failures():
from SCons.Script import GetBuildFailures
def print_build_failures():
from SCons.Script import GetBuildFailures
- bf_list = GetBuildFailures()
- bf_list.sort(lambda a,b: cmp(str(a.node), str(b.node)))
- for bf in bf_list:
+ for bf in sorted(GetBuildFailures(), key=lambda t: str(t.node)):
assert( isinstance(bf, SCons.Errors.BuildError) )
print "BF: %%s failed (%%s): %%s" %% (bf.node, bf.status, bf.errstr)
if bf.command:
assert( isinstance(bf, SCons.Errors.BuildError) )
print "BF: %%s failed (%%s): %%s" %% (bf.node, bf.status, bf.errstr)
if bf.command:
Import("env")
env.Build('xxx.out', Glob('x*.in'))
env.Build('yyy.out', Glob('yy?.in'))
Import("env")
env.Build('xxx.out', Glob('x*.in'))
env.Build('yyy.out', Glob('yy?.in'))
-zzz_in = Glob('*/zzz.in')
-zzz_in.sort(lambda a,b: cmp(a.abspath, b.abspath))
-env.Build('zzz.out', zzz_in)
+env.Build('zzz.out', sorted(Glob('*/zzz.in'), key=lambda t: t.abspath))
""")
test.write(['repository', 'src', 'xxx.in'], "repository/src/xxx.in\n")
""")
test.write(['repository', 'src', 'xxx.in'], "repository/src/xxx.in\n")
env['BUILDERS']['Concatenate'] = Builder(action=concatenate)
env['BUILDERS']['Concatenate'] = Builder(action=concatenate)
-f_in = Glob('f*.in')
-f_in.sort(lambda a,b: cmp(a.name, b.name))
-env.Concatenate('f.out', f_in)
+env.Concatenate('f.out', sorted(Glob('f*.in'), key=lambda t: t.name))
""")
test.write(['src', 'f1.in'], "src/f1.in\n")
""")
test.write(['src', 'f1.in'], "src/f1.in\n")
env['BUILDERS']['Concatenate'] = Builder(action=concatenate)
env['BUILDERS']['Concatenate'] = Builder(action=concatenate)
-f_in = Glob('f*.in')
-f_in.sort(lambda a,b: cmp(a.name, b.name))
-env.Concatenate('f.out', f_in)
+env.Concatenate('f.out', sorted(Glob('f*.in'), key=lambda t: t.name))
""")
test.write('f1.in', "f1.in\n")
""")
test.write('f1.in', "f1.in\n")
test.write(['var1', 'SConscript'], """\
Import("env")
test.write(['var1', 'SConscript'], """\
Import("env")
-f_in = Glob('f[45].in', source=True)
-f_in.sort(lambda a,b: cmp(a.name, b.name))
-env.Concatenate('f.out', f_in)
+env.Concatenate('f.out', sorted(Glob('f[45].in', source=True),
+ key=lambda t: t.name))
""")
test.write(['var2', 'SConscript'], """\
Import("env")
""")
test.write(['var2', 'SConscript'], """\
Import("env")
-f_in = Glob('f[67].in')
-f_in.sort(lambda a,b: cmp(a.name, b.name))
+f_in = sorted(Glob('f[67].in'), cmp=lambda a,b: cmp(a.name, b.name))
env.Concatenate('f.out', f_in)
""")
env.Concatenate('f.out', f_in)
""")
env['BUILDERS']['Concatenate'] = Builder(action=concatenate)
env['BUILDERS']['Concatenate'] = Builder(action=concatenate)
-f_in = Glob('f*.in', strings=True)
-f_in.sort()
-env.Concatenate('f.out', f_in)
+env.Concatenate('f.out', sorted(Glob('f*.in', strings=True)))
""")
test.write(['src', 'f1.in'], "src/f1.in\n")
""")
test.write(['src', 'f1.in'], "src/f1.in\n")
env['BUILDERS']['Concatenate'] = Builder(action=concatenate)
env['BUILDERS']['Concatenate'] = Builder(action=concatenate)
-f_in = Glob('subdir/*.in')
-f_in.sort(lambda a,b: cmp(a.name, b.name))
-env.Concatenate('f.out', f_in)
+env.Concatenate('f.out', sorted(Glob('subdir/*.in'), key=lambda t: t.name))
""")
test.write(['subdir', 'file.in'], "subdir/file.in\n")
""")
test.write(['subdir', 'file.in'], "subdir/file.in\n")
env['BUILDERS']['Copy'] = Builder(action=copy)
env['BUILDERS']['Copy'] = Builder(action=copy)
-f_in = env.Glob('$PATTERN')
-f_in.sort(lambda a,b: cmp(a.name, b.name))
-env.Copy('f.out', f_in)
+env.Copy('f.out', sorted(env.Glob('$PATTERN'), key=lambda t: t.name))
""")
test.write('f1.in', "f1.in\n")
""")
test.write('f1.in', "f1.in\n")
outfp = open(target, "wb")
for src in source:
s = str(src)
outfp = open(target, "wb")
for src in source:
s = str(src)
- l = os.listdir(s)
- l.sort()
- for f in l:
+ for f in sorted(os.listdir(s)):
f = os.path.join(s, f)
if os.path.isfile(f):
outfp.write(open(f, "rb").read())
f = os.path.join(s, f)
if os.path.isfile(f):
outfp.write(open(f, "rb").read())
Scanned = {}
def write_out(file, dict):
Scanned = {}
def write_out(file, dict):
- keys = dict.keys()
- keys.sort()
+ for k in sorted(dict.keys()):
file = os.path.split(k)[1]
f.write(file + ": " + str(dict[k]) + "\\n")
f.close()
file = os.path.split(k)[1]
f.write(file + ": " + str(dict[k]) + "\\n")
f.close()
test.write('SConstruct', """\
def foo(target, source, env):
test.write('SConstruct', """\
def foo(target, source, env):
- children = source[0].children()
- children.sort(lambda a,b: cmp(a.name, b.name))
fp = open(str(target[0]), 'wb')
fp = open(str(target[0]), 'wb')
+ for c in sorted(source[0].children(), key=lambda t: t.name):
fp.write('%s\\n' % c)
fp.close()
Command('list.out', 'subdir', foo, source_scanner = DirScanner)
fp.write('%s\\n' % c)
fp.close()
Command('list.out', 'subdir', foo, source_scanner = DirScanner)
if opt == '-f': out = arg
def process(outfile, name):
if os.path.isdir(name):
if opt == '-f': out = arg
def process(outfile, name):
if os.path.isdir(name):
+ ## TODO 2.5: the next three lines can be replaced by
+ #for entry in sorted(os.listdir(name)):
list = os.listdir(name)
list.sort()
for entry in list:
list = os.listdir(name)
list.sort()
for entry in list:
else: opt_string = opt_string + ' ' + opt
def process(outfile, name):
if os.path.isdir(name):
else: opt_string = opt_string + ' ' + opt
def process(outfile, name):
if os.path.isdir(name):
+ ## TODO 2.5: the next three lines can be replaced by
+ #for entry in sorted(os.listdir(name)):
entries = os.listdir(name)
entries.sort()
for entry in entries:
entries = os.listdir(name)
entries.sort()
for entry in entries:
import sys
def process(outfile, name):
if os.path.isdir(name):
import sys
def process(outfile, name):
if os.path.isdir(name):
+ ## TODO 2.5: the next three lines can be replaced by
+ #for entry in sorted(os.listdir(name)):
list = os.listdir(name)
list.sort()
for entry in list:
list = os.listdir(name)
list.sort()
for entry in list:
test.write('SConstruct', """\
def marker(target, source, env):
open(r'%s', 'wb').write("marker\\n")
test.write('SConstruct', """\
def marker(target, source, env):
open(r'%s', 'wb').write("marker\\n")
f1 = Environment()
zipcom = f1.Dictionary('ZIPCOM')
f1 = Environment()
zipcom = f1.Dictionary('ZIPCOM')
-if not type(zipcom) is types.ListType:
+if not isinstance(zipcom, list):
zipcom = [zipcom]
f2 = Environment(ZIPCOM = [Action(marker)] + zipcom)
f3 = Environment(ZIPSUFFIX = '.xyzzy')
zipcom = [zipcom]
f2 = Environment(ZIPCOM = [Action(marker)] + zipcom)
f3 = Environment(ZIPSUFFIX = '.xyzzy')
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import os
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
import os
import TestSCons
def match_normcase(lines, matches):
import TestSCons
def match_normcase(lines, matches):
- if not type(lines) is types.ListType:
+ if not isinstance(lines, list):
lines = lines.split("\n")
lines = lines.split("\n")
- if not type(matches) is types.ListType:
+ if not isinstance(matches, list):
matches = matches.split("\n")
if len(lines) != len(matches):
return
matches = matches.split("\n")
if len(lines) != len(matches):
return
options = [x.split()[0] for x in lines]
options = [x[-1] == ',' and x[:-1] or x for x in options]
lowered = [x.lower() for x in options]
options = [x.split()[0] for x in lines]
options = [x[-1] == ',' and x[:-1] or x for x in options]
lowered = [x.lower() for x in options]
-sorted = lowered[:]
-sorted.sort()
-if lowered != sorted:
+ordered = sorted(lowered)
+if lowered != ordered:
print "lowered =", lowered
print "lowered =", lowered
- print "sorted =", sorted
+ print "sorted =", ordered
test.fail_test()
test.pass_test()
test.fail_test()
test.pass_test()
prog = env.Install( 'bin/', ["f1", "f2"] )
env.File( "f3" )
prog = env.Install( 'bin/', ["f1", "f2"] )
env.File( "f3" )
-src_files = list(map(str, env.FindSourceFiles()))
-oth_files = list(map(str, env.FindInstalledFiles()))
-src_files.sort()
-oth_files.sort()
+src_files = sorted(map(str, env.FindSourceFiles()))
+oth_files = sorted(map(str, env.FindInstalledFiles()))
print src_files
print oth_files
print src_files
print oth_files
if color is None:
color = self.color
if revs is None:
if color is None:
color = self.color
if revs is None:
- revs = self.keys()
- revs.sort()
+ revs = sorted(self.keys())
if labels:
result = [ (r, color, None, self[r]) for r in revs ]
else:
if labels:
result = [ (r, color, None, self[r]) for r in revs ]
else: