Skip to content

CLN: use f-strings in core.categorical.py #29748

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 2 commits into from
Nov 21, 2019
Merged
Changes from 1 commit
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
83 changes: 35 additions & 48 deletions pandas/core/arrays/categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,10 @@


def _cat_compare_op(op):
opname = "__{op}__".format(op=op.__name__)
opname = f"__{op.__name__}__"

@unpack_zerodim_and_defer(opname)
def f(self, other):
def func(self, other):
# On python2, you can usually compare any type to any type, and
# Categoricals can be seen as a custom type, but having different
# results depending whether categories are the same or not is kind of
Expand Down Expand Up @@ -137,28 +137,26 @@ def f(self, other):
elif opname == "__ne__":
return np.repeat(True, len(self))
else:
msg = (
"Cannot compare a Categorical for op {op} with a "
raise TypeError(
f"Cannot compare a Categorical for op {opname} with a "
"scalar, which is not a category."
)
raise TypeError(msg.format(op=opname))
else:

# allow categorical vs object dtype array comparisons for equality
# these are only positional comparisons
if opname in ["__eq__", "__ne__"]:
return getattr(np.array(self), opname)(np.array(other))

msg = (
"Cannot compare a Categorical for op {op} with type {typ}."
"\nIf you want to compare values, use 'np.asarray(cat) "
"<op> other'."
raise TypeError(
f"Cannot compare a Categorical for op {opname} with "
f"type {type(other)}.\nIf you want to compare values, "
f"use 'np.asarray(cat) <op> other'."
Copy link
Member

@jschendel jschendel Nov 20, 2019

Choose a reason for hiding this comment

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

the last line doesn't need the f prefix

)
raise TypeError(msg.format(op=opname, typ=type(other)))

f.__name__ = opname
func.__name__ = opname

return f
return func


def contains(cat, key, container):
Expand Down Expand Up @@ -1060,11 +1058,9 @@ def add_categories(self, new_categories, inplace=False):
new_categories = [new_categories]
already_included = set(new_categories) & set(self.dtype.categories)
if len(already_included) != 0:
msg = (
"new categories must not include old categories: "
"{already_included!s}"
raise ValueError(
f"new categories must not include old categories: {already_included}"
)
raise ValueError(msg.format(already_included=already_included))
new_categories = list(self.dtype.categories) + list(new_categories)
new_dtype = CategoricalDtype(new_categories, self.ordered)

Expand Down Expand Up @@ -1120,8 +1116,7 @@ def remove_categories(self, removals, inplace=False):
new_categories = [x for x in new_categories if notna(x)]

if len(not_included) != 0:
msg = "removals must all be in old categories: {not_included!s}"
raise ValueError(msg.format(not_included=not_included))
raise ValueError(f"removals must all be in old categories: {not_included}")

return self.set_categories(
new_categories, ordered=self.ordered, rename=False, inplace=inplace
Expand Down Expand Up @@ -1299,9 +1294,8 @@ def shift(self, periods, fill_value=None):
fill_value = self.categories.get_loc(fill_value)
else:
raise ValueError(
"'fill_value={}' is not present "
"in this Categorical's "
"categories".format(fill_value)
f"'fill_value={fill_value}' is not present "
"in this Categorical's categories"
)
if periods > 0:
codes[:periods] = fill_value
Expand Down Expand Up @@ -1342,8 +1336,8 @@ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
# for all other cases, raise for now (similarly as what happens in
# Series.__array_prepare__)
raise TypeError(
"Object with dtype {dtype} cannot perform "
"the numpy op {op}".format(dtype=self.dtype, op=ufunc.__name__)
f"Object with dtype {self.dtype} cannot perform "
f"the numpy op {ufunc.__name__}"
)

def __setstate__(self, state):
Expand Down Expand Up @@ -1542,9 +1536,9 @@ def check_for_ordered(self, op):
""" assert that we are ordered """
if not self.ordered:
raise TypeError(
"Categorical is not ordered for operation {op}\n"
f"Categorical is not ordered for operation {op}\n"
"you can use .as_ordered() to change the "
"Categorical to an ordered one\n".format(op=op)
"Categorical to an ordered one\n"
)

def _values_for_argsort(self):
Expand Down Expand Up @@ -1679,8 +1673,7 @@ def sort_values(self, inplace=False, ascending=True, na_position="last"):
"""
inplace = validate_bool_kwarg(inplace, "inplace")
if na_position not in ["last", "first"]:
msg = "invalid na_position: {na_position!r}"
raise ValueError(msg.format(na_position=na_position))
raise ValueError(f"invalid na_position: {na_position!r}")

sorted_idx = nargsort(self, ascending=ascending, na_position=na_position)

Expand Down Expand Up @@ -1836,8 +1829,7 @@ def fillna(self, value=None, method=None, limit=None):
else:
raise TypeError(
'"value" parameter must be a scalar, dict '
"or Series, but you passed a "
'"{0}"'.format(type(value).__name__)
f'or Series, but you passed a {type(value).__name__!r}"'
)

return self._constructor(codes, dtype=self.dtype, fastpath=True)
Expand Down Expand Up @@ -1930,8 +1922,11 @@ def take_nd(self, indexer, allow_fill=None, fill_value=None):
if fill_value in self.categories:
fill_value = self.categories.get_loc(fill_value)
else:
msg = "'fill_value' ('{}') is not in this Categorical's categories."
raise TypeError(msg.format(fill_value))
msg = (
f"'fill_value' ('{fill_value}') is not in this "
"Categorical's categories."
)
raise TypeError(msg)

codes = take(self._codes, indexer, allow_fill=allow_fill, fill_value=fill_value)
result = type(self).from_codes(codes, dtype=dtype)
Expand Down Expand Up @@ -1969,11 +1964,9 @@ def _tidy_repr(self, max_vals=10, footer=True):
head = self[:num]._get_repr(length=False, footer=False)
tail = self[-(max_vals - num) :]._get_repr(length=False, footer=False)

result = "{head}, ..., {tail}".format(head=head[:-1], tail=tail[1:])
result = f"{head[:-1]}, ..., {tail[1:]}"
if footer:
result = "{result}\n{footer}".format(
result=result, footer=self._repr_footer()
)
result = f"{result}\n{self._repr_footer()}"

return str(result)

Expand Down Expand Up @@ -2007,9 +2000,7 @@ def _repr_categories_info(self):

category_strs = self._repr_categories()
dtype = str(self.categories.dtype)
levheader = "Categories ({length}, {dtype}): ".format(
length=len(self.categories), dtype=dtype
)
levheader = f"Categories ({len(self.categories)}, {dtype}): "
width, height = get_terminal_size()
max_width = get_option("display.width") or width
if console.in_ipython_frontend():
Expand All @@ -2033,10 +2024,8 @@ def _repr_categories_info(self):
return levheader + "[" + levstring.replace(" < ... < ", " ... ") + "]"

def _repr_footer(self):

return "Length: {length}\n{info}".format(
length=len(self), info=self._repr_categories_info()
)
info = self._repr_categories_info()
return f"Length: {len(self)}\n{info}"

def _get_repr(self, length=True, na_rep="NaN", footer=True):
from pandas.io.formats import format as fmt
Expand All @@ -2058,7 +2047,7 @@ def __repr__(self) -> str:
result = self._get_repr(length=len(self) > _maxlen)
else:
msg = self._get_repr(length=False, footer=True).replace("\n", ", ")
result = "[], {repr_msg}".format(repr_msg=msg)
result = f"[], {msg}"

return result

Expand Down Expand Up @@ -2189,8 +2178,7 @@ def _reverse_indexer(self):
def _reduce(self, name, axis=0, **kwargs):
func = getattr(self, name, None)
if func is None:
msg = "Categorical cannot perform the operation {op}"
raise TypeError(msg.format(op=name))
raise TypeError(f"Categorical cannot perform the operation {name}")
return func(**kwargs)

def min(self, numeric_only=None, **kwargs):
Expand Down Expand Up @@ -2458,11 +2446,10 @@ def isin(self, values):
array([ True, False, True, False, True, False])
"""
if not is_list_like(values):
values_type = type(values).__name__
raise TypeError(
"only list-like objects are allowed to be passed"
" to isin(), you passed a [{values_type}]".format(
values_type=type(values).__name__
)
f" to isin(), you passed a [{values_type}]"
)
values = sanitize_array(values, None, None)
null_mask = np.asarray(isna(values))
Expand Down