Skip to content

Commit 9ded2eb

Browse files
WillAydNico Cernek
authored and
Nico Cernek
committed
Removed raise_from_traceback (#29174)
1 parent b735c09 commit 9ded2eb

File tree

7 files changed

+12
-194
lines changed

7 files changed

+12
-194
lines changed

pandas/compat/__init__.py

-10
Original file line numberDiff line numberDiff line change
@@ -37,16 +37,6 @@ def set_function_name(f, name, cls):
3737
return f
3838

3939

40-
def raise_with_traceback(exc, traceback=Ellipsis):
41-
"""
42-
Raise exception with existing traceback.
43-
If traceback is not passed, uses sys.exc_info() to get traceback.
44-
"""
45-
if traceback == Ellipsis:
46-
_, _, traceback = sys.exc_info()
47-
raise exc.with_traceback(traceback)
48-
49-
5040
# https://github.com/pandas-dev/pandas/pull/9123
5141
def is_platform_little_endian():
5242
""" am I little endian """

pandas/core/frame.py

+4-5
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
from pandas._config import get_option
3535

3636
from pandas._libs import algos as libalgos, lib
37-
from pandas.compat import PY36, raise_with_traceback
37+
from pandas.compat import PY36
3838
from pandas.compat.numpy import function as nv
3939
from pandas.util._decorators import (
4040
Appender,
@@ -485,7 +485,7 @@ def __init__(
485485
"DataFrame constructor called with "
486486
"incompatible data and dtype: {e}".format(e=e)
487487
)
488-
raise_with_traceback(exc)
488+
raise exc from e
489489

490490
if arr.ndim == 0 and index is not None and columns is not None:
491491
values = cast_scalar_to_array(
@@ -7821,11 +7821,10 @@ def f(x):
78217821
elif filter_type == "bool":
78227822
data = self._get_bool_data()
78237823
else: # pragma: no cover
7824-
e = NotImplementedError(
7824+
raise NotImplementedError(
78257825
"Handling exception with filter_type {f} not"
78267826
"implemented.".format(f=filter_type)
7827-
)
7828-
raise_with_traceback(e)
7827+
) from e
78297828
with np.errstate(all="ignore"):
78307829
result = f(data.values)
78317830
labels = data._get_agg_axis(axis)

pandas/core/internals/construction.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
from pandas._libs import lib
1111
import pandas.compat as compat
12-
from pandas.compat import PY36, raise_with_traceback
12+
from pandas.compat import PY36
1313

1414
from pandas.core.dtypes.cast import (
1515
construct_1d_arraylike_from_scalar,
@@ -164,11 +164,10 @@ def init_ndarray(values, index, columns, dtype=None, copy=False):
164164
try:
165165
values = values.astype(dtype)
166166
except Exception as orig:
167-
e = ValueError(
167+
raise ValueError(
168168
"failed to cast to '{dtype}' (Exception "
169169
"was: {orig})".format(dtype=dtype, orig=orig)
170-
)
171-
raise_with_traceback(e)
170+
) from orig
172171

173172
index, columns = _get_axes(*values.shape, index=index, columns=columns)
174173
values = values.T

pandas/io/html.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
import os
1010
import re
1111

12-
from pandas.compat import raise_with_traceback
1312
from pandas.compat._optional import import_optional_dependency
1413
from pandas.errors import AbstractMethodError, EmptyDataError
1514

@@ -889,7 +888,6 @@ def _parse(flavor, io, match, attrs, encoding, displayed_only, **kwargs):
889888
flavor = _validate_flavor(flavor)
890889
compiled_match = re.compile(match) # you can pass a compiled regex here
891890

892-
# hack around python 3 deleting the exception variable
893891
retained = None
894892
for flav in flavor:
895893
parser = _parser_dispatch(flav)
@@ -916,7 +914,7 @@ def _parse(flavor, io, match, attrs, encoding, displayed_only, **kwargs):
916914
else:
917915
break
918916
else:
919-
raise_with_traceback(retained)
917+
raise retained
920918

921919
ret = []
922920
for table in tables:

pandas/io/sql.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
import numpy as np
1313

1414
import pandas._libs.lib as lib
15-
from pandas.compat import raise_with_traceback
1615

1716
from pandas.core.dtypes.common import is_datetime64tz_dtype, is_dict_like, is_list_like
1817
from pandas.core.dtypes.dtypes import DatetimeTZDtype
@@ -1596,17 +1595,17 @@ def execute(self, *args, **kwargs):
15961595
except Exception as exc:
15971596
try:
15981597
self.con.rollback()
1599-
except Exception: # pragma: no cover
1598+
except Exception as inner_exc: # pragma: no cover
16001599
ex = DatabaseError(
16011600
"Execution failed on sql: {sql}\n{exc}\nunable "
16021601
"to rollback".format(sql=args[0], exc=exc)
16031602
)
1604-
raise_with_traceback(ex)
1603+
raise ex from inner_exc
16051604

16061605
ex = DatabaseError(
16071606
"Execution failed on sql '{sql}': {exc}".format(sql=args[0], exc=exc)
16081607
)
1609-
raise_with_traceback(ex)
1608+
raise ex from exc
16101609

16111610
@staticmethod
16121611
def _query_iterator(

pandas/tests/util/test_util.py

-29
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
11
import os
2-
import sys
32

43
import pytest
54

65
import pandas.compat as compat
7-
from pandas.compat import raise_with_traceback
86

97
import pandas.util.testing as tm
108

@@ -34,23 +32,6 @@ def test_numpy_err_state_is_default():
3432
assert np.geterr() == expected
3533

3634

37-
def test_raise_with_traceback():
38-
with pytest.raises(LookupError, match="error_text"):
39-
try:
40-
raise ValueError("THIS IS AN ERROR")
41-
except ValueError:
42-
e = LookupError("error_text")
43-
raise_with_traceback(e)
44-
45-
with pytest.raises(LookupError, match="error_text"):
46-
try:
47-
raise ValueError("This is another error")
48-
except ValueError:
49-
e = LookupError("error_text")
50-
_, _, traceback = sys.exc_info()
51-
raise_with_traceback(e, traceback)
52-
53-
5435
def test_convert_rows_list_to_csv_str():
5536
rows_list = ["aaa", "bbb", "ccc"]
5637
ret = tm.convert_rows_list_to_csv_str(rows_list)
@@ -70,16 +51,6 @@ def test_create_temp_directory():
7051
assert not os.path.exists(path)
7152

7253

73-
def test_assert_raises_regex_deprecated():
74-
# see gh-23592
75-
76-
with tm.assert_produces_warning(FutureWarning):
77-
msg = "Not equal!"
78-
79-
with tm.assert_raises_regex(AssertionError, msg):
80-
assert 1 == 2, msg
81-
82-
8354
@pytest.mark.parametrize("strict_data_files", [True, False])
8455
def test_datapath_missing(datapath):
8556
with pytest.raises(ValueError, match="Could not find file"):

pandas/util/testing.py

+1-139
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
from functools import wraps
66
import gzip
77
import os
8-
import re
98
from shutil import rmtree
109
import string
1110
import tempfile
@@ -23,7 +22,7 @@
2322
)
2423

2524
import pandas._libs.testing as _testing
26-
from pandas.compat import _get_lzma_file, _import_lzma, raise_with_traceback
25+
from pandas.compat import _get_lzma_file, _import_lzma
2726

2827
from pandas.core.dtypes.common import (
2928
is_bool,
@@ -2404,143 +2403,6 @@ def wrapper(*args, **kwargs):
24042403
with_connectivity_check = network
24052404

24062405

2407-
def assert_raises_regex(_exception, _regexp, _callable=None, *args, **kwargs):
2408-
r"""
2409-
Check that the specified Exception is raised and that the error message
2410-
matches a given regular expression pattern. This may be a regular
2411-
expression object or a string containing a regular expression suitable
2412-
for use by `re.search()`. This is a port of the `assertRaisesRegexp`
2413-
function from unittest in Python 2.7.
2414-
2415-
.. deprecated:: 0.24.0
2416-
Use `pytest.raises` instead.
2417-
2418-
Examples
2419-
--------
2420-
>>> assert_raises_regex(ValueError, 'invalid literal for.*XYZ', int, 'XYZ')
2421-
>>> import re
2422-
>>> assert_raises_regex(ValueError, re.compile('literal'), int, 'XYZ')
2423-
2424-
If an exception of a different type is raised, it bubbles up.
2425-
2426-
>>> assert_raises_regex(TypeError, 'literal', int, 'XYZ')
2427-
Traceback (most recent call last):
2428-
...
2429-
ValueError: invalid literal for int() with base 10: 'XYZ'
2430-
>>> dct = dict()
2431-
>>> assert_raises_regex(KeyError, 'pear', dct.__getitem__, 'apple')
2432-
Traceback (most recent call last):
2433-
...
2434-
AssertionError: "pear" does not match "'apple'"
2435-
2436-
You can also use this in a with statement.
2437-
2438-
>>> with assert_raises_regex(TypeError, r'unsupported operand type\(s\)'):
2439-
... 1 + {}
2440-
>>> with assert_raises_regex(TypeError, 'banana'):
2441-
... 'apple'[0] = 'b'
2442-
Traceback (most recent call last):
2443-
...
2444-
AssertionError: "banana" does not match "'str' object does not support \
2445-
item assignment"
2446-
"""
2447-
warnings.warn(
2448-
(
2449-
"assert_raises_regex has been deprecated and will "
2450-
"be removed in the next release. Please use "
2451-
"`pytest.raises` instead."
2452-
),
2453-
FutureWarning,
2454-
stacklevel=2,
2455-
)
2456-
2457-
manager = _AssertRaisesContextmanager(exception=_exception, regexp=_regexp)
2458-
if _callable is not None:
2459-
with manager:
2460-
_callable(*args, **kwargs)
2461-
else:
2462-
return manager
2463-
2464-
2465-
class _AssertRaisesContextmanager:
2466-
"""
2467-
Context manager behind `assert_raises_regex`.
2468-
"""
2469-
2470-
def __init__(self, exception, regexp=None):
2471-
"""
2472-
Initialize an _AssertRaisesContextManager instance.
2473-
2474-
Parameters
2475-
----------
2476-
exception : class
2477-
The expected Exception class.
2478-
regexp : str, default None
2479-
The regex to compare against the Exception message.
2480-
"""
2481-
2482-
self.exception = exception
2483-
2484-
if regexp is not None and not hasattr(regexp, "search"):
2485-
regexp = re.compile(regexp, re.DOTALL)
2486-
2487-
self.regexp = regexp
2488-
2489-
def __enter__(self):
2490-
return self
2491-
2492-
def __exit__(self, exc_type, exc_value, trace_back):
2493-
expected = self.exception
2494-
2495-
if not exc_type:
2496-
exp_name = getattr(expected, "__name__", str(expected))
2497-
raise AssertionError("{name} not raised.".format(name=exp_name))
2498-
2499-
return self.exception_matches(exc_type, exc_value, trace_back)
2500-
2501-
def exception_matches(self, exc_type, exc_value, trace_back):
2502-
"""
2503-
Check that the Exception raised matches the expected Exception
2504-
and expected error message regular expression.
2505-
2506-
Parameters
2507-
----------
2508-
exc_type : class
2509-
The type of Exception raised.
2510-
exc_value : Exception
2511-
The instance of `exc_type` raised.
2512-
trace_back : stack trace object
2513-
The traceback object associated with `exc_value`.
2514-
2515-
Returns
2516-
-------
2517-
is_matched : bool
2518-
Whether or not the Exception raised matches the expected
2519-
Exception class and expected error message regular expression.
2520-
2521-
Raises
2522-
------
2523-
AssertionError : The error message provided does not match
2524-
the expected error message regular expression.
2525-
"""
2526-
2527-
if issubclass(exc_type, self.exception):
2528-
if self.regexp is not None:
2529-
val = str(exc_value)
2530-
2531-
if not self.regexp.search(val):
2532-
msg = '"{pat}" does not match "{val}"'.format(
2533-
pat=self.regexp.pattern, val=val
2534-
)
2535-
e = AssertionError(msg)
2536-
raise_with_traceback(e, trace_back)
2537-
2538-
return True
2539-
else:
2540-
# Failed, so allow Exception to bubble up.
2541-
return False
2542-
2543-
25442406
@contextmanager
25452407
def assert_produces_warning(
25462408
expected_warning=Warning,

0 commit comments

Comments
 (0)