Issue #2974 - Part 20: Use last few fixers.

Just rush through the last ones I semi-trust...

2to3 . --fix methodattrs -wpn
''           funcattrs   ''
''           has_key     ''
''           renames     ''
''           types       ''
''           nonzero     ''

Ref:
https://docs.python.org/3/whatsnew/3.0.html
This commit is contained in:
Jeremy Andrews committed 2026-03-06 02:08:07 -06:00
1 parent e12d6ebd5e
commit ae877638e8
56 files changed
+144 -144

No files matched your search

+1 -1
View File
@@ -377,7 +377,7 @@ if __name__ == "__main__":
extra_cflags2 = ["-fPIC"]
extra_cxxflags2 = ["-fPIC", "-static-libstdc++"]
if os.environ.has_key('LD_LIBRARY_PATH'):
if 'LD_LIBRARY_PATH' in os.environ:
os.environ['LD_LIBRARY_PATH'] = '%s/lib64/:%s' % (gcc_dir, os.environ['LD_LIBRARY_PATH']);
else:
os.environ['LD_LIBRARY_PATH'] = '%s/lib64/' % gcc_dir
+1 -1
View File
@@ -327,7 +327,7 @@ class PopenJob(Job):
# general overview of "subprocess PATH semantics and portability".
oldpath = os.environ['PATH']
try:
if self.env is not None and self.env.has_key('PATH'):
if self.env is not None and 'PATH' in self.env:
os.environ['PATH'] = self.env['PATH']
p = subprocess.Popen(self.argv, executable=self.executable, shell=self.shell, env=self.env, cwd=self.cwd)
return p.wait()
+1 -1
View File
@@ -58,7 +58,7 @@ class ZipFile(zipfile.ZipFile):
# as the old, reuse the existing entry.
doSeek = False # store if we need to seek to the eof after overwriting
if self.NameToInfo.has_key(zinfo.filename):
if zinfo.filename in self.NameToInfo:
# Find the last ZipInfo with our name.
# Last, because that's catching multiple overwrites
i = len(self.filelist)
+1 -1
View File
@@ -51,7 +51,7 @@ class Struct:
print(' Created struct: %s' % name, file=sys.stderr)
def AddEntry(self, entry):
if self._tags.has_key(entry.Tag()):
if entry.Tag() in self._tags:
raise RpcGenError(
'Entry "%s" duplicates tag number %d from "%s" '
'around line %d' % (entry.Name(), entry.Tag(),
+2 -2
View File
@@ -22,7 +22,7 @@ class TaskFinishedMarker:
def _do_work(qTasks, qResults, qWatch, prefix, run_skipped, timeout, show_cmd):
while True:
test = qTasks.get(block=True, timeout=sys.maxint)
test = qTasks.get(block=True, timeout=sys.maxsize)
if test is EndMarker:
qWatch.put(EndMarker)
qResults.put(EndMarker)
@@ -73,7 +73,7 @@ def _do_watch(qWatch, timeout):
# ignore this.
if ex.winerror != 5:
raise
fin = qWatch.get(block=True, timeout=sys.maxint)
fin = qWatch.get(block=True, timeout=sys.maxsize)
assert fin is TaskFinishedMarker, "invalid finish marker"
+3 -3
View File
@@ -135,7 +135,7 @@ def evaluate(variables, cache_variables, parsed):
variable = arguments[1]
values = arguments[2:]
if action == 'APPEND':
if not variables.has_key(variable):
if variable not in variables:
variables[variable] = ' '.join(values)
else:
variables[variable] += ' ' + ' '.join(values)
@@ -145,7 +145,7 @@ def evaluate(variables, cache_variables, parsed):
variable = arguments[0]
value = arguments[2]
# Allow options to be override without changing CMake files
if not variables.has_key(variable):
if variable not in variables:
variables[variable] = value
elif command == 'return':
return False, sources
@@ -156,7 +156,7 @@ def evaluate(variables, cache_variables, parsed):
try:
cache = values.index('CACHE')
values = values[0:cache]
if not variables.has_key(variable):
if variable not in variables:
variables[variable] = ' '.join(values)
cache_variables.append(variable)
except ValueError:
+8 -8
View File
@@ -213,7 +213,7 @@ class DataTable(object):
(len(value) == 3 and not isinstance(value[2], dict))):
raise DataTableException("Wrong format for value and formatting - %s." %
str(value))
if not isinstance(value[1], types.StringTypes + (types.NoneType,)):
if not isinstance(value[1], (str,) + (type(None),)):
raise DataTableException("Formatted value is not string, given %s." %
type(value[1]))
js_value = DataTable.CoerceValue(value[0], value_type)
@@ -329,17 +329,17 @@ class DataTable(object):
if not description:
raise DataTableException("Description error: empty description given")
if not isinstance(description, (types.StringTypes, tuple)):
if not isinstance(description, ((str,), tuple)):
raise DataTableException("Description error: expected either string or "
"tuple, got %s." % type(description))
if isinstance(description, types.StringTypes):
if isinstance(description, (str,)):
description = (description,)
# According to the tuple's length, we fill the keys
# We verify everything is of type string
for elem in description[:3]:
if not isinstance(elem, types.StringTypes):
if not isinstance(elem, (str,)):
raise DataTableException("Description error: expected tuple of "
"strings, current element of type %s." %
type(elem))
@@ -456,7 +456,7 @@ class DataTable(object):
-- second 'b' is the label, and {} is the custom properties field.
"""
# For the recursion step, we check for a scalar object (string or tuple)
if isinstance(table_description, (types.StringTypes, tuple)):
if isinstance(table_description, ((str,), tuple)):
parsed_col = DataTable.ColumnTypeParser(table_description)
parsed_col["depth"] = depth
parsed_col["container"] = "scalar"
@@ -491,7 +491,7 @@ class DataTable(object):
# dictionary).
# NOTE: this way of differentiating might create ambiguity. See docs.
if (len(table_description) != 1 or
(isinstance(list(table_description.keys())[0], types.StringTypes) and
(isinstance(list(table_description.keys())[0], (str,)) and
isinstance(list(table_description.values())[0], tuple) and
len(list(table_description.values())[0]) < 4)):
# This is the most inner dictionary. Parsing types.
@@ -655,12 +655,12 @@ class DataTable(object):
return self.__data
proper_sort_keys = []
if isinstance(order_by, types.StringTypes) or (
if isinstance(order_by, (str,)) or (
isinstance(order_by, tuple) and len(order_by) == 2 and
order_by[1].lower() in ["asc", "desc"]):
order_by = (order_by,)
for key in order_by:
if isinstance(key, types.StringTypes):
if isinstance(key, (str,)):
proper_sort_keys.append((key, 1))
elif (isinstance(key, (list, tuple)) and len(key) == 2 and
key[1].lower() in ("asc", "desc")):
@@ -147,7 +147,7 @@ class TestServerThread(threading.Thread):
return False
logging.info('Got port json data: %s', port_json)
port_json = json.loads(port_json)
if port_json.has_key('port') and isinstance(port_json['port'], int):
if 'port' in port_json and isinstance(port_json['port'], int):
self.host_port = port_json['port']
return _CheckPortStatus(self.host_port, True)
logging.error('Failed to get port information from the server data.')
@@ -177,29 +177,29 @@ class TestServerThread(threading.Thread):
data_dir = os.path.join(constants.CHROME_DIR, data_dir)
self.command_line.append('--data-dir=%s' % data_dir)
# The following arguments are optional depending on the individual test.
if self.arguments.has_key('log-to-console'):
if 'log-to-console' in self.arguments:
self.command_line.append('--log-to-console')
if self.arguments.has_key('auth-token'):
if 'auth-token' in self.arguments:
self.command_line.append('--auth-token=%s' % self.arguments['auth-token'])
if self.arguments.has_key('https'):
if 'https' in self.arguments:
self.command_line.append('--https')
if self.arguments.has_key('cert-and-key-file'):
if 'cert-and-key-file' in self.arguments:
self.command_line.append('--cert-and-key-file=%s' % os.path.join(
constants.CHROME_DIR, self.arguments['cert-and-key-file']))
if self.arguments.has_key('ocsp'):
if 'ocsp' in self.arguments:
self.command_line.append('--ocsp=%s' % self.arguments['ocsp'])
if self.arguments.has_key('https-record-resume'):
if 'https-record-resume' in self.arguments:
self.command_line.append('--https-record-resume')
if self.arguments.has_key('ssl-client-auth'):
if 'ssl-client-auth' in self.arguments:
self.command_line.append('--ssl-client-auth')
if self.arguments.has_key('tls-intolerant'):
if 'tls-intolerant' in self.arguments:
self.command_line.append('--tls-intolerant=%s' %
self.arguments['tls-intolerant'])
if self.arguments.has_key('ssl-client-ca'):
if 'ssl-client-ca' in self.arguments:
for ca in self.arguments['ssl-client-ca']:
self.command_line.append('--ssl-client-ca=%s' %
os.path.join(constants.CHROME_DIR, ca))
if self.arguments.has_key('ssl-bulk-cipher'):
if 'ssl-bulk-cipher' in self.arguments:
for bulk_cipher in self.arguments['ssl-bulk-cipher']:
self.command_line.append('--ssl-bulk-cipher=%s' % bulk_cipher)
@@ -168,7 +168,7 @@ def _GetTestClassesFromModule(test_module):
def _IsTestClass(test_class):
return (type(test_class) is types.TypeType and
return (type(test_class) is type and
issubclass(test_class, python_test_base.PythonTestBase) and
test_class is not python_test_base.PythonTestBase)
@@ -23,7 +23,7 @@ class AnnotatedFunctions(object):
"""
module_name = os.path.splitext(os.path.basename(
function.__globals__['__file__']))[0]
qualified_function_name = '.'.join([module_name, function.func_name])
qualified_function_name = '.'.join([module_name, function.__name__])
function_list = AnnotatedFunctions._ANNOTATED.get(annotation, [])
function_list.append(qualified_function_name)
AnnotatedFunctions._ANNOTATED[annotation] = function_list
@@ -141,7 +141,7 @@ def GetAllIncludeDirectories(target_list, target_dicts,
compiler_includes_list.append(include_dir)
# Find standard gyp include dirs.
if config.has_key('include_dirs'):
if 'include_dirs' in config:
include_dirs = config['include_dirs']
for shared_intermediate_dir in shared_intermediate_dirs:
for include_dir in include_dirs:
@@ -2760,7 +2760,7 @@ def _GetMSBuildPropertySheets(configurations):
props_specified = False
for name, settings in sorted(configurations.items()):
configuration = _GetConfigurationCondition(name, settings)
if settings.has_key('msbuild_props'):
if 'msbuild_props' in settings:
additional_props[configuration] = _FixPaths(settings['msbuild_props'])
props_specified = True
else:
@@ -251,7 +251,7 @@ except ImportError:
__all__.append('simple_diff')
def is_List(e):
return type(e) is types.ListType \
return type(e) is list \
or isinstance(e, collections.UserList)
try:
@@ -262,12 +262,12 @@ except ImportError:
if hasattr(types, 'UnicodeType'):
def is_String(e):
return type(e) is types.StringType \
or type(e) is types.UnicodeType \
return type(e) is bytes \
or type(e) is str \
or isinstance(e, UserString)
else:
def is_String(e):
return type(e) is types.StringType or isinstance(e, UserString)
return type(e) is bytes or isinstance(e, UserString)
tempfile.template = 'testcmd.'
if os.name in ('posix', 'nt'):
@@ -882,7 +882,7 @@ class TestCmd(object):
#self.diff_function = difflib.unified_diff
self._dirlist = []
self._preserve = {'pass_test': 0, 'fail_test': 0, 'no_result': 0}
if os.environ.has_key('PRESERVE') and not os.environ['PRESERVE'] is '':
if 'PRESERVE' in os.environ and not os.environ['PRESERVE'] is '':
self._preserve['pass_test'] = os.environ['PRESERVE']
self._preserve['fail_test'] = os.environ['PRESERVE']
self._preserve['no_result'] = os.environ['PRESERVE']
@@ -184,7 +184,7 @@ else:
module_suffix = '.so'
def is_List(e):
return type(e) is types.ListType \
return type(e) is list \
or isinstance(e, collections.UserList)
def is_writable(f):
@@ -326,7 +326,7 @@ class TestGypBase(TestCommon.TestCommon):
the tool-specific subclasses or clutter the tests themselves
with platform-specific code.
"""
if kw.has_key('SYMROOT'):
if 'SYMROOT' in kw:
del kw['SYMROOT']
super(TestGypBase, self).run(*args, **kw)
@@ -68,8 +68,8 @@ if sys.platform == 'win32':
test.fail_test(len(execution_level) != 1)
execution_level = execution_level[0].attributes
test.fail_test(not (
execution_level.has_key('level') and
execution_level.has_key('uiAccess') and
'level' in execution_level and
'uiAccess' in execution_level and
execution_level['level'].nodeValue == 'asInvoker' and
execution_level['uiAccess'].nodeValue == 'false'))
@@ -87,8 +87,8 @@ if sys.platform == 'win32':
test.fail_test(len(execution_level) != 1)
execution_level = execution_level[0].attributes
test.fail_test(not (
execution_level.has_key('level') and
execution_level.has_key('uiAccess') and
'level' in execution_level and
'uiAccess' in execution_level and
execution_level['level'].nodeValue == 'requireAdministrator' and
execution_level['uiAccess'].nodeValue == 'true'))
+2 -2
View File
@@ -39,7 +39,7 @@ import re, sys, types, copy, os
# This tuple contains known string types
try:
# Python 2.6
StringTypes = (types.StringType, types.UnicodeType)
StringTypes = (bytes, str)
except AttributeError:
# Python 3.0
StringTypes = (str, bytes)
@@ -49,7 +49,7 @@ except AttributeError:
if sys.version_info[0] < 3:
def func_code(f):
return f.func_code
return f.__code__
else:
def func_code(f):
return f.__code__
+3 -3
View File
@@ -89,14 +89,14 @@ import re, types, sys, os.path
# Compatibility function for python 2.6/3.0
if sys.version_info[0] < 3:
def func_code(f):
return f.func_code
return f.__code__
else:
def func_code(f):
return f.__code__
# Compatibility
try:
MAXINT = sys.maxint
MAXINT = sys.maxsize
except AttributeError:
MAXINT = sys.maxsize
@@ -1190,7 +1190,7 @@ class Production(object):
def __len__(self):
return len(self.prod)
def __nonzero__(self):
def __bool__(self):
return 1
def __getitem__(self,index):
+1 -1
View File
@@ -1185,7 +1185,7 @@ class Bits(object):
return h % 1442968193
# This is only used in Python 2.x...
def __nonzero__(self):
def __bool__(self):
"""Return True if any bits are set to 1, otherwise return False."""
return self.any(True)
+2 -2
View File
@@ -437,13 +437,13 @@ def format_docstring(docstring):
if not docstring:
return ''
lines = docstring.expandtabs().splitlines()
indent = sys.maxint
indent = sys.maxsize
for line in lines[1:]:
stripped = line.lstrip()
if stripped:
indent = min(indent, len(line) - len(stripped))
trimmed = [lines[0].strip()]
if indent < sys.maxint:
if indent < sys.maxsize:
for line in lines[1:]:
trimmed.append(line[indent:].rstrip())
while trimmed and not trimmed[-1]:
+2 -2
View File
@@ -209,7 +209,7 @@ def _copy_func_details(func, funcopy):
#funcopy.__dict__.update(func.__dict__)
funcopy.__module__ = func.__module__
if not inPy3k:
funcopy.func_defaults = func.func_defaults
funcopy.__defaults__ = func.__defaults__
return
funcopy.__defaults__ = func.__defaults__
funcopy.__kwdefaults__ = func.__kwdefaults__
@@ -1207,7 +1207,7 @@ class _patch(object):
# not in Python 3
patched.compat_co_firstlineno = getattr(
func, "compat_co_firstlineno",
func.func_code.co_firstlineno
func.__code__.co_firstlineno
)
return patched
+1 -1
View File
@@ -36,7 +36,7 @@ def dependency_map(lines):
deps = {}
for i, (indent, target) in enumerate(pairs):
if not deps.has_key(target):
if target not in deps:
deps[target] = []
for j in range(i+1, len(pairs)):
@@ -151,7 +151,7 @@ class CompileDBBackend(CommonBackend):
a = expand_variables(a, variables).split()
if not a:
continue
if isinstance(a, types.StringTypes):
if isinstance(a, (str,)):
c.append(a)
else:
c.extend(a)
@@ -216,7 +216,7 @@ class CompileDBBackend(CommonBackend):
value = cenv.substs.get(name)
if not value:
return
if isinstance(value, types.StringTypes):
if isinstance(value, (str,)):
value = value.split()
db.extend(value)
+13 -13
View File
@@ -438,7 +438,7 @@ class ConfigureSandbox(dict):
value = PositiveOptionValue()
elif value is False or value == ():
value = NegativeOptionValue()
elif isinstance(value, types.StringTypes):
elif isinstance(value, (str,)):
value = PositiveOptionValue((value,))
elif isinstance(value, tuple):
value = PositiveOptionValue(value)
@@ -478,7 +478,7 @@ class ConfigureSandbox(dict):
return value
def _dependency(self, arg, callee_name, arg_name=None):
if isinstance(arg, types.StringTypes):
if isinstance(arg, (str,)):
prefix, name, values = Option.split_option(arg)
if values != ():
raise ConfigureError("Option must not contain an '='")
@@ -623,7 +623,7 @@ class ConfigureSandbox(dict):
with self.only_when_impl(when):
what = self._resolve(what)
if what:
if not isinstance(what, types.StringTypes):
if not isinstance(what, (str,)):
raise TypeError("Unexpected type: '%s'" % type(what).__name__)
self.include_file(what)
@@ -697,7 +697,7 @@ class ConfigureSandbox(dict):
for value, required in (
(_import, True), (_from, False), (_as, False)):
if not isinstance(value, types.StringTypes) and (
if not isinstance(value, (str,)) and (
required or value is not None):
raise TypeError("Unexpected type: '%s'" % type(value).__name__)
if value is not None and not self.RE_MODULE.match(value):
@@ -760,7 +760,7 @@ class ConfigureSandbox(dict):
name = self._resolve(name, need_help_dependency=False)
if name is None:
return
if not isinstance(name, types.StringTypes):
if not isinstance(name, (str,)):
raise TypeError("Unexpected type: '%s'" % type(name).__name__)
if name in data:
raise ConfigureError(
@@ -850,7 +850,7 @@ class ConfigureSandbox(dict):
if isinstance(possible_reasons[0], Option):
reason = possible_reasons[0]
if not reason and (isinstance(value, (bool, tuple)) or
isinstance(value, types.StringTypes)):
isinstance(value, (str,))):
# A reason can be provided automatically when imply_option
# is called with an immediate value.
_, filename, line, _, _, _ = inspect.stack()[1]
@@ -885,10 +885,10 @@ class ConfigureSandbox(dict):
if not inspect.isfunction(func):
raise TypeError("Unexpected type: '%s'" % type(func).__name__)
if func in self._prepared_functions:
return func, func.func_globals
return func, func.__globals__
glob = SandboxedGlobal(
(k, v) for k, v in func.func_globals.items()
(k, v) for k, v in func.__globals__.items()
if (inspect.isfunction(v) and v not in self._templates) or (
inspect.isclass(v) and issubclass(v, Exception))
)
@@ -909,20 +909,20 @@ class ConfigureSandbox(dict):
# Note this is not entirely bullet proof (if the value is e.g. a list,
# the list contents could have changed), but covers the bases.
closure = None
if func.func_closure:
if func.__closure__:
def makecell(content):
def f():
content
return f.func_closure[0]
return f.__closure__[0]
closure = tuple(makecell(cell.cell_contents)
for cell in func.func_closure)
for cell in func.__closure__)
new_func = wraps(func)(types.FunctionType(
func.func_code,
func.__code__,
glob,
func.__name__,
func.func_defaults,
func.__defaults__,
closure
))
@wraps(new_func)
+1 -1
View File
@@ -42,7 +42,7 @@ class LintSandbox(ConfigureSandbox):
# - don't use @imports
# - don't have a closure
# - don't use global variables
if func in self._imports or func.func_closure:
if func in self._imports or func.__closure__:
return True
for op, arg in disassemble_as_iter(func):
if op in ('LOAD_GLOBAL', 'STORE_GLOBAL'):
@@ -12,9 +12,9 @@ import inspect
# returns an iterator.
def disassemble_as_iter(co):
if inspect.ismethod(co):
co = co.im_func
co = co.__func__
if inspect.isfunction(co):
co = co.func_code
co = co.__code__
code = co.co_code
n = len(code)
i = 0
@@ -12,7 +12,7 @@ from collections import OrderedDict
def istupleofstrings(obj):
return isinstance(obj, tuple) and len(obj) and all(
isinstance(o, types.StringTypes) for o in obj)
isinstance(o, (str,)) for o in obj)
class OptionValue(tuple):
@@ -71,7 +71,7 @@ class PositiveOptionValue(OptionValue):
in the form of a tuple for when values are given to the option (in the form
--option=value[,value2...].
'''
def __nonzero__(self):
def __bool__(self):
return True
@@ -132,7 +132,7 @@ class Option(object):
'At least an option name or an environment variable name must '
'be given')
if name:
if not isinstance(name, types.StringTypes):
if not isinstance(name, (str,)):
raise InvalidOptionError('Option must be a string')
if not name.startswith('--'):
raise InvalidOptionError('Option must start with `--`')
@@ -141,7 +141,7 @@ class Option(object):
if not name.islower():
raise InvalidOptionError('Option must be all lowercase')
if env:
if not isinstance(env, types.StringTypes):
if not isinstance(env, (str,)):
raise InvalidOptionError(
'Environment variable name must be a string')
if not env.isupper():
@@ -151,8 +151,8 @@ class Option(object):
isinstance(nargs, int) and nargs >= 0):
raise InvalidOptionError(
"nargs must be a positive integer, '?', '*' or '+'")
if (not isinstance(default, types.StringTypes) and
not isinstance(default, (bool, types.NoneType)) and
if (not isinstance(default, (str,)) and
not isinstance(default, (bool, type(None))) and
not istupleofstrings(default)):
raise InvalidOptionError(
'default must be a bool, a string or a tuple of strings')
@@ -224,7 +224,7 @@ class Option(object):
', '.join("'%s'" % c for c in choices))
elif has_choices:
maxargs = self.maxargs
if len(choices) < maxargs and maxargs != sys.maxint:
if len(choices) < maxargs and maxargs != sys.maxsize:
raise InvalidOptionError('Not enough `choices` for `nargs`')
self.choices = choices
self.help = help
@@ -238,7 +238,7 @@ class Option(object):
where prefix is one of 'with', 'without', 'enable' or 'disable'.
The '=values' part is optional. Values are separated with commas.
'''
if not isinstance(option, types.StringTypes):
if not isinstance(option, (str,)):
raise InvalidOptionError('Option must be a string')
elements = option.split('=', 1)
@@ -291,7 +291,7 @@ class Option(object):
def maxargs(self):
if isinstance(self.nargs, int):
return self.nargs
return 1 if self.nargs == '?' else sys.maxint
return 1 if self.nargs == '?' else sys.maxsize
def _validate_nargs(self, num):
minargs, maxargs = self.minargs, self.maxargs
@@ -643,7 +643,7 @@ class CCacheStats(object):
return '\n'.join(lines)
def __nonzero__(self):
def __bool__(self):
relative_values = [v for k, v in list(self._values.items())
if k not in self.ABSOLUTE_KEYS]
return (all(v >= 0 for v in relative_values) and
@@ -343,7 +343,7 @@ def read_from_gyp(config, path, output, vars, no_chromium, no_unified, action_ov
if not f:
continue
# the result may be a string or a list.
if isinstance(f, types.StringTypes):
if isinstance(f, (str,)):
context[var].append(f)
else:
context[var].extend(f)
+10 -10
View File
@@ -84,7 +84,7 @@ from functools import reduce
if sys.version_info.major == 2:
text_type = str
type_type = types.TypeType
type_type = type
else:
text_type = str
type_type = type
@@ -310,7 +310,7 @@ class MozbuildSandbox(Sandbox):
raise Exception('`template` is a function decorator. You must '
'use it as `@template` preceding a function declaration.')
name = func.func_name
name = func.__name__
if name in self.templates:
raise KeyError(
@@ -406,10 +406,10 @@ class MozbuildSandbox(Sandbox):
class TemplateFunction(object):
def __init__(self, func, sandbox):
self.path = func.func_code.co_filename
self.name = func.func_name
self.path = func.__code__.co_filename
self.name = func.__name__
code = func.func_code
code = func.__code__
firstlineno = code.co_firstlineno
lines = sandbox._current_source.splitlines(True)
lines = inspect.getblock(lines[firstlineno - 1:])
@@ -448,8 +448,8 @@ class TemplateFunction(object):
compile(func_ast, self.path, 'exec'),
glob,
self.name,
func.func_defaults,
func.func_closure,
func.__defaults__,
func.__closure__,
)
func()
@@ -463,11 +463,11 @@ class TemplateFunction(object):
'__builtins__': sandbox._builtins
}
func = types.FunctionType(
self._func.func_code,
self._func.__code__,
glob,
self.name,
self._func.func_defaults,
self._func.func_closure
self._func.__defaults__,
self._func.__closure__
)
sandbox.exec_function(func, args, kwargs, self.path,
becomes_current_path=False)
+1 -1
View File
@@ -66,7 +66,7 @@ class _SimpleOrderedSet(object):
self._list = []
self._set = set()
def __nonzero__(self):
def __bool__(self):
return bool(self._set)
def __iter__(self):
+4 -4
View File
@@ -293,14 +293,14 @@ class Preprocessor:
self.cmds = {}
for cmd, level in {'define': 0,
'undef': 0,
'if': sys.maxint,
'ifdef': sys.maxint,
'ifndef': sys.maxint,
'if': sys.maxsize,
'ifdef': sys.maxsize,
'ifndef': sys.maxsize,
'else': 1,
'elif': 1,
'elifdef': 1,
'elifndef': 1,
'endif': sys.maxint,
'endif': sys.maxsize,
'expand': 0,
'literal': 0,
'filter': 0,
@@ -43,7 +43,7 @@ class CompilerPreprocessor(Preprocessor):
# Hack around it enough that the configure tests work properly.
context = self.context
def normalize_numbers(value):
if isinstance(value, types.StringTypes):
if isinstance(value, (str,)):
if value[-1:] == 'L' and value[:-1].isdigit():
value = int(value[:-1])
return value
+3 -3
View File
@@ -381,7 +381,7 @@ class ListMixin(object):
def __add__(self, other):
# Allow None and EmptyValue is a special case because it makes undefined
# variable references in moz.build behave better.
other = [] if isinstance(other, (types.NoneType, EmptyValue)) else other
other = [] if isinstance(other, (type(None), EmptyValue)) else other
if not isinstance(other, list):
raise ValueError('Only lists can be appended to lists.')
@@ -390,7 +390,7 @@ class ListMixin(object):
return new_list
def __iadd__(self, other):
other = [] if isinstance(other, (types.NoneType, EmptyValue)) else other
other = [] if isinstance(other, (type(None), EmptyValue)) else other
if not isinstance(other, list):
raise ValueError('Only lists can be appended to lists.')
@@ -1122,7 +1122,7 @@ def expand_variables(s, variables):
value = variables.get(name)
if not value:
continue
if not isinstance(value, types.StringTypes):
if not isinstance(value, (str,)):
value = ' '.join(value)
result += value
return result
+2 -2
View File
@@ -52,7 +52,7 @@ if sys.version_info[:2] == (2, 6):
something on __getattr__ calls (see #1035).
Backport of https://hg.python.org/cpython/rev/35bf8f7a8edc
"""
return isinstance(object, (type, types.ClassType))
return isinstance(object, (type, type))
def _has_positional_arg(func):
return func.__code__.co_argcount
@@ -96,7 +96,7 @@ def getimfunc(func):
return func.__func__
except AttributeError:
try:
return func.im_func
return func.__func__
except AttributeError:
return func
+1 -1
View File
@@ -112,7 +112,7 @@ class MarkEvaluator:
try:
d.update(func.__globals__)
except AttributeError:
d.update(func.func_globals)
d.update(func.__globals__)
return d
def _istrue(self):
+1 -1
View File
@@ -464,7 +464,7 @@ Representer.add_representer(tuple,
Representer.add_representer(type,
Representer.represent_name)
Representer.add_representer(types.ClassType,
Representer.add_representer(type,
Representer.represent_name)
Representer.add_representer(types.FunctionType,
+1 -1
View File
@@ -609,7 +609,7 @@ class Response(object):
"""Returns true if :attr:`status_code` is 'OK'."""
return self.ok
def __nonzero__(self):
def __bool__(self):
"""Returns true if :attr:`status_code` is 'OK'."""
return self.ok
@@ -41,7 +41,7 @@ if PY3:
else:
string_types = basestring,
integer_types = (int, int)
class_types = (type, types.ClassType)
class_types = (type, type)
text_type = str
binary_type = str
@@ -242,7 +242,7 @@ if PY3:
return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
else:
def get_unbound_function(unbound):
return unbound.im_func
return unbound.__func__
class Iterator(object):
+1 -1
View File
@@ -25,7 +25,7 @@ from struct import pack
try:
MAX_INT = sys.maxsize
except AttributeError:
MAX_INT = sys.maxint
MAX_INT = sys.maxsize
MAX_INT64 = (1 << 63) - 1
MAX_INT32 = (1 << 31) - 1
+5 -5
View File
@@ -55,14 +55,14 @@ def bytes2int(bytes):
8405007
"""
if not (type(bytes) is types.ListType or type(bytes) is types.StringType):
if not (type(bytes) is list or type(bytes) is bytes):
raise TypeError("You must pass a string or a list")
# Convert byte stream to integer
integer = 0
for byte in bytes:
integer *= 256
if type(byte) is types.StringType: byte = ord(byte)
if type(byte) is bytes: byte = ord(byte)
integer += byte
return integer
@@ -74,7 +74,7 @@ def int2bytes(number):
123456789
"""
if not (type(number) is types.LongType or type(number) is types.IntType):
if not (type(number) is int or type(number) is int):
raise TypeError("You must pass a long or an int")
string = ""
@@ -330,10 +330,10 @@ def encrypt_int(message, ekey, n):
"""Encrypts a message using encryption key 'ekey', working modulo
n"""
if type(message) is types.IntType:
if type(message) is int:
return encrypt_int(int(message), ekey, n)
if not type(message) is types.LongType:
if not type(message) is int:
raise TypeError("You must pass a long or an int")
if message > 0 and \
+10 -10
View File
@@ -52,14 +52,14 @@ def bytes2int(bytes):
8405007
"""
if not (type(bytes) is types.ListType or type(bytes) is types.StringType):
if not (type(bytes) is list or type(bytes) is bytes):
raise TypeError("You must pass a string or a list")
# Convert byte stream to integer
integer = 0
for byte in bytes:
integer *= 256
if type(byte) is types.StringType: byte = ord(byte)
if type(byte) is bytes: byte = ord(byte)
integer += byte
return integer
@@ -69,7 +69,7 @@ def int2bytes(number):
Converts a number to a string of bytes
"""
if not (type(number) is types.LongType or type(number) is types.IntType):
if not (type(number) is int or type(number) is int):
raise TypeError("You must pass a long or an int")
string = ""
@@ -88,7 +88,7 @@ def to64(number):
'A'
"""
if not (type(number) is types.LongType or type(number) is types.IntType):
if not (type(number) is int or type(number) is int):
raise TypeError("You must pass a long or an int")
if 0 <= number <= 9: #00-09 translates to '0' - '9'
@@ -117,7 +117,7 @@ def from64(number):
1
"""
if not (type(number) is types.LongType or type(number) is types.IntType):
if not (type(number) is int or type(number) is int):
raise TypeError("You must pass a long or an int")
if 48 <= number <= 57: #ord('0') - ord('9') translates to 0-9
@@ -146,7 +146,7 @@ def int2str64(number):
'7MyqL'
"""
if not (type(number) is types.LongType or type(number) is types.IntType):
if not (type(number) is int or type(number) is int):
raise TypeError("You must pass a long or an int")
string = ""
@@ -166,13 +166,13 @@ def str642int(string):
123456789
"""
if not (type(string) is types.ListType or type(string) is types.StringType):
if not (type(string) is list or type(string) is bytes):
raise TypeError("You must pass a string or a list")
integer = 0
for byte in string:
integer *= 64
if type(byte) is types.StringType: byte = ord(byte)
if type(byte) is bytes: byte = ord(byte)
integer += from64(byte)
return integer
@@ -393,10 +393,10 @@ def newkeys(nbits):
def encrypt_int(message, ekey, n):
"""Encrypts a message using encryption key 'ekey', working modulo n"""
if type(message) is types.IntType:
if type(message) is int:
message = int(message)
if not type(message) is types.LongType:
if not type(message) is int:
raise TypeError("You must pass a long or int")
if message < 0 or message > n:
+1 -1
View File
@@ -122,7 +122,7 @@ def raises(exc, msg=None, regex=None):
class Undefined(object):
def __nonzero__(self):
def __bool__(self):
return False
def __repr__(self):
+2 -2
View File
@@ -409,13 +409,13 @@ def build(targets=[]):
log.debug("build(targets=%r)" % targets)
available = _getTargets()
if not targets:
if available.has_key('default'):
if 'default' in available:
return available['default']()
else:
log.warn("No default target available. Doing nothing.")
else:
for target in targets:
if available.has_key(target):
if target in available:
retval = available[target]()
if retval:
raise Error("Error running '%s' target: retval=%s"\
+1 -1
View File
@@ -37,7 +37,7 @@ def run(argv):
results. Returns (<stdout lines>, <stderr lines>, <return value>).
Note: 'argv' may also just be the command string.
"""
if type(argv) in (types.ListType, types.TupleType):
if type(argv) in (list, tuple):
cmd = _joinArgv(argv)
else:
cmd = argv
@@ -47,7 +47,7 @@ class MemorizingFile(object):
the control reaches WebSocketRequestHandler.
"""
def __init__(self, file_, max_memorized_lines=sys.maxint):
def __init__(self, file_, max_memorized_lines=sys.maxsize):
"""Construct an instance.
Args:
@@ -1392,7 +1392,7 @@ class _HandshakeDeltaBase(object):
for key, value in list(delta.items()):
# The spec requires that a header with an empty value is
# removed from the delta base.
if len(value) == 0 and headers.has_key(key):
if len(value) == 0 and key in headers:
del headers[key]
else:
headers[key] = value
@@ -27,8 +27,8 @@ class DMError(Exception):
def abstractmethod(method):
line = method.func_code.co_firstlineno
filename = method.func_code.co_filename
line = method.__code__.co_firstlineno
filename = method.__code__.co_filename
@wraps(method)
def not_implemented(*args, **kwargs):
@@ -48,7 +48,7 @@ class DeviceManagerTestLoader(unittest.TestLoader):
module = __import__(module_name)
for name in dir(module):
obj = getattr(module, name)
if (isinstance(obj, (type, types.ClassType)) and
if (isinstance(obj, (type, type)) and
issubclass(obj, unittest.TestCase)) and \
(not self.isTestDevice or obj.runs_on_test_device):
tests.append(self.loadTestsFromTestCase(obj))
+1 -1
View File
@@ -24,7 +24,7 @@ _os = os
class unknown(object):
"""marker class for unknown information"""
def __nonzero__(self):
def __bool__(self):
return False
def __str__(self):
@@ -7,7 +7,7 @@ from . import base
def format_test_id(test_id):
"""Take a test id and return something that looks a bit like
a class path"""
if type(test_id) not in types.StringTypes:
if type(test_id) not in (str,):
# Not sure how to deal with reftests yet
raise NotImplementedError
@@ -121,14 +121,14 @@ class ProcessHandlerMixin(object):
thread = threading.current_thread().name
print(("DBG::MOZPROC PID:{} ({}) | {}".format(self.pid, thread, msg)))
def __del__(self, _maxint=sys.maxint):
def __del__(self, _maxint=sys.maxsize):
if isWin:
handle = getattr(self, '_handle', None)
if handle:
if hasattr(self, '_internal_poll'):
self._internal_poll(_deadstate=_maxint)
else:
self.poll(_deadstate=sys.maxint)
self.poll(_deadstate=sys.maxsize)
if handle or self._job or self._io_port:
self._cleanup()
else:
@@ -13,8 +13,8 @@ except ImportError:
# abc is python 2.6+
# from https://github.com/mozilla/mozbase/blob/master/mozdevice/mozdevice/devicemanager.py
def abstractmethod(method):
line = method.func_code.co_firstlineno
filename = method.func_code.co_filename
line = method.__code__.co_firstlineno
filename = method.__code__.co_filename
def not_implemented(*args, **kwargs):
raise NotImplementedError('Abstract method %s at File "%s", '
+1 -1
View File
@@ -21,7 +21,7 @@ _os = os
class unknown(object):
"""marker class for unknown information"""
def __nonzero__(self):
def __bool__(self):
return False
def __str__(self):
return 'UNKNOWN'
@@ -98,13 +98,13 @@ class ProcessHandlerMixin(object):
print(args, file=sys.stderr)
raise
def __del__(self, _maxint=sys.maxint):
def __del__(self, _maxint=sys.maxsize):
if isWin:
if self._handle:
if hasattr(self, '_internal_poll'):
self._internal_poll(_deadstate=_maxint)
else:
self.poll(_deadstate=sys.maxint)
self.poll(_deadstate=sys.maxsize)
if self._handle or self._job or self._io_port:
self._cleanup()
else:
+1 -1
View File
@@ -176,7 +176,7 @@ class Cache(object):
self.sem.acquire()
self.semlock.release()
try:
if not self.db.has_key(key):
if key not in self.db:
return None
# returns status, headers, content
return self.db[key]