Skip to content

CLN: assorted cleanups, mostly post-black fixups #28857

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 15 commits into from
Oct 11, 2019
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
2 changes: 1 addition & 1 deletion asv_bench/benchmarks/ctors.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ class SeriesConstructors:
def setup(self, data_fmt, with_index, dtype):
if data_fmt in (gen_of_str, gen_of_tuples) and with_index:
raise NotImplementedError(
"Series constructors do not support " "using generators with indexes"
"Series constructors do not support using generators with indexes"
)
N = 10 ** 4
if dtype == "float":
Expand Down
2 changes: 1 addition & 1 deletion asv_bench/benchmarks/eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def time_add(self, engine, threads):

def time_and(self, engine, threads):
pd.eval(
"(self.df > 0) & (self.df2 > 0) & " "(self.df3 > 0) & (self.df4 > 0)",
"(self.df > 0) & (self.df2 > 0) & (self.df3 > 0) & (self.df4 > 0)",
engine=engine,
)

Expand Down
4 changes: 2 additions & 2 deletions asv_bench/benchmarks/io/hdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,11 +88,11 @@ def time_write_store_table_dc(self):

def time_query_store_table_wide(self):
self.store.select(
"table_wide", where="index > self.start_wide and " "index < self.stop_wide"
"table_wide", where="index > self.start_wide and index < self.stop_wide"
)

def time_query_store_table(self):
self.store.select("table", where="index > self.start and " "index < self.stop")
self.store.select("table", where="index > self.start and index < self.stop")

def time_store_repr(self):
repr(self.store)
Expand Down
4 changes: 2 additions & 2 deletions doc/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -628,11 +628,11 @@ def linkcode_resolve(domain, info):
fn = os.path.relpath(fn, start=os.path.dirname(pandas.__file__))

if "+" in pandas.__version__:
return "http://github.com/pandas-dev/pandas/blob/master/pandas/" "{}{}".format(
return "http://github.com/pandas-dev/pandas/blob/master/pandas/{}{}".format(
fn, linespec
)
else:
return "http://github.com/pandas-dev/pandas/blob/" "v{}/pandas/{}{}".format(
return "http://github.com/pandas-dev/pandas/blob/v{}/pandas/{}{}".format(
pandas.__version__, fn, linespec
)

Expand Down
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ Timezones
Numeric
^^^^^^^
- Bug in :meth:`DataFrame.quantile` with zero-column :class:`DataFrame` incorrectly raising (:issue:`23925`)
- :class:`DataFrame` inequality comparisons with object-dtype and ``complex`` entries failing to raise ``TypeError`` like their :class:`Series` counterparts (:issue:`28079`)
- :class:`DataFrame` flex inequality comparisons methods (:meth:`DataFrame.lt`, :meth:`DataFrame.le`, :meth:`DataFrame.gt`, :meth: `DataFrame.ge`) with object-dtype and ``complex`` entries failing to raise ``TypeError`` like their :class:`Series` counterparts (:issue:`28079`)
- Bug in :class:`DataFrame` logical operations (`&`, `|`, `^`) not matching :class:`Series` behavior by filling NA values (:issue:`28741`)
-

Expand Down
6 changes: 3 additions & 3 deletions pandas/_libs/reduction.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -170,9 +170,9 @@ cdef class Reducer:
PyArray_SETITEM(result, PyArray_ITER_DATA(it), res)
chunk.data = chunk.data + self.increment
PyArray_ITER_NEXT(it)
except Exception, e:
if hasattr(e, 'args'):
e.args = e.args + (i,)
except Exception as err:
if hasattr(err, 'args'):
err.args = err.args + (i,)
raise
finally:
# so we don't free the wrong memory
Expand Down
2 changes: 1 addition & 1 deletion pandas/_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
# tag
full_tag = mo.group(1)
if not full_tag.startswith(tag_prefix):
fmt = "tag '{full_tag}' doesn't start with prefix " "'{tag_prefix}'"
fmt = "tag '{full_tag}' doesn't start with prefix '{tag_prefix}'"
msg = fmt.format(full_tag=full_tag, tag_prefix=tag_prefix)
if verbose:
print(msg)
Expand Down
8 changes: 5 additions & 3 deletions pandas/core/apply.py
Original file line number Diff line number Diff line change
Expand Up @@ -341,13 +341,15 @@ def apply_series_generator(self):
for i, v in enumerate(series_gen):
results[i] = self.f(v)
keys.append(v.name)
except Exception as e:
if hasattr(e, "args"):
except Exception as err:
if hasattr(err, "args"):

# make sure i is defined
if i is not None:
k = res_index[i]
e.args = e.args + ("occurred at index %s" % pprint_thing(k),)
err.args = err.args + (
"occurred at index %s" % pprint_thing(k),
)
raise

self.results = results
Expand Down
2 changes: 1 addition & 1 deletion pandas/io/sas/sas7bdat.py
Original file line number Diff line number Diff line change
Expand Up @@ -672,7 +672,7 @@ def _read_next_page(self):
return True
elif len(self._cached_page) != self._page_length:
self.close()
msg = "failed to read complete page from file " "(read {:d} of {:d} bytes)"
msg = "failed to read complete page from file (read {:d} of {:d} bytes)"
raise ValueError(msg.format(len(self._cached_page), self._page_length))

self._read_page_header()
Expand Down
4 changes: 2 additions & 2 deletions pandas/plotting/_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -685,7 +685,7 @@ def _get_call_args(backend_name, data, args, kwargs):
else:
raise TypeError(
(
"Called plot accessor for type {}, expected " "Series or DataFrame"
"Called plot accessor for type {}, expected Series or DataFrame"
).format(type(data).__name__)
)

Expand Down Expand Up @@ -740,7 +740,7 @@ def __call__(self, *args, **kwargs):
return plot_backend.plot(data, x=x, y=y, kind=kind, **kwargs)
else:
raise ValueError(
("plot kind {} can only be used for " "data frames").format(kind)
("plot kind {} can only be used for data frames").format(kind)
)
elif kind in self._series_kinds:
if isinstance(data, ABCDataFrame):
Expand Down
4 changes: 1 addition & 3 deletions pandas/plotting/_matplotlib/boxplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,9 +331,7 @@ def plot_group(keys, values, ax):
if return_type is None:
return_type = "axes"
if layout is not None:
raise ValueError(
"The 'layout' keyword is not supported when " "'by' is None"
)
raise ValueError("The 'layout' keyword is not supported when 'by' is None")

if ax is None:
rc = {"figure.figsize": figsize} if figsize is not None else {}
Expand Down
2 changes: 1 addition & 1 deletion pandas/plotting/_matplotlib/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ def _validate_color_args(self):
"color" in self.kwds or "colors" in self.kwds
) and self.colormap is not None:
warnings.warn(
"'color' and 'colormap' cannot be used " "simultaneously. Using 'color'"
"'color' and 'colormap' cannot be used simultaneously. Using 'color'"
)

if "color" in self.kwds and self.style is not None:
Expand Down
8 changes: 3 additions & 5 deletions pandas/plotting/_matplotlib/hist.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ def _grouped_plot(
if figsize == "default":
# allowed to specify mpl default with 'default'
warnings.warn(
"figsize='default' is deprecated. Specify figure " "size by tuple instead",
"figsize='default' is deprecated. Specify figure size by tuple instead",
FutureWarning,
stacklevel=5,
)
Expand Down Expand Up @@ -298,9 +298,7 @@ def hist_series(

if by is None:
if kwds.get("layout", None) is not None:
raise ValueError(
"The 'layout' keyword is not supported when " "'by' is None"
)
raise ValueError("The 'layout' keyword is not supported when 'by' is None")
# hack until the plotting interface is a bit more unified
fig = kwds.pop(
"figure", plt.gcf() if plt.get_fignums() else plt.figure(figsize=figsize)
Expand Down Expand Up @@ -394,7 +392,7 @@ def hist_frame(
naxes = len(data.columns)

if naxes == 0:
raise ValueError("hist method requires numerical columns, " "nothing to plot.")
raise ValueError("hist method requires numerical columns, nothing to plot.")

fig, axes = _subplots(
naxes=naxes,
Expand Down
2 changes: 1 addition & 1 deletion pandas/plotting/_matplotlib/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def _get_standard_colors(
elif color is not None:
if colormap is not None:
warnings.warn(
"'color' and 'colormap' cannot be used " "simultaneously. Using 'color'"
"'color' and 'colormap' cannot be used simultaneously. Using 'color'"
)
colors = list(color) if is_list_like(color) else color
else:
Expand Down
3 changes: 1 addition & 2 deletions pandas/plotting/_matplotlib/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,8 +188,7 @@ def _subplots(
ax = _flatten(ax)
if layout is not None:
warnings.warn(
"When passing multiple axes, layout keyword is " "ignored",
UserWarning,
"When passing multiple axes, layout keyword is ignored", UserWarning
)
if sharex or sharey:
warnings.warn(
Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/io/test_html.py
Original file line number Diff line number Diff line change
Expand Up @@ -1233,8 +1233,8 @@ class ErrorThread(threading.Thread):
def run(self):
try:
super().run()
except Exception as e:
self.err = e
except Exception as err:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you might have mentioned in the past but is there a flake8 rule for single character variable names? Worth turning on?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIRC there is a rule that excludes lower-case "l", upper-case "I", and upper-case "O" as ambiguous. My complaint about the more general case is that these are hard to grep for.

self.err = err
else:
self.err = None

Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/window/test_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def test_agg_function_support(self, arg):
df = pd.DataFrame({"A": np.arange(5)})
roll = df.rolling(2, win_type="triang")

msg = "'{arg}' is not a valid function for " "'Window' object".format(arg=arg)
msg = "'{arg}' is not a valid function for 'Window' object".format(arg=arg)
with pytest.raises(AttributeError, match=msg):
roll.agg(arg)

Expand Down
8 changes: 3 additions & 5 deletions pandas/tseries/offsets.py
Original file line number Diff line number Diff line change
Expand Up @@ -658,9 +658,7 @@ def __init__(self, start="09:00", end="17:00", offset=timedelta(0)):

# Validation of input
if len(start) != len(end):
raise ValueError(
"number of starting time and ending time " "must be the same"
)
raise ValueError("number of starting time and ending time must be the same")
num_openings = len(start)

# sort starting and ending time by starting time
Expand Down Expand Up @@ -2242,7 +2240,7 @@ def _parse_suffix(cls, varion_code, startingMonth_code, weekday_code):
variation = "last"
else:
raise ValueError(
"Unable to parse varion_code: " "{code}".format(code=varion_code)
"Unable to parse varion_code: {code}".format(code=varion_code)
)

startingMonth = ccalendar.MONTH_TO_CAL_NUM[startingMonth_code]
Expand Down Expand Up @@ -2557,7 +2555,7 @@ def __init__(self, n=1, normalize=False):
BaseOffset.__init__(self, n, normalize)
if normalize:
raise ValueError(
"Tick offset with `normalize=True` are not " "allowed."
"Tick offset with `normalize=True` are not allowed."
) # GH#21427

__gt__ = _tick_comp(operator.gt)
Expand Down
4 changes: 2 additions & 2 deletions pandas/util/_decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ def deprecate_kwarg(

if mapping is not None and not hasattr(mapping, "get") and not callable(mapping):
raise TypeError(
"mapping from old to new argument values " "must be dict or callable!"
"mapping from old to new argument values must be dict or callable!"
)

def _deprecate_kwarg(func: F) -> F:
Expand Down Expand Up @@ -214,7 +214,7 @@ def wrapper(*args, **kwargs) -> Callable[..., Any]:
warnings.warn(msg, FutureWarning, stacklevel=stacklevel)
if kwargs.get(new_arg_name) is not None:
msg = (
"Can only specify '{old_name}' or '{new_name}', " "not both"
"Can only specify '{old_name}' or '{new_name}', not both"
).format(old_name=old_arg_name, new_name=new_arg_name)
raise TypeError(msg)
else:
Expand Down
10 changes: 5 additions & 5 deletions pandas/util/_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ def rewrite_exception(old_name, new_name):
"""Rewrite the message of an exception."""
try:
yield
except Exception as e:
msg = e.args[0]
except Exception as err:
msg = err.args[0]
msg = msg.replace(old_name, new_name)
args = (msg,)
if len(e.args) > 1:
args = args + e.args[1:]
e.args = args
if len(err.args) > 1:
args = args + err.args[1:]
err.args = args
raise
2 changes: 1 addition & 1 deletion pandas/util/_print_versions.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ def main():
"--json",
metavar="FILE",
nargs=1,
help="Save output as JSON into file, pass in " "'-' to output to stdout",
help="Save output as JSON into file, pass in '-' to output to stdout",
)

(options, args) = parser.parse_args()
Expand Down
2 changes: 1 addition & 1 deletion pandas/util/_test_decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ def skip_if_no(package: str, min_version: Optional[str] = None) -> Callable:
)
skip_if_not_us_locale = pytest.mark.skipif(
_skip_if_not_us_locale(),
reason="Specific locale is set " "{lang}".format(lang=locale.getlocale()[0]),
reason="Specific locale is set {lang}".format(lang=locale.getlocale()[0]),
)
skip_if_no_scipy = pytest.mark.skipif(
_skip_if_no_scipy(), reason="Missing SciPy requirement"
Expand Down
4 changes: 2 additions & 2 deletions pandas/util/_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ def validate_axis_style_args(data, args, kwargs, arg_name, method_name):
# First fill with explicit values provided by the user...
if arg_name in kwargs:
if args:
msg = "{} got multiple values for argument " "'{}'".format(
msg = "{} got multiple values for argument '{}'".format(
method_name, arg_name
)
raise TypeError(msg)
Expand Down Expand Up @@ -318,7 +318,7 @@ def validate_axis_style_args(data, args, kwargs, arg_name, method_name):
elif len(args) == 2:
if "axis" in kwargs:
# Unambiguously wrong
msg = "Cannot specify both 'axis' and any of 'index' " "or 'columns'"
msg = "Cannot specify both 'axis' and any of 'index' or 'columns'"
raise TypeError(msg)

msg = (
Expand Down
18 changes: 9 additions & 9 deletions pandas/util/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1175,7 +1175,7 @@ def assert_series_equal(
# vs Timestamp) but will compare equal
if not Index(left.values).equals(Index(right.values)):
msg = (
"[datetimelike_compat=True] {left} is not equal to " "{right}."
"[datetimelike_compat=True] {left} is not equal to {right}."
).format(left=left.values, right=right.values)
raise AssertionError(msg)
else:
Expand Down Expand Up @@ -2363,34 +2363,34 @@ def wrapper(*args, **kwargs):
skip()
try:
return t(*args, **kwargs)
except Exception as e:
errno = getattr(e, "errno", None)
except Exception as err:
errno = getattr(err, "errno", None)
if not errno and hasattr(errno, "reason"):
errno = getattr(e.reason, "errno", None)
errno = getattr(err.reason, "errno", None)

if errno in skip_errnos:
skip(
"Skipping test due to known errno"
" and error {error}".format(error=e)
" and error {error}".format(error=err)
)

e_str = str(e)
e_str = str(err)

if any(m.lower() in e_str.lower() for m in _skip_on_messages):
skip(
"Skipping test because exception "
"message is known and error {error}".format(error=e)
"message is known and error {error}".format(error=err)
)

if not isinstance(e, error_classes):
if not isinstance(err, error_classes):
raise

if raise_on_error or can_connect(url, error_classes):
raise
else:
skip(
"Skipping test due to lack of connectivity"
" and error {error}".format(error=e)
" and error {error}".format(error=err)
)

return wrapper
Expand Down
6 changes: 3 additions & 3 deletions scripts/find_commits_touching_func.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,14 +46,14 @@
"--dir-masks",
metavar="d_re(,d_re)*",
default=[],
help="comma separated list of regexes to match base " "path against",
help="comma separated list of regexes to match base path against",
)
argparser.add_argument(
"-p",
"--path-masks",
metavar="p_re(,p_re)*",
default=[],
help="comma separated list of regexes to match full " "file path against",
help="comma separated list of regexes to match full file path against",
)
argparser.add_argument(
"-y",
Expand Down Expand Up @@ -195,7 +195,7 @@ def sorter(i):
return hits[i].path, d

print(
("\nThese commits touched the %s method in these files " "on these dates:\n")
("\nThese commits touched the %s method in these files on these dates:\n")
% args.funcname
)
for i in sorted(range(len(hits)), key=sorter):
Expand Down
2 changes: 1 addition & 1 deletion scripts/tests/test_validate_docstrings.py
Original file line number Diff line number Diff line change
Expand Up @@ -1029,7 +1029,7 @@ def test_bad_generic_functions(self, capsys, func):
(
"BadReturns",
"no_capitalization",
("Return value description should start with a capital " "letter",),
("Return value description should start with a capital letter",),
),
(
"BadReturns",
Expand Down
Loading