Skip to content

Commit

Permalink
Removed raise_from_traceback (#29174)
Browse files Browse the repository at this point in the history
  • Loading branch information
WillAyd authored and simonjayhawkins committed Oct 26, 2019
1 parent 08ab156 commit a38a004
Show file tree
Hide file tree
Showing 7 changed files with 12 additions and 194 deletions.
10 changes: 0 additions & 10 deletions pandas/compat/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 """
Expand Down
9 changes: 4 additions & 5 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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)
Expand Down
7 changes: 3 additions & 4 deletions pandas/core/internals/construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
4 changes: 1 addition & 3 deletions pandas/io/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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)
Expand All @@ -916,7 +914,7 @@ def _parse(flavor, io, match, attrs, encoding, displayed_only, **kwargs):
else:
break
else:
raise_with_traceback(retained)
raise retained

This comment has been minimized.

Copy link
@simonjayhawkins

simonjayhawkins Oct 27, 2019

Member

This is giving mypy error error: Exception must be derived from BaseException [misc]


ret = []
for table in tables:
Expand Down
7 changes: 3 additions & 4 deletions pandas/io/sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down
29 changes: 0 additions & 29 deletions pandas/tests/util/test_util.py
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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)
Expand All @@ -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"):
Expand Down
140 changes: 1 addition & 139 deletions pandas/util/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from functools import wraps
import gzip
import os
import re
from shutil import rmtree
import string
import tempfile
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand Down

0 comments on commit a38a004

Please sign in to comment.