Skip to content
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

STY: "{foo!r}" -> "{repr(foo)}" #batch-4 #29959

Merged
merged 1 commit into from
Dec 2, 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
26 changes: 10 additions & 16 deletions pandas/io/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -560,9 +560,7 @@ def _parse_tables(self, doc, match, attrs):
unique_tables.add(table)

if not result:
raise ValueError(
"No tables found matching pattern {patt!r}".format(patt=match.pattern)
)
raise ValueError(f"No tables found matching pattern {repr(match.pattern)}")
return result

def _text_getter(self, obj):
Expand Down Expand Up @@ -618,7 +616,7 @@ def _build_xpath_expr(attrs) -> str:
if "class_" in attrs:
attrs["class"] = attrs.pop("class_")

s = ["@{key}={val!r}".format(key=k, val=v) for k, v in attrs.items()]
s = [f"@{k}={repr(v)}" for k, v in attrs.items()]
return "[{expr}]".format(expr=" and ".join(s))


Expand Down Expand Up @@ -661,8 +659,7 @@ def _parse_tables(self, doc, match, kwargs):

# 1. check all descendants for the given pattern and only search tables
# 2. go up the tree until we find a table
query = "//table//*[re:test(text(), {patt!r})]/ancestor::table"
xpath_expr = query.format(patt=pattern)
xpath_expr = f"//table//*[re:test(text(), {repr(pattern)})]/ancestor::table"

# if any table attributes were given build an xpath expression to
# search for them
Expand All @@ -682,9 +679,7 @@ def _parse_tables(self, doc, match, kwargs):
elem.getparent().remove(elem)

if not tables:
raise ValueError(
"No tables found matching regex {patt!r}".format(patt=pattern)
)
raise ValueError(f"No tables found matching regex {repr(pattern)}")
return tables

def _equals_tag(self, obj, tag):
Expand Down Expand Up @@ -833,8 +828,7 @@ def _parser_dispatch(flavor):
valid_parsers = list(_valid_parsers.keys())
if flavor not in valid_parsers:
raise ValueError(
"{invalid!r} is not a valid flavor, valid flavors "
"are {valid}".format(invalid=flavor, valid=valid_parsers)
f"{repr(flavor)} is not a valid flavor, valid flavors are {valid_parsers}"
)

if flavor in ("bs4", "html5lib"):
Expand Down Expand Up @@ -863,13 +857,13 @@ def _validate_flavor(flavor):
elif isinstance(flavor, abc.Iterable):
if not all(isinstance(flav, str) for flav in flavor):
raise TypeError(
"Object of type {typ!r} is not an iterable of "
"strings".format(typ=type(flavor).__name__)
f"Object of type {repr(type(flavor).__name__)} "
f"is not an iterable of strings"
)
else:
fmt = "{flavor!r}" if isinstance(flavor, str) else "{flavor}"
fmt += " is not a valid flavor"
raise ValueError(fmt.format(flavor=flavor))
msg = repr(flavor) if isinstance(flavor, str) else str(flavor)
msg += " is not a valid flavor"
raise ValueError(msg)

flavor = tuple(flavor)
valid_flavors = set(_valid_parsers)
Expand Down
41 changes: 19 additions & 22 deletions pandas/io/parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -972,10 +972,10 @@ def _clean_options(self, options, engine):
elif engine not in ("python", "python-fwf"):
# wait until regex engine integrated
fallback_reason = (
"the 'c' engine does not support"
" regex separators (separators > 1 char and"
r" different from '\s+' are"
" interpreted as regex)"
"the 'c' engine does not support "
"regex separators (separators > 1 char and "
r"different from '\s+' are "
"interpreted as regex)"
)
engine = "python"
elif delim_whitespace:
Expand All @@ -990,9 +990,9 @@ def _clean_options(self, options, engine):
encodeable = False
if not encodeable and engine not in ("python", "python-fwf"):
fallback_reason = (
"the separator encoded in {encoding}"
" is > 1 char long, and the 'c' engine"
" does not support such separators".format(encoding=encoding)
"the separator encoded in {encoding} "
"is > 1 char long, and the 'c' engine "
"does not support such separators".format(encoding=encoding)
)
engine = "python"

Expand Down Expand Up @@ -1021,21 +1021,19 @@ def _clean_options(self, options, engine):
if "python" in engine:
for arg in _python_unsupported:
if fallback_reason and result[arg] != _c_parser_defaults[arg]:
msg = (
"Falling back to the 'python' engine because"
" {reason}, but this causes {option!r} to be"
" ignored as it is not supported by the 'python'"
" engine."
).format(reason=fallback_reason, option=arg)
raise ValueError(msg)
raise ValueError(
f"Falling back to the 'python' engine because "
f"{fallback_reason}, but this causes {repr(arg)} to be "
f"ignored as it is not supported by the 'python' engine."
)
del result[arg]

if fallback_reason:
warnings.warn(
(
"Falling back to the 'python' engine because"
" {0}; you can avoid this warning by specifying"
" engine='python'."
"Falling back to the 'python' engine because "
"{0}; you can avoid this warning by specifying "
"engine='python'."
).format(fallback_reason),
ParserWarning,
stacklevel=5,
Expand All @@ -1056,8 +1054,8 @@ def _clean_options(self, options, engine):
depr_default = _deprecated_defaults[arg]

msg = (
"The '{arg}' argument has been deprecated "
"and will be removed in a future version.".format(arg=arg)
f"The {repr(arg)} argument has been deprecated and will be "
f"removed in a future version."
)

if result.get(arg, depr_default) != depr_default:
Expand All @@ -1081,9 +1079,8 @@ def _clean_options(self, options, engine):
if converters is not None:
if not isinstance(converters, dict):
raise TypeError(
"Type converters must be a dict or"
" subclass, input was "
"a {0!r}".format(type(converters).__name__)
f"Type converters must be a dict or subclass, "
f"input was a {repr(type(converters).__name__)}"
)
else:
converters = {}
Expand Down
2 changes: 1 addition & 1 deletion pandas/plotting/_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -743,7 +743,7 @@ def _get_call_args(backend_name, data, args, kwargs):
if args and isinstance(data, ABCSeries):
positional_args = str(args)[1:-1]
keyword_args = ", ".join(
f"{name}={value!r}" for (name, default), value in zip(arg_def, args)
f"{name}={repr(value)}" for (name, default), value in zip(arg_def, args)
)
msg = (
"`Series.plot()` should not be called with positional "
Expand Down
8 changes: 4 additions & 4 deletions pandas/tests/computation/test_eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -1114,11 +1114,11 @@ def test_performance_warning_for_poor_alignment(self, engine, parser):
if not is_python_engine:
assert len(w) == 1
msg = str(w[0].message)
loged = np.log10(s.size - df.shape[1])
expected = (
"Alignment difference on axis {0} is larger"
" than an order of magnitude on term {1!r}, "
"by more than {2:.4g}; performance may suffer"
"".format(1, "df", np.log10(s.size - df.shape[1]))
f"Alignment difference on axis 1 is larger "
f"than an order of magnitude on term 'df', "
f"by more than {loged:.4g}; performance may suffer"
)
assert msg == expected

Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/frame/test_alter_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,7 @@ def __init__(self, name, color):
self.color = color

def __str__(self) -> str:
return "<Thing {self.name!r}>".format(self=self)
return f"<Thing {repr(self.name)}>"

# necessary for pretty KeyError
__repr__ = __str__
Expand Down Expand Up @@ -419,7 +419,7 @@ def __init__(self, name, color):
self.color = color

def __str__(self) -> str:
return "<Thing {self.name!r}>".format(self=self)
return f"<Thing {repr(self.name)}>"

thing1 = Thing("One", "red")
thing2 = Thing("Two", "blue")
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/frame/test_query_eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def engine(request):

def skip_if_no_pandas_parser(parser):
if parser != "pandas":
pytest.skip("cannot evaluate with parser {0!r}".format(parser))
pytest.skip(f"cannot evaluate with parser {repr(parser)}")


class TestCompat:
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/indexes/timedeltas/test_timedelta.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ def test_pickle(self):
def test_hash_error(self):
index = timedelta_range("1 days", periods=10)
with pytest.raises(
TypeError, match=("unhashable type: {0.__name__!r}".format(type(index)))
TypeError, match=(f"unhashable type: {repr(type(index).__name__)}")
):
hash(index)

Expand Down
6 changes: 3 additions & 3 deletions pandas/tests/io/parser/test_unsupported.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,9 +96,9 @@ def test_python_engine(self, python_engine):

for default in py_unsupported:
msg = (
"The {default!r} option is not supported with the {python_engine!r}"
" engine"
).format(default=default, python_engine=python_engine)
f"The {repr(default)} option is not "
f"supported with the {repr(python_engine)} engine"
)

kwargs = {default: object()}
with pytest.raises(ValueError, match=msg):
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 @@ -902,8 +902,8 @@ def test_computer_sales_page(self, datapath):

def test_wikipedia_states_table(self, datapath):
data = datapath("io", "data", "html", "wikipedia_states.html")
assert os.path.isfile(data), "{data!r} is not a file".format(data=data)
assert os.path.getsize(data), "{data!r} is an empty file".format(data=data)
assert os.path.isfile(data), f"{repr(data)} is not a file"
assert os.path.getsize(data), f"{repr(data)} is an empty file"
result = self.read_html(data, "Arizona", header=1)[0]
assert result["sq mi"].dtype == np.dtype("float64")

Expand Down
6 changes: 2 additions & 4 deletions pandas/tests/test_strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,10 +296,8 @@ def test_api_per_method(
else:
# GH 23011, GH 23163
msg = (
"Cannot use .str.{name} with values of inferred dtype "
"{inferred_dtype!r}.".format(
name=method_name, inferred_dtype=inferred_dtype
)
f"Cannot use .str.{method_name} with values of "
f"inferred dtype {repr(inferred_dtype)}."
)
with pytest.raises(TypeError, match=msg):
method(*args, **kwargs)
Expand Down