Skip to content

Fix exception causes in 14 modules #32235

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

Merged
merged 1 commit into from
Feb 26, 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
10 changes: 5 additions & 5 deletions pandas/io/sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,8 +238,8 @@ def read_sql_table(
meta = MetaData(con, schema=schema)
try:
meta.reflect(only=[table_name], views=True)
except sqlalchemy.exc.InvalidRequestError:
raise ValueError(f"Table {table_name} not found")
except sqlalchemy.exc.InvalidRequestError as err:
raise ValueError(f"Table {table_name} not found") from err

pandas_sql = SQLDatabase(con, meta=meta)
table = pandas_sql.read_table(
Expand Down Expand Up @@ -685,7 +685,7 @@ def insert_data(self):
try:
temp.reset_index(inplace=True)
except ValueError as err:
raise ValueError(f"duplicate name in index/columns: {err}")
raise ValueError(f"duplicate name in index/columns: {err}") from err
else:
temp = self.frame

Expand Down Expand Up @@ -1387,8 +1387,8 @@ def _create_sql_schema(self, frame, table_name, keys=None, dtype=None):
def _get_unicode_name(name):
try:
uname = str(name).encode("utf-8", "strict").decode("utf-8")
except UnicodeError:
raise ValueError(f"Cannot convert identifier to UTF-8: '{name}'")
except UnicodeError as err:
raise ValueError(f"Cannot convert identifier to UTF-8: '{name}'") from err
return uname


Expand Down
24 changes: 12 additions & 12 deletions pandas/io/stata.py
Original file line number Diff line number Diff line change
Expand Up @@ -1161,8 +1161,8 @@ def f(typ: int) -> Union[int, str]:
return typ
try:
return self.TYPE_MAP_XML[typ]
except KeyError:
raise ValueError(f"cannot convert stata types [{typ}]")
except KeyError as err:
raise ValueError(f"cannot convert stata types [{typ}]") from err

typlist = [f(x) for x in raw_typlist]

Expand All @@ -1171,8 +1171,8 @@ def g(typ: int) -> Union[str, np.dtype]:
return str(typ)
try:
return self.DTYPE_MAP_XML[typ]
except KeyError:
raise ValueError(f"cannot convert stata dtype [{typ}]")
except KeyError as err:
raise ValueError(f"cannot convert stata dtype [{typ}]") from err

dtyplist = [g(x) for x in raw_typlist]

Expand Down Expand Up @@ -1296,14 +1296,14 @@ def _read_old_header(self, first_char: bytes) -> None:

try:
self.typlist = [self.TYPE_MAP[typ] for typ in typlist]
except ValueError:
except ValueError as err:
invalid_types = ",".join(str(x) for x in typlist)
raise ValueError(f"cannot convert stata types [{invalid_types}]")
raise ValueError(f"cannot convert stata types [{invalid_types}]") from err
try:
self.dtyplist = [self.DTYPE_MAP[typ] for typ in typlist]
except ValueError:
except ValueError as err:
invalid_dtypes = ",".join(str(x) for x in typlist)
raise ValueError(f"cannot convert stata dtypes [{invalid_dtypes}]")
raise ValueError(f"cannot convert stata dtypes [{invalid_dtypes}]") from err

if self.format_version > 108:
self.varlist = [
Expand Down Expand Up @@ -1761,7 +1761,7 @@ def _do_convert_categoricals(
categories.append(category) # Partially labeled
try:
cat_data.categories = categories
except ValueError:
except ValueError as err:
vc = Series(categories).value_counts()
repeated_cats = list(vc.index[vc > 1])
repeats = "-" * 80 + "\n" + "\n".join(repeated_cats)
Expand All @@ -1777,7 +1777,7 @@ def _do_convert_categoricals(
The repeated labels are:
{repeats}
"""
raise ValueError(msg)
raise ValueError(msg) from err
# TODO: is the next line needed above in the data(...) method?
cat_series = Series(cat_data, index=data.index)
cat_converted_data.append((col, cat_series))
Expand Down Expand Up @@ -3143,11 +3143,11 @@ def _write_variable_labels(self) -> None:
raise ValueError("Variable labels must be 80 characters or fewer")
try:
encoded = label.encode(self._encoding)
except UnicodeEncodeError:
except UnicodeEncodeError as err:
raise ValueError(
"Variable labels must contain only characters that "
f"can be encoded in {self._encoding}"
)
) from err

bio.write(_pad_bytes_new(encoded, vl_len + 1))
else:
Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/extension/arrow/arrays.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,8 +148,8 @@ def _reduce(self, method, skipna=True, **kwargs):

try:
op = getattr(arr, method)
except AttributeError:
raise TypeError
except AttributeError as err:
raise TypeError from err
return op(**kwargs)

def any(self, axis=0, out=None):
Expand Down
6 changes: 4 additions & 2 deletions pandas/tests/extension/decimal/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,8 +183,10 @@ def _reduce(self, name, skipna=True, **kwargs):

try:
op = getattr(self.data, name)
except AttributeError:
raise NotImplementedError(f"decimal does not support the {name} operation")
except AttributeError as err:
raise NotImplementedError(
f"decimal does not support the {name} operation"
) from err
return op(axis=0)


Expand Down
8 changes: 4 additions & 4 deletions pandas/tests/extension/json/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,13 +137,13 @@ def take(self, indexer, allow_fill=False, fill_value=None):
output = [
self.data[loc] if loc != -1 else fill_value for loc in indexer
]
except IndexError:
raise IndexError(msg)
except IndexError as err:
raise IndexError(msg) from err
else:
try:
output = [self.data[loc] for loc in indexer]
except IndexError:
raise IndexError(msg)
except IndexError as err:
raise IndexError(msg) from err

return self._from_sequence(output)

Expand Down
8 changes: 4 additions & 4 deletions pandas/tests/extension/list/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,13 +86,13 @@ def take(self, indexer, allow_fill=False, fill_value=None):
output = [
self.data[loc] if loc != -1 else fill_value for loc in indexer
]
except IndexError:
raise IndexError(msg)
except IndexError as err:
raise IndexError(msg) from err
else:
try:
output = [self.data[loc] for loc in indexer]
except IndexError:
raise IndexError(msg)
except IndexError as err:
raise IndexError(msg) from err

return self._from_sequence(output)

Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/indexes/datetimes/test_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -1110,8 +1110,8 @@ def test_unit(self, cache):
for val in ["foo", Timestamp("20130101")]:
try:
to_datetime(val, errors="raise", unit="s", cache=cache)
except tslib.OutOfBoundsDatetime:
raise AssertionError("incorrect exception raised")
except tslib.OutOfBoundsDatetime as err:
raise AssertionError("incorrect exception raised") from err
except ValueError:
pass

Expand Down
16 changes: 8 additions & 8 deletions pandas/tests/io/test_sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -2575,39 +2575,39 @@ def setup_class(cls):
pymysql.connect(host="localhost", user="root", passwd="", db="pandas_nosetest")
try:
pymysql.connect(read_default_group="pandas")
except pymysql.ProgrammingError:
except pymysql.ProgrammingError as err:
raise RuntimeError(
"Create a group of connection parameters under the heading "
"[pandas] in your system's mysql default file, "
"typically located at ~/.my.cnf or /etc/.my.cnf."
)
except pymysql.Error:
) from err
except pymysql.Error as err:
raise RuntimeError(
"Cannot connect to database. "
"Create a group of connection parameters under the heading "
"[pandas] in your system's mysql default file, "
"typically located at ~/.my.cnf or /etc/.my.cnf."
)
) from err

@pytest.fixture(autouse=True)
def setup_method(self, request, datapath):
pymysql = pytest.importorskip("pymysql")
pymysql.connect(host="localhost", user="root", passwd="", db="pandas_nosetest")
try:
pymysql.connect(read_default_group="pandas")
except pymysql.ProgrammingError:
except pymysql.ProgrammingError as err:
raise RuntimeError(
"Create a group of connection parameters under the heading "
"[pandas] in your system's mysql default file, "
"typically located at ~/.my.cnf or /etc/.my.cnf."
)
except pymysql.Error:
) from err
except pymysql.Error as err:
raise RuntimeError(
"Cannot connect to database. "
"Create a group of connection parameters under the heading "
"[pandas] in your system's mysql default file, "
"typically located at ~/.my.cnf or /etc/.my.cnf."
)
) from err

self.method = request.function

Expand Down
8 changes: 4 additions & 4 deletions pandas/tests/reshape/merge/test_join.py
Original file line number Diff line number Diff line change
Expand Up @@ -810,23 +810,23 @@ def _check_join(left, right, result, join_col, how="left", lsuffix="_x", rsuffix

try:
lgroup = left_grouped.get_group(group_key)
except KeyError:
except KeyError as err:
if how in ("left", "inner"):
raise AssertionError(
f"key {group_key} should not have been in the join"
)
) from err

_assert_all_na(l_joined, left.columns, join_col)
else:
_assert_same_contents(l_joined, lgroup)

try:
rgroup = right_grouped.get_group(group_key)
except KeyError:
except KeyError as err:
if how in ("right", "inner"):
raise AssertionError(
f"key {group_key} should not have been in the join"
)
) from err

_assert_all_na(r_joined, right.columns, join_col)
else:
Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/reshape/test_concat.py
Original file line number Diff line number Diff line change
Expand Up @@ -1849,8 +1849,8 @@ def __len__(self) -> int:
def __getitem__(self, index):
try:
return {0: df1, 1: df2}[index]
except KeyError:
raise IndexError
except KeyError as err:
raise IndexError from err

tm.assert_frame_equal(pd.concat(CustomIterator1(), ignore_index=True), expected)

Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/tseries/offsets/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ def assert_offset_equal(offset, base, expected):
assert actual == expected
assert actual_swapped == expected
assert actual_apply == expected
except AssertionError:
except AssertionError as err:
raise AssertionError(
f"\nExpected: {expected}\nActual: {actual}\nFor Offset: {offset})"
f"\nAt Date: {base}"
)
) from err


def assert_is_on_offset(offset, date, expected):
Expand Down
12 changes: 6 additions & 6 deletions pandas/tseries/frequencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,8 +141,8 @@ def to_offset(freq) -> Optional[DateOffset]:
delta = offset
else:
delta = delta + offset
except ValueError:
raise ValueError(libfreqs.INVALID_FREQ_ERR_MSG.format(freq))
except ValueError as err:
raise ValueError(libfreqs.INVALID_FREQ_ERR_MSG.format(freq)) from err

else:
delta = None
Expand Down Expand Up @@ -173,8 +173,8 @@ def to_offset(freq) -> Optional[DateOffset]:
delta = offset
else:
delta = delta + offset
except (ValueError, TypeError):
raise ValueError(libfreqs.INVALID_FREQ_ERR_MSG.format(freq))
except (ValueError, TypeError) as err:
raise ValueError(libfreqs.INVALID_FREQ_ERR_MSG.format(freq)) from err

if delta is None:
raise ValueError(libfreqs.INVALID_FREQ_ERR_MSG.format(freq))
Expand Down Expand Up @@ -223,9 +223,9 @@ def _get_offset(name: str) -> DateOffset:
# handles case where there's no suffix (and will TypeError if too
# many '-')
offset = klass._from_name(*split[1:])
except (ValueError, TypeError, KeyError):
except (ValueError, TypeError, KeyError) as err:
# bad prefix or suffix
raise ValueError(libfreqs.INVALID_FREQ_ERR_MSG.format(name))
raise ValueError(libfreqs.INVALID_FREQ_ERR_MSG.format(name)) from err
# cache
_offset_map[name] = offset

Expand Down
8 changes: 4 additions & 4 deletions pandas/tseries/offsets.py
Original file line number Diff line number Diff line change
Expand Up @@ -2530,12 +2530,12 @@ def _tick_comp(op):
def f(self, other):
try:
return op(self.delta, other.delta)
except AttributeError:
except AttributeError as err:
# comparing with a non-Tick object
raise TypeError(
f"Invalid comparison between {type(self).__name__} "
f"and {type(other).__name__}"
)
) from err

f.__name__ = f"__{op.__name__}__"
return f
Expand Down Expand Up @@ -2570,10 +2570,10 @@ def __add__(self, other):
return self.apply(other)
except ApplyTypeError:
return NotImplemented
except OverflowError:
except OverflowError as err:
raise OverflowError(
f"the add operation between {self} and {other} will overflow"
)
) from err

def __eq__(self, other: Any) -> bool:
if isinstance(other, str):
Expand Down
8 changes: 4 additions & 4 deletions pandas/util/_tester.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,12 @@
def test(extra_args=None):
try:
import pytest
except ImportError:
raise ImportError("Need pytest>=5.0.1 to run tests")
except ImportError as err:
raise ImportError("Need pytest>=5.0.1 to run tests") from err
try:
import hypothesis # noqa
except ImportError:
raise ImportError("Need hypothesis>=3.58 to run tests")
except ImportError as err:
raise ImportError("Need hypothesis>=3.58 to run tests") from err
cmd = ["--skip-slow", "--skip-network", "--skip-db"]
if extra_args:
if not isinstance(extra_args, list):
Expand Down