From e034e8e117be72ca12f483587f07939e4ab25f72 Mon Sep 17 00:00:00 2001 From: Ram Rachum Date: Fri, 12 Jun 2020 23:21:55 +0300 Subject: [PATCH] Fix exception causes all over the codebase --- mypy/build.py | 4 ++-- mypy/dmypy/client.py | 4 ++-- mypy/dmypy_util.py | 4 ++-- mypy/ipc.py | 14 +++++++------- mypy/main.py | 5 +++-- mypy/moduleinspect.py | 2 +- mypy/stubgen.py | 4 ++-- mypy/stubtest.py | 2 +- mypy/stubutil.py | 4 ++-- mypy/suggestions.py | 4 ++-- mypy/util.py | 2 +- mypyc/test/test_run.py | 2 +- 12 files changed, 26 insertions(+), 25 deletions(-) diff --git a/mypy/build.py b/mypy/build.py index e7f3a047dbe7..f372f3d087a1 100644 --- a/mypy/build.py +++ b/mypy/build.py @@ -1988,13 +1988,13 @@ def parse_file(self) -> None: raise CompileError([ "mypy: can't read file '{}': {}".format( self.path, os.strerror(ioerr.errno))], - module_with_blocker=self.id) + module_with_blocker=self.id) from ioerr except (UnicodeDecodeError, DecodeError) as decodeerr: if self.path.endswith('.pyd'): err = "mypy: stubgen does not support .pyd files: '{}'".format(self.path) else: err = "mypy: can't decode file '{}': {}".format(self.path, str(decodeerr)) - raise CompileError([err], module_with_blocker=self.id) + raise CompileError([err], module_with_blocker=self.id) from decodeerr else: assert source is not None self.source_hash = compute_hash(source) diff --git a/mypy/dmypy/client.py b/mypy/dmypy/client.py index 80f03743086c..b02ac23a0be9 100644 --- a/mypy/dmypy/client.py +++ b/mypy/dmypy/client.py @@ -534,8 +534,8 @@ def read_status(status_file: str) -> Dict[str, object]: with open(status_file) as f: try: data = json.load(f) - except Exception: - raise BadStatus("Malformed status file (not JSON)") + except Exception as e: + raise BadStatus("Malformed status file (not JSON)") from e if not isinstance(data, dict): raise BadStatus("Invalid status file (not a dict)") return data diff --git a/mypy/dmypy_util.py b/mypy/dmypy_util.py index 9918e3c3b26f..f598742d2474 100644 --- a/mypy/dmypy_util.py +++ b/mypy/dmypy_util.py @@ -24,8 +24,8 @@ def receive(connection: IPCBase) -> Any: raise OSError("No data received") try: data = json.loads(bdata.decode('utf8')) - except Exception: - raise OSError("Data received is not valid JSON") + except Exception as e: + raise OSError("Data received is not valid JSON") from e if not isinstance(data, dict): raise OSError("Data received is not a dict (%s)" % str(type(data))) return data diff --git a/mypy/ipc.py b/mypy/ipc.py index 02c70eb82829..83d3ca787329 100644 --- a/mypy/ipc.py +++ b/mypy/ipc.py @@ -109,7 +109,7 @@ def write(self, data: bytes) -> None: assert err == 0, err assert bytes_written == len(data) except WindowsError as e: - raise IPCException("Failed to write with error: {}".format(e.winerror)) + raise IPCException("Failed to write with error: {}".format(e.winerror)) from e else: self.connection.sendall(data) self.connection.shutdown(socket.SHUT_WR) @@ -131,11 +131,11 @@ def __init__(self, name: str, timeout: Optional[float]) -> None: timeout = int(self.timeout * 1000) if self.timeout else _winapi.NMPWAIT_WAIT_FOREVER try: _winapi.WaitNamedPipe(self.name, timeout) - except FileNotFoundError: - raise IPCException("The NamedPipe at {} was not found.".format(self.name)) + except FileNotFoundError as e: + raise IPCException("The NamedPipe at {} was not found.".format(self.name)) from e except WindowsError as e: if e.winerror == _winapi.ERROR_SEM_TIMEOUT: - raise IPCException("Timed out waiting for connection.") + raise IPCException("Timed out waiting for connection.") from e else: raise try: @@ -150,7 +150,7 @@ def __init__(self, name: str, timeout: Optional[float]) -> None: ) except WindowsError as e: if e.winerror == _winapi.ERROR_PIPE_BUSY: - raise IPCException("The connection is busy.") + raise IPCException("The connection is busy.") from e else: raise _winapi.SetNamedPipeHandleState(self.connection, @@ -237,8 +237,8 @@ def __enter__(self) -> 'IPCServer': else: try: self.connection, _ = self.sock.accept() - except socket.timeout: - raise IPCException('The socket timed out') + except socket.timeout as e: + raise IPCException('The socket timed out') from e return self def __exit__(self, diff --git a/mypy/main.py b/mypy/main.py index a1a6fc17166d..8e80364234b4 100644 --- a/mypy/main.py +++ b/mypy/main.py @@ -192,10 +192,11 @@ def _python_executable_from_version(python_version: Tuple[int, int]) -> str: ['-c', 'import sys; print(sys.executable)'], stderr=subprocess.STDOUT).decode().strip() return sys_exe - except (subprocess.CalledProcessError, FileNotFoundError): + except (subprocess.CalledProcessError, FileNotFoundError) as e: raise PythonExecutableInferenceError( 'failed to find a Python executable matching version {},' - ' perhaps try --python-executable, or --no-site-packages?'.format(python_version)) + ' perhaps try --python-executable, or --no-site-packages?'.format(python_version) + ) from e def infer_python_executable(options: Options, diff --git a/mypy/moduleinspect.py b/mypy/moduleinspect.py index a4c7bcc13438..d54746260123 100644 --- a/mypy/moduleinspect.py +++ b/mypy/moduleinspect.py @@ -44,7 +44,7 @@ def get_package_properties(package_id: str) -> ModuleProperties: try: package = importlib.import_module(package_id) except BaseException as e: - raise InspectError(str(e)) + raise InspectError(str(e)) from e name = getattr(package, '__name__', None) file = getattr(package, '__file__', None) path = getattr(package, '__path__', None) # type: Optional[List[str]] diff --git a/mypy/stubgen.py b/mypy/stubgen.py index 75fa94e8e630..972863416668 100755 --- a/mypy/stubgen.py +++ b/mypy/stubgen.py @@ -1191,7 +1191,7 @@ def collect_build_targets(options: Options, mypy_opts: MypyOptions) -> Tuple[Lis try: source_list = create_source_list(options.files, mypy_opts) except InvalidSourceList as e: - raise SystemExit(str(e)) + raise SystemExit(str(e)) from e py_modules = [StubSource(m.module, m.path) for m in source_list] c_modules = [] @@ -1362,7 +1362,7 @@ def generate_asts_for_modules(py_modules: List[StubSource], try: res = build(list(py_modules), mypy_options) except CompileError as e: - raise SystemExit("Critical error during semantic analysis: {}".format(e)) + raise SystemExit("Critical error during semantic analysis: {}".format(e)) from e for mod in py_modules: mod.ast = res.graph[mod.module].tree diff --git a/mypy/stubtest.py b/mypy/stubtest.py index 3dc0468868bd..535f049d9b2e 100644 --- a/mypy/stubtest.py +++ b/mypy/stubtest.py @@ -957,7 +957,7 @@ def build_stubs(modules: List[str], options: Options, find_submodules: bool = Fa except mypy.errors.CompileError as e: output = [_style("error: ", color="red", bold=True), "failed mypy compile.\n", str(e)] print("".join(output)) - raise RuntimeError + raise RuntimeError from e if res.errors: output = [_style("error: ", color="red", bold=True), "failed mypy build.\n"] print("".join(output) + "\n".join(res.errors)) diff --git a/mypy/stubutil.py b/mypy/stubutil.py index 51f9ef6e39ff..d21ba4059913 100644 --- a/mypy/stubutil.py +++ b/mypy/stubutil.py @@ -91,7 +91,7 @@ def find_module_path_and_all_py2(module: str, except subprocess.CalledProcessError as e: path = find_module_path_using_py2_sys_path(module, interpreter) if path is None: - raise CantImport(module, str(e)) + raise CantImport(module, str(e)) from e return path, None output = output_bytes.decode('ascii').strip().splitlines() module_path = output[0] @@ -153,7 +153,7 @@ def find_module_path_and_all_py3(inspect: ModuleInspect, # Fall back to finding the module using sys.path. path = find_module_path_using_sys_path(module, sys.path) if path is None: - raise CantImport(module, str(e)) + raise CantImport(module, str(e)) from e return path, None if mod.is_c_module: return None diff --git a/mypy/suggestions.py b/mypy/suggestions.py index d8a927b39590..0a41b134db6f 100644 --- a/mypy/suggestions.py +++ b/mypy/suggestions.py @@ -568,8 +568,8 @@ def find_node_by_file_and_line(self, file: str, line: int) -> Tuple[str, SymbolN raise SuggestionFailure('Source file is not a Python file') try: modname, _ = self.finder.crawl_up(os.path.normpath(file)) - except InvalidSourceList: - raise SuggestionFailure('Invalid source file name: ' + file) + except InvalidSourceList as e: + raise SuggestionFailure('Invalid source file name: ' + file) from e if modname not in self.graph: raise SuggestionFailure('Unknown module: ' + modname) # We must be sure about any edits in this file as this might affect the line numbers. diff --git a/mypy/util.py b/mypy/util.py index dd59f287c9ed..6f6252136d64 100644 --- a/mypy/util.py +++ b/mypy/util.py @@ -132,7 +132,7 @@ def decode_python_encoding(source: bytes, pyversion: Tuple[int, int]) -> str: try: source_text = source.decode(encoding) except LookupError as lookuperr: - raise DecodeError(str(lookuperr)) + raise DecodeError(str(lookuperr)) from lookuperr return source_text diff --git a/mypyc/test/test_run.py b/mypyc/test/test_run.py index 0e3151e1a09c..f57ea5b94166 100644 --- a/mypyc/test/test_run.py +++ b/mypyc/test/test_run.py @@ -82,7 +82,7 @@ def run_setup(script_name: str, script_args: List[str]) -> bool: # "interrupted" as the argument. Convert it back so that # pytest will exit instead of just failing the test. if code == "interrupted": - raise KeyboardInterrupt + raise KeyboardInterrupt from e return code == 0 or code is None