Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix exception causes all over the codebase #8998

Merged
merged 1 commit into from
Jun 17, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions mypy/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions mypy/dmypy/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions mypy/dmypy_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
14 changes: 7 additions & 7 deletions mypy/ipc.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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:
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
5 changes: 3 additions & 2 deletions mypy/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion mypy/moduleinspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]]
Expand Down
4 changes: 2 additions & 2 deletions mypy/stubgen.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = []

Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion mypy/stubtest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
4 changes: 2 additions & 2 deletions mypy/stubutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions mypy/suggestions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion mypy/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
2 changes: 1 addition & 1 deletion mypyc/test/test_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down