Skip to content

Commit 868425b

Browse files
authored
More Python3 lint fixes (#32967)
* More Python3 lint fixes Some of the issues addressed include: * Don't use `l` as a variable name (confusable with `1` or `I`) * `print` statement does not exist in Py3, use `print` function instead * Implicit tuple deconstruction in function args is no longer supported, use explicit splat `*` at the call site instead * `xrange` does not exist in Py3, use `range` instead * Better name per review feedback
1 parent d3ecf88 commit 868425b

File tree

8 files changed

+52
-40
lines changed

8 files changed

+52
-40
lines changed

unittests/Reflection/RemoteMirrorInterop/test.py

+9-7
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,18 @@
77
#
88
# Invoke by passing the various Swift build directories as parameters.
99

10+
from __future__ import print_function
11+
1012
import itertools
1113
import os
1214
import subprocess
1315
import sys
1416

1517
args = sys.argv[1:]
1618
if len(args) == 0:
17-
print >> sys.stderr, "Usage:", sys.argv[0], "swift-build-dirs..."
18-
print >> sys.stderr, ("Note: pass paths to the swift-macosx-x86_64"
19-
" directories, or /usr to test the OS.")
19+
print("Usage:", sys.argv[0], "swift-build-dirs...", file=sys.stderr)
20+
print(("Note: pass paths to the swift-macosx-x86_64"
21+
" directories, or /usr to test the OS."), file=sys.stderr)
2022
sys.exit(1)
2123

2224
absoluteArgs = [os.path.abspath(arg) for arg in args]
@@ -63,8 +65,8 @@ def libPath(path):
6365
dylibPath = os.path.join('/tmp', 'libtest' + str(i) + '.dylib')
6466
callArgs.append(dylibPath)
6567
callArgs += list(localMirrorlibs)
66-
print ' '.join(callArgs)
68+
print(' '.join(callArgs))
6769
subprocess.call(callArgs)
68-
print 'DONE'
69-
print ''
70-
print localMirrorlibs
70+
print('DONE')
71+
print('')
72+
print(localMirrorlibs)

utils/api_checker/sdk-module-lists/infer-imports.py

+16-11
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
#!/usr/bin/env python -u
22

3+
from __future__ import print_function
4+
35
import os
46
import sys
57

@@ -63,14 +65,17 @@ def get_frameworks(sdk_path, swift_frameworks_only):
6365

6466
if not os.path.exists(header_dir_path):
6567
if os.path.exists(module_dir_path):
66-
print >>sys.stderr, header_dir_path, \
67-
" non-existent while 'Modules' exists"
68+
print(header_dir_path,
69+
" non-existent while 'Modules' exists",
70+
file=sys.stderr)
6871
if os.path.exists(old_modulemap_path):
69-
print >>sys.stderr, header_dir_path, \
70-
" non-existent while 'module.map' exists"
72+
print(header_dir_path,
73+
" non-existent while 'module.map' exists",
74+
file=sys.stderr)
7175
if os.path.exists(old_modulemap_private_path):
72-
print >>sys.stderr, header_dir_path, \
73-
" non-existent while 'module_private.map' exists"
76+
print(header_dir_path,
77+
" non-existent while 'module_private.map' exists",
78+
file=sys.stderr)
7479
continue
7580

7681
if should_exclude_framework(frameworks_path + '/' + frame):
@@ -110,14 +115,14 @@ def should_exclude_framework(frame_path):
110115
def print_clang_imports(frames, use_hash):
111116
for name in frames:
112117
if use_hash:
113-
print "#import <" + name + "/" + name + ".h>"
118+
print("#import <" + name + "/" + name + ".h>")
114119
else:
115-
print "@import " + name + ";"
120+
print("@import " + name + ";")
116121

117122

118123
def print_swift_imports(frames):
119124
for name in frames:
120-
print "import " + name
125+
print("import " + name)
121126

122127

123128
def main():
@@ -161,14 +166,14 @@ def main():
161166
frames = get_frameworks(opts.sdk, opts.swift_frameworks_only)
162167
if opts.v:
163168
for name in frames:
164-
print >>sys.stderr, 'Including: ', name
169+
print('Including: ', name, file=sys.stderr)
165170
if opts.out_mode == "clang-import":
166171
print_clang_imports(frames, opts.use_hash)
167172
elif opts.out_mode == "swift-import":
168173
print_swift_imports(frames)
169174
elif opts.out_mode == "list":
170175
for name in frames:
171-
print name
176+
print(name)
172177
else:
173178
parser.error(
174179
"output mode not found: 'clang-import'/'swift-import'/'list'")

utils/build_swift/tests/build_swift/test_driver_arguments.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -342,7 +342,7 @@ def _parse_args(self, args):
342342
try:
343343
return migration.parse_args(self.parser, args)
344344
except (SystemExit, ValueError) as e:
345-
raise ParserError('failed to parse arguments: {}'.format(
345+
raise ParserError('failed to parse arguments: {} {}'.format(
346346
six.text_type(args), e))
347347

348348
def _check_impl_args(self, namespace):
@@ -353,7 +353,7 @@ def _check_impl_args(self, namespace):
353353
constants.BUILD_SCRIPT_IMPL_PATH,
354354
namespace.build_script_impl_args)
355355
except (SystemExit, ValueError) as e:
356-
raise ParserError('failed to parse impl arguments: {}'.format(
356+
raise ParserError('failed to parse impl arguments: {} {}'.format(
357357
six.text_type(namespace.build_script_impl_args), e))
358358

359359
def parse_args_and_unknown_args(self, args, namespace=None):
@@ -369,7 +369,7 @@ def parse_args_and_unknown_args(self, args, namespace=None):
369369
migration._process_disambiguation_arguments(
370370
namespace, unknown_args))
371371
except (SystemExit, argparse.ArgumentError) as e:
372-
raise ParserError('failed to parse arguments: {}'.format(
372+
raise ParserError('failed to parse arguments: {} {}'.format(
373373
six.text_type(args), e))
374374

375375
return namespace, unknown_args

utils/lldb/lldbCheckExpect.py

+10-9
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
Expected value : 98
2222
Actual value : ...
2323
'''
24+
from __future__ import print_function
2425

2526

2627
def unwrap(s):
@@ -55,7 +56,7 @@ def unwrap(s):
5556
def on_check_expect(frame, bp_loc, session):
5657
parent_frame = frame.get_parent_frame()
5758
parent_name = parent_frame.GetFunctionName()
58-
print "Evaluating check-expect in", parent_name
59+
print("Evaluating check-expect in", parent_name)
5960

6061
# Note: If we fail to stringify the arguments in the check-expect frame,
6162
# the standard library has probably not been compiled with debug info.
@@ -69,25 +70,25 @@ def on_check_expect(frame, bp_loc, session):
6970
expr_result = parent_frame.FindVariable(var_name).GetObjectDescription()
7071
eval_result = unwrap(str(expr_result))
7172

72-
print " Checked variable:", var_name
73-
print " Expected value :", expected_value
74-
print " Actual value :", eval_result
73+
print(" Checked variable:", var_name)
74+
print(" Expected value :", expected_value)
75+
print(" Actual value :", eval_result)
7576

7677
if eval_result == expected_value:
7778
# Do not stop execution.
7879
return False
7980

80-
print "Found a possible expression evaluation failure."
81+
print("Found a possible expression evaluation failure.")
8182

8283
for i, (c1, c2) in enumerate(zip(expected_value, eval_result)):
8384
if c1 == c2:
8485
continue
85-
print " -> Character difference at index", i
86-
print " -> Expected", c1, "but found", c2
86+
print(" -> Character difference at index", i)
87+
print(" -> Expected", c1, "but found", c2)
8788
break
8889
else:
89-
print " -> Expected string has length", len(expected_value)
90-
print " -> Actual string has length", len(eval_result)
90+
print(" -> Expected string has length", len(expected_value))
91+
print(" -> Actual string has length", len(eval_result))
9192
return True
9293

9394

utils/lldb/lldbToolBox.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
This will also import LLVM data formatters as well, assuming that llvm is next
77
to the swift checkout.
88
"""
9+
from __future__ import print_function
910

1011
import argparse
1112
import os
@@ -108,7 +109,7 @@ def sequence(debugger, command, exec_ctx, result, internal_dict):
108109
ret = lldb.SBCommandReturnObject()
109110
interpreter.HandleCommand(subcommand, exec_ctx, ret)
110111
if ret.GetOutput():
111-
print >>result, ret.GetOutput().strip()
112+
print(ret.GetOutput().strip(), file=result)
112113

113114
if not ret.Succeeded():
114115
result.SetError(ret.GetError())

utils/scale-test

+3-3
Original file line numberDiff line numberDiff line change
@@ -281,7 +281,7 @@ def Nelder_Mead_simplex(objective, params, bounds, epsilon=1.0e-6):
281281
locs = [tuple(random.uniform(*b) for b in bounds)
282282
for _ in range(ndim + 1)]
283283
SimplexPoint = namedtuple("SimplexPoint", ["loc", "val"])
284-
simplex = [SimplexPoint(loc=l, val=f(l)) for l in locs]
284+
simplex = [SimplexPoint(loc=loc, val=f(loc)) for loc in locs]
285285

286286
# Algorithm parameters
287287
alpha = 1.0
@@ -337,8 +337,8 @@ def Nelder_Mead_simplex(objective, params, bounds, epsilon=1.0e-6):
337337

338338
# 6. Shrink
339339
simplex = (simplex[:1] +
340-
[SimplexPoint(loc=l, val=f(l))
341-
for l in [tup_add(xb, tup_mul(sigma, tup_sub(p.loc, xb)))
340+
[SimplexPoint(loc=L, val=f(L))
341+
for L in [tup_add(xb, tup_mul(sigma, tup_sub(p.loc, xb)))
342342
for p in simplex[1:]]])
343343

344344

utils/swift-api-dump.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -161,8 +161,11 @@ def print_command(cmd, outfile=""):
161161
# Dump the API for the given module.
162162

163163

164-
def dump_module_api((cmd, extra_dump_args, output_dir, module, quiet,
165-
verbose)):
164+
def dump_module_api_star(pack):
165+
dump_module_api(*pack)
166+
167+
168+
def dump_module_api(cmd, extra_dump_args, output_dir, module, quiet, verbose):
166169
# Collect the submodules
167170
submodules = collect_submodules(cmd, module)
168171

@@ -341,7 +344,7 @@ def main():
341344

342345
# Execute the API dumps
343346
pool = multiprocessing.Pool(processes=args.jobs)
344-
pool.map(dump_module_api, jobs)
347+
pool.map(dump_module_api_star, jobs)
345348

346349
# Remove the .swift file we fed into swift-ide-test
347350
subprocess.call(['rm', '-f', source_filename])

utils/type-layout-fuzzer.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
def randomTypeList(depth):
3636
count = random.randint(0, maxMembers)
3737
result = "("
38-
for i in xrange(count):
38+
for i in range(count):
3939
if i > 0:
4040
result += ", "
4141
result += randomTypeReference(depth + 1)
@@ -81,7 +81,7 @@ def leaf():
8181

8282
def defineRandomFields(depth, basename):
8383
numMembers = random.randint(0, maxMembers)
84-
for i in xrange(numMembers):
84+
for i in range(numMembers):
8585
print(" var " + basename + str(i) + ": " +
8686
randomTypeReference(depth + 1))
8787

@@ -141,7 +141,7 @@ def enum():
141141
print("enum " + name + " {")
142142

143143
numCases = random.randint(0, maxMembers)
144-
for i in xrange(numCases):
144+
for i in range(numCases):
145145
print(" case x" + str(i) + randomTypeList(depth + 1))
146146

147147
print("}")

0 commit comments

Comments
 (0)