From 9ded2eb582dae2f3bb9b7d2281a2cbff511a85b3 Mon Sep 17 00:00:00 2001 From: William Ayd Date: Sat, 26 Oct 2019 01:28:59 -0700 Subject: [PATCH] Removed raise_from_traceback (#29174) --- pandas/compat/__init__.py | 10 -- pandas/core/frame.py | 9 +- pandas/core/internals/construction.py | 7 +- pandas/io/html.py | 4 +- pandas/io/sql.py | 7 +- pandas/tests/util/test_util.py | 29 ------ pandas/util/testing.py | 140 +------------------------- 7 files changed, 12 insertions(+), 194 deletions(-) diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py index 9c778f68727c6..81431db5b867c 100644 --- a/pandas/compat/__init__.py +++ b/pandas/compat/__init__.py @@ -37,16 +37,6 @@ def set_function_name(f, name, cls): return f -def raise_with_traceback(exc, traceback=Ellipsis): - """ - Raise exception with existing traceback. - If traceback is not passed, uses sys.exc_info() to get traceback. - """ - if traceback == Ellipsis: - _, _, traceback = sys.exc_info() - raise exc.with_traceback(traceback) - - # https://github.com/pandas-dev/pandas/pull/9123 def is_platform_little_endian(): """ am I little endian """ diff --git a/pandas/core/frame.py b/pandas/core/frame.py index ef4e3e064d85e..23611055d6f01 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -34,7 +34,7 @@ from pandas._config import get_option from pandas._libs import algos as libalgos, lib -from pandas.compat import PY36, raise_with_traceback +from pandas.compat import PY36 from pandas.compat.numpy import function as nv from pandas.util._decorators import ( Appender, @@ -485,7 +485,7 @@ def __init__( "DataFrame constructor called with " "incompatible data and dtype: {e}".format(e=e) ) - raise_with_traceback(exc) + raise exc from e if arr.ndim == 0 and index is not None and columns is not None: values = cast_scalar_to_array( @@ -7821,11 +7821,10 @@ def f(x): elif filter_type == "bool": data = self._get_bool_data() else: # pragma: no cover - e = NotImplementedError( + raise NotImplementedError( "Handling exception with filter_type {f} not" "implemented.".format(f=filter_type) - ) - raise_with_traceback(e) + ) from e with np.errstate(all="ignore"): result = f(data.values) labels = data._get_agg_axis(axis) diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index 3126b9d9d3e2e..176f4acd113fe 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -9,7 +9,7 @@ from pandas._libs import lib import pandas.compat as compat -from pandas.compat import PY36, raise_with_traceback +from pandas.compat import PY36 from pandas.core.dtypes.cast import ( construct_1d_arraylike_from_scalar, @@ -164,11 +164,10 @@ def init_ndarray(values, index, columns, dtype=None, copy=False): try: values = values.astype(dtype) except Exception as orig: - e = ValueError( + raise ValueError( "failed to cast to '{dtype}' (Exception " "was: {orig})".format(dtype=dtype, orig=orig) - ) - raise_with_traceback(e) + ) from orig index, columns = _get_axes(*values.shape, index=index, columns=columns) values = values.T diff --git a/pandas/io/html.py b/pandas/io/html.py index 490c574463b9b..7da7a819f81e8 100644 --- a/pandas/io/html.py +++ b/pandas/io/html.py @@ -9,7 +9,6 @@ import os import re -from pandas.compat import raise_with_traceback from pandas.compat._optional import import_optional_dependency from pandas.errors import AbstractMethodError, EmptyDataError @@ -889,7 +888,6 @@ def _parse(flavor, io, match, attrs, encoding, displayed_only, **kwargs): flavor = _validate_flavor(flavor) compiled_match = re.compile(match) # you can pass a compiled regex here - # hack around python 3 deleting the exception variable retained = None for flav in flavor: parser = _parser_dispatch(flav) @@ -916,7 +914,7 @@ def _parse(flavor, io, match, attrs, encoding, displayed_only, **kwargs): else: break else: - raise_with_traceback(retained) + raise retained ret = [] for table in tables: diff --git a/pandas/io/sql.py b/pandas/io/sql.py index 822b3288c82d9..820aeaeb11649 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -12,7 +12,6 @@ import numpy as np import pandas._libs.lib as lib -from pandas.compat import raise_with_traceback from pandas.core.dtypes.common import is_datetime64tz_dtype, is_dict_like, is_list_like from pandas.core.dtypes.dtypes import DatetimeTZDtype @@ -1596,17 +1595,17 @@ def execute(self, *args, **kwargs): except Exception as exc: try: self.con.rollback() - except Exception: # pragma: no cover + except Exception as inner_exc: # pragma: no cover ex = DatabaseError( "Execution failed on sql: {sql}\n{exc}\nunable " "to rollback".format(sql=args[0], exc=exc) ) - raise_with_traceback(ex) + raise ex from inner_exc ex = DatabaseError( "Execution failed on sql '{sql}': {exc}".format(sql=args[0], exc=exc) ) - raise_with_traceback(ex) + raise ex from exc @staticmethod def _query_iterator( diff --git a/pandas/tests/util/test_util.py b/pandas/tests/util/test_util.py index 83d9be1ad235f..60124c8e943ad 100644 --- a/pandas/tests/util/test_util.py +++ b/pandas/tests/util/test_util.py @@ -1,10 +1,8 @@ import os -import sys import pytest import pandas.compat as compat -from pandas.compat import raise_with_traceback import pandas.util.testing as tm @@ -34,23 +32,6 @@ def test_numpy_err_state_is_default(): assert np.geterr() == expected -def test_raise_with_traceback(): - with pytest.raises(LookupError, match="error_text"): - try: - raise ValueError("THIS IS AN ERROR") - except ValueError: - e = LookupError("error_text") - raise_with_traceback(e) - - with pytest.raises(LookupError, match="error_text"): - try: - raise ValueError("This is another error") - except ValueError: - e = LookupError("error_text") - _, _, traceback = sys.exc_info() - raise_with_traceback(e, traceback) - - def test_convert_rows_list_to_csv_str(): rows_list = ["aaa", "bbb", "ccc"] ret = tm.convert_rows_list_to_csv_str(rows_list) @@ -70,16 +51,6 @@ def test_create_temp_directory(): assert not os.path.exists(path) -def test_assert_raises_regex_deprecated(): - # see gh-23592 - - with tm.assert_produces_warning(FutureWarning): - msg = "Not equal!" - - with tm.assert_raises_regex(AssertionError, msg): - assert 1 == 2, msg - - @pytest.mark.parametrize("strict_data_files", [True, False]) def test_datapath_missing(datapath): with pytest.raises(ValueError, match="Could not find file"): diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 73535e55d4fa5..f3b0226547c78 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -5,7 +5,6 @@ from functools import wraps import gzip import os -import re from shutil import rmtree import string import tempfile @@ -23,7 +22,7 @@ ) import pandas._libs.testing as _testing -from pandas.compat import _get_lzma_file, _import_lzma, raise_with_traceback +from pandas.compat import _get_lzma_file, _import_lzma from pandas.core.dtypes.common import ( is_bool, @@ -2404,143 +2403,6 @@ def wrapper(*args, **kwargs): with_connectivity_check = network -def assert_raises_regex(_exception, _regexp, _callable=None, *args, **kwargs): - r""" - Check that the specified Exception is raised and that the error message - matches a given regular expression pattern. This may be a regular - expression object or a string containing a regular expression suitable - for use by `re.search()`. This is a port of the `assertRaisesRegexp` - function from unittest in Python 2.7. - - .. deprecated:: 0.24.0 - Use `pytest.raises` instead. - - Examples - -------- - >>> assert_raises_regex(ValueError, 'invalid literal for.*XYZ', int, 'XYZ') - >>> import re - >>> assert_raises_regex(ValueError, re.compile('literal'), int, 'XYZ') - - If an exception of a different type is raised, it bubbles up. - - >>> assert_raises_regex(TypeError, 'literal', int, 'XYZ') - Traceback (most recent call last): - ... - ValueError: invalid literal for int() with base 10: 'XYZ' - >>> dct = dict() - >>> assert_raises_regex(KeyError, 'pear', dct.__getitem__, 'apple') - Traceback (most recent call last): - ... - AssertionError: "pear" does not match "'apple'" - - You can also use this in a with statement. - - >>> with assert_raises_regex(TypeError, r'unsupported operand type\(s\)'): - ... 1 + {} - >>> with assert_raises_regex(TypeError, 'banana'): - ... 'apple'[0] = 'b' - Traceback (most recent call last): - ... - AssertionError: "banana" does not match "'str' object does not support \ -item assignment" - """ - warnings.warn( - ( - "assert_raises_regex has been deprecated and will " - "be removed in the next release. Please use " - "`pytest.raises` instead." - ), - FutureWarning, - stacklevel=2, - ) - - manager = _AssertRaisesContextmanager(exception=_exception, regexp=_regexp) - if _callable is not None: - with manager: - _callable(*args, **kwargs) - else: - return manager - - -class _AssertRaisesContextmanager: - """ - Context manager behind `assert_raises_regex`. - """ - - def __init__(self, exception, regexp=None): - """ - Initialize an _AssertRaisesContextManager instance. - - Parameters - ---------- - exception : class - The expected Exception class. - regexp : str, default None - The regex to compare against the Exception message. - """ - - self.exception = exception - - if regexp is not None and not hasattr(regexp, "search"): - regexp = re.compile(regexp, re.DOTALL) - - self.regexp = regexp - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_value, trace_back): - expected = self.exception - - if not exc_type: - exp_name = getattr(expected, "__name__", str(expected)) - raise AssertionError("{name} not raised.".format(name=exp_name)) - - return self.exception_matches(exc_type, exc_value, trace_back) - - def exception_matches(self, exc_type, exc_value, trace_back): - """ - Check that the Exception raised matches the expected Exception - and expected error message regular expression. - - Parameters - ---------- - exc_type : class - The type of Exception raised. - exc_value : Exception - The instance of `exc_type` raised. - trace_back : stack trace object - The traceback object associated with `exc_value`. - - Returns - ------- - is_matched : bool - Whether or not the Exception raised matches the expected - Exception class and expected error message regular expression. - - Raises - ------ - AssertionError : The error message provided does not match - the expected error message regular expression. - """ - - if issubclass(exc_type, self.exception): - if self.regexp is not None: - val = str(exc_value) - - if not self.regexp.search(val): - msg = '"{pat}" does not match "{val}"'.format( - pat=self.regexp.pattern, val=val - ) - e = AssertionError(msg) - raise_with_traceback(e, trace_back) - - return True - else: - # Failed, so allow Exception to bubble up. - return False - - @contextmanager def assert_produces_warning( expected_warning=Warning,