Skip to content

Commit

Permalink
Clean up a bunch of lint errors.
Browse files Browse the repository at this point in the history
For #656.

I had to leave a few due to us still having one py2 rdep (maybe?).

PiperOrigin-RevId: 328639524
  • Loading branch information
rchen152 committed Aug 27, 2020
1 parent 0a40a88 commit e63f511
Show file tree
Hide file tree
Showing 59 changed files with 257 additions and 263 deletions.
128 changes: 62 additions & 66 deletions pytype/abstract.py

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions pytype/abstract_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
class AbstractTestBase(test_base.UnitTest):

def setUp(self):
super(AbstractTestBase, self).setUp()
super().setUp()
options = config.Options.create(python_version=self.python_version)
self._vm = vm.VirtualMachine(
errors.ErrorLog(), options, load_pytd.Loader(None, self.python_version))
Expand All @@ -46,7 +46,7 @@ def new_dict(self, **kwargs):
class IsInstanceTest(AbstractTestBase):

def setUp(self):
super(IsInstanceTest, self).setUp()
super().setUp()
self._is_instance = special_builtins.IsInstance.make(self._vm)
# Easier access to some primitive instances.
self._bool = self._vm.convert.primitive_class_instances[bool]
Expand Down
6 changes: 3 additions & 3 deletions pytype/abstract_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ class GenericTypeError(Exception):
"""The error for user-defined generic types."""

def __init__(self, annot, error):
super(GenericTypeError, self).__init__(annot, error)
super().__init__(annot, error)
self.annot = annot
self.error = error

Expand Down Expand Up @@ -488,9 +488,9 @@ def compute_template(val):
seqs.append(seq)
try:
template.extend(mro.MergeSequences(seqs))
except ValueError:
except ValueError as e:
raise GenericTypeError(
val, "Illegal type parameter order in class %s" % val.name)
val, "Illegal type parameter order in class %s" % val.name) from e

return template

Expand Down
2 changes: 1 addition & 1 deletion pytype/abstract_utils_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
class GetViewsTest(test_base.UnitTest):

def setUp(self):
super(GetViewsTest, self).setUp()
super().setUp()
self._vm = vm.VirtualMachine(
errors.ErrorLog(), config.Options.create(
python_version=self.python_version),
Expand Down
2 changes: 1 addition & 1 deletion pytype/analyze.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ class CallTracer(vm.VirtualMachine):
_CONSTRUCTORS = ("__new__", "__init__")

def __init__(self, *args, **kwargs):
super(CallTracer, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self._unknowns = {}
self._builtin_map = {}
self._calls = set()
Expand Down
2 changes: 1 addition & 1 deletion pytype/attribute_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
class AttributeTest(test_base.UnitTest):

def setUp(self):
super(AttributeTest, self).setUp()
super().setUp()
options = config.Options.create(python_version=self.python_version)
self._vm = vm.VirtualMachine(
errors.ErrorLog(), options, load_pytd.Loader(None, self.python_version))
Expand Down
6 changes: 3 additions & 3 deletions pytype/compare_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
class CompareTestBase(test_base.UnitTest):

def setUp(self):
super(CompareTestBase, self).setUp()
super().setUp()
options = config.Options.create(python_version=self.python_version)
self._vm = vm.VirtualMachine(
errors.ErrorLog(), options, load_pytd.Loader(None, self.python_version))
Expand Down Expand Up @@ -87,7 +87,7 @@ def test_compare_frozensets(self):
class TupleTest(CompareTestBase):

def setUp(self):
super(TupleTest, self).setUp()
super().setUp()
self._var = self._program.NewVariable()
self._var.AddBinding(abstract.Unknown(self._vm), [], self._node)

Expand Down Expand Up @@ -119,7 +119,7 @@ def test_getitem__abstract_index(self):
class DictTest(CompareTestBase):

def setUp(self):
super(DictTest, self).setUp()
super().setUp()
self._d = abstract.Dict(self._vm)
self._var = self._program.NewVariable()
self._var.AddBinding(abstract.Unknown(self._vm), [], self._node)
Expand Down
2 changes: 1 addition & 1 deletion pytype/config_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def test_arg_conflicts(self):
class PostprocessorTest(unittest.TestCase):

def setUp(self):
super(PostprocessorTest, self).setUp()
super().setUp()
self.output_options = datatypes.SimpleNamespace()

def test_input(self):
Expand Down
4 changes: 2 additions & 2 deletions pytype/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,11 @@ class Converter(utils.VirtualMachineWeakrefMixin):
class TypeParameterError(Exception):

def __init__(self, type_param_name):
super(Converter.TypeParameterError, self).__init__(type_param_name)
super().__init__(type_param_name)
self.type_param_name = type_param_name

def __init__(self, vm):
super(Converter, self).__init__(vm)
super().__init__(vm)
self.vm.convert = self # to make constant_to_value calls below work
self.pytd_convert = output.Converter(vm)

Expand Down
2 changes: 1 addition & 1 deletion pytype/convert_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
class ConvertTest(test_base.UnitTest):

def setUp(self):
super(ConvertTest, self).setUp()
super().setUp()
options = config.Options.create(python_version=self.python_version)
self._vm = vm.VirtualMachine(
errors.ErrorLog(), options, load_pytd.Loader(None, self.python_version))
Expand Down
2 changes: 1 addition & 1 deletion pytype/debug_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def __repr__(self):
class DebugTest(unittest.TestCase):

def setUp(self):
super(DebugTest, self).setUp()
super().setUp()
self.prog = cfg.Program()
self.current_location = self.prog.NewCFGNode()

Expand Down
4 changes: 2 additions & 2 deletions pytype/directors.py
Original file line number Diff line number Diff line change
Expand Up @@ -382,8 +382,8 @@ def _process_pytype(self, lineno, data, open_ended):
try:
command, values = option.split("=", 1)
values = values.split(",")
except ValueError:
raise _DirectiveError("Invalid directive syntax.")
except ValueError as e:
raise _DirectiveError("Invalid directive syntax.") from e
# Additional commands may be added in the future. For now, only
# "disable" and "enable" are supported.
if command == "disable":
Expand Down
25 changes: 14 additions & 11 deletions pytype/function.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,8 +302,11 @@ def __new__(cls, posargs, namedargs=None, starargs=None, starstarargs=None):
"""
assert isinstance(posargs, tuple), posargs
cls.replace = cls._replace
return super(Args, cls).__new__(
cls, posargs=posargs, namedargs=namedargs or {}, starargs=starargs,
return super().__new__(
cls,
posargs=posargs,
namedargs=namedargs or {},
starargs=starargs,
starstarargs=starstarargs)

def starargs_as_tuple(self, node, vm):
Expand Down Expand Up @@ -374,7 +377,7 @@ class ReturnValueMixin(object):
"""Mixin for exceptions that hold a return node and variable."""

def __init__(self):
super(ReturnValueMixin, self).__init__()
super().__init__()
self.return_node = None
self.return_variable = None

Expand All @@ -399,23 +402,23 @@ class NotCallable(FailedFunctionCall):
"""For objects that don't have __call__."""

def __init__(self, obj):
super(NotCallable, self).__init__()
super().__init__()
self.obj = obj


class UndefinedParameterError(FailedFunctionCall):
"""Function called with an undefined variable."""

def __init__(self, name):
super(UndefinedParameterError, self).__init__()
super().__init__()
self.name = name


class DictKeyMissing(Exception, ReturnValueMixin):
"""When retrieving a key that does not exist in a dict."""

def __init__(self, name):
super(DictKeyMissing, self).__init__()
super().__init__()
self.name = name

def __gt__(self, other):
Expand All @@ -432,7 +435,7 @@ class InvalidParameters(FailedFunctionCall):
"""Exception for functions called with an incorrect parameter combination."""

def __init__(self, sig, passed_args, vm, bad_param=None):
super(InvalidParameters, self).__init__()
super().__init__()
self.name = sig.name
passed_args = [(name, vm.merge_values(arg.data))
for name, arg, _ in sig.iter_args(passed_args)]
Expand All @@ -456,23 +459,23 @@ class WrongKeywordArgs(InvalidParameters):
"""E.g. an arg "x" is passed to a function that doesn't have an "x" param."""

def __init__(self, sig, passed_args, vm, extra_keywords):
super(WrongKeywordArgs, self).__init__(sig, passed_args, vm)
super().__init__(sig, passed_args, vm)
self.extra_keywords = tuple(extra_keywords)


class DuplicateKeyword(InvalidParameters):
"""E.g. an arg "x" is passed to a function as both a posarg and a kwarg."""

def __init__(self, sig, passed_args, vm, duplicate):
super(DuplicateKeyword, self).__init__(sig, passed_args, vm)
super().__init__(sig, passed_args, vm)
self.duplicate = duplicate


class MissingParameter(InvalidParameters):
"""E.g. a function requires parameter 'x' but 'x' isn't passed."""

def __init__(self, sig, passed_args, vm, missing_parameter):
super(MissingParameter, self).__init__(sig, passed_args, vm)
super().__init__(sig, passed_args, vm)
self.missing_parameter = missing_parameter
# pylint: enable=g-bad-exception-name

Expand All @@ -496,7 +499,7 @@ class PyTDSignature(utils.VirtualMachineWeakrefMixin):
"""

def __init__(self, name, pytd_sig, vm):
super(PyTDSignature, self).__init__(vm)
super().__init__(vm)
self.name = name
self.pytd_sig = pytd_sig
self.param_types = [
Expand Down
19 changes: 10 additions & 9 deletions pytype/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,9 @@ def read_source_file(input_filename):
else:
with open(input_filename, "rb") as fi:
return fi.read().decode("utf8")
except IOError:
raise utils.UsageError("Could not load input file %s" % input_filename)
except IOError as e:
raise utils.UsageError("Could not load input file %s" %
input_filename) from e


def _set_verbosity_from(posarg):
Expand Down Expand Up @@ -167,7 +168,7 @@ def check_or_generate_pyi(options, loader=None):
result += "# skip-file found, file not analyzed"
except Exception as e: # pylint: disable=broad-except
if options.nofail:
log.warn("***Caught exception: %s", str(e), exc_info=True)
log.warning("***Caught exception: %s", str(e), exc_info=True)
if not options.check:
result += ( # pytype: disable=name-error
"# Caught error in pytype: " + str(e).replace("\n", "\n#")
Expand Down Expand Up @@ -246,7 +247,7 @@ def write_pickle(ast, options, loader=None):
ast = serialize_ast.PrepareForExport(
options.module_name,
pytd_builtins.GetDefaultAst(options.python_version), loader)
log.warn("***Caught exception: %s", str(e), exc_info=True)
log.warning("***Caught exception: %s", str(e), exc_info=True)
else:
raise
if options.verify_pickle:
Expand Down Expand Up @@ -319,17 +320,17 @@ def wrap_pytype_exceptions(exception_type, filename=""):
try:
yield
except utils.UsageError as e:
raise exception_type("Pytype usage error: %s" % utils.message(e))
raise exception_type("Pytype usage error: %s" % utils.message(e)) from e
except pyc.CompileError as e:
raise exception_type("Error reading file %s at line %s: %s" %
(filename, e.lineno, e.error))
(filename, e.lineno, e.error)) from e
except tokenize.TokenError as e:
msg, (lineno, unused_column) = e.args # pylint: disable=unbalanced-tuple-unpacking
raise exception_type("Error reading file %s at line %s: %s" %
(filename, lineno, msg))
except directors.SkipFileError:
(filename, lineno, msg)) from e
except directors.SkipFileError as e:
raise exception_type("Pytype could not analyze file %s: "
"'# skip-file' directive found" % filename)
"'# skip-file' directive found" % filename) from e
except Exception as e: # pylint: disable=broad-except
msg = "Pytype error: %s: %s" % (e.__class__.__name__, e.args[0])
# We need the version check here because six.reraise doesn't work properly
Expand Down
12 changes: 6 additions & 6 deletions pytype/load_pytd.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ class BadDependencyError(Exception):

def __init__(self, module_error, src=None):
referenced = ", referenced from %r" % src if src else ""
super(BadDependencyError, self).__init__(module_error + referenced)
super().__init__(module_error + referenced)

def __str__(self):
return utils.message(self)
Expand Down Expand Up @@ -347,7 +347,7 @@ def _resolve_external_types(self, pyval, ast_name=None):
self._get_module_map(), self_name=name,
module_alias_map=self._aliases))
except KeyError as e:
raise BadDependencyError(utils.message(e), name)
raise BadDependencyError(utils.message(e), name) from e
return pyval

def _finish_pyi(self, pyval, ast=None):
Expand All @@ -359,7 +359,7 @@ def _verify_pyi(self, pyval, ast_name=None):
try:
pyval.Visit(visitors.VerifyLookup(ignore_late_types=True))
except ValueError as e:
raise BadDependencyError(utils.message(e), ast_name or pyval.name)
raise BadDependencyError(utils.message(e), ast_name or pyval.name) from e
pyval.Visit(visitors.VerifyContainers())

def resolve_type(self, pyval, ast):
Expand Down Expand Up @@ -633,7 +633,7 @@ class PickledPyiLoader(Loader):
"""A Loader which always loads pickle instead of PYI, for speed."""

def __init__(self, *args, **kwargs):
super(PickledPyiLoader, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)

@classmethod
def load_from_pickle(cls, filename, base_module, **kwargs):
Expand Down Expand Up @@ -675,7 +675,7 @@ def _unpickle_module(self, module):
def load_file(self, module_name, filename, ast=None):
"""Load (or retrieve from cache) a module and resolve its dependencies."""
if not is_pickle(filename):
return super(PickledPyiLoader, self).load_file(module_name, filename, ast)
return super().load_file(module_name, filename, ast)
existing = self._get_existing_ast(module_name)
if existing:
return existing
Expand All @@ -691,7 +691,7 @@ def load_file(self, module_name, filename, ast=None):
ast = serialize_ast.ProcessAst(loaded_ast, self._get_module_map())
except serialize_ast.UnrestorableDependencyError as e:
del self._modules[module_name]
raise BadDependencyError(utils.message(e), module_name)
raise BadDependencyError(utils.message(e), module_name) from e
# Mark all the module's late dependencies as explicitly imported.
for d, _ in loaded_ast.late_dependencies:
if d != loaded_ast.ast.name:
Expand Down
2 changes: 1 addition & 1 deletion pytype/matcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class AbstractMatcher(utils.VirtualMachineWeakrefMixin):
"""Matcher for abstract values."""

def __init__(self, vm):
super(AbstractMatcher, self).__init__(vm)
super().__init__(vm)
self._protocol_cache = set()

def _set_error_subst(self, subst):
Expand Down
2 changes: 1 addition & 1 deletion pytype/matcher_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class MatcherTest(test_base.UnitTest):
"""Test matcher.AbstractMatcher."""

def setUp(self):
super(MatcherTest, self).setUp()
super().setUp()
options = config.Options.create(python_version=self.python_version)
self.vm = vm.VirtualMachine(
errors.ErrorLog(), options, load_pytd.Loader(None, self.python_version))
Expand Down
6 changes: 3 additions & 3 deletions pytype/metaclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class AddMetaclassInstance(abstract.AtomicAbstractValue):
"""AddMetaclass instance (constructed by AddMetaclass.call())."""

def __init__(self, meta, vm, module_name):
super(AddMetaclassInstance, self).__init__("AddMetaclassInstance", vm)
super().__init__("AddMetaclassInstance", vm)
self.meta = meta
self.module_name = module_name

Expand All @@ -45,7 +45,7 @@ class AddMetaclass(abstract.PyTDFunction):

@classmethod
def make(cls, name, vm, module_name):
self = super(AddMetaclass, cls).make(name, vm, module_name)
self = super().make(name, vm, module_name)
self.module_name = module_name
return self

Expand All @@ -62,7 +62,7 @@ class WithMetaclassInstance(abstract.AtomicAbstractValue):
"""Anonymous class created by with_metaclass."""

def __init__(self, vm, cls, bases):
super(WithMetaclassInstance, self).__init__("WithMetaclassInstance", vm)
super().__init__("WithMetaclassInstance", vm)
self.cls = cls
self.bases = bases

Expand Down
Loading

0 comments on commit e63f511

Please sign in to comment.