Skip to content

Commit 5461b9a

Browse files
ahgamutKevin D Smith
authored and
Kevin D Smith
committed
CLN: Update files (as per pandas-dev#36450) to Python 3.7+ syntax (pandas-dev#36457)
1 parent 88d4adf commit 5461b9a

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

43 files changed

+94
-108
lines changed

pandas/_config/display.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ def detect_console_encoding() -> str:
2222
encoding = None
2323
try:
2424
encoding = sys.stdout.encoding or sys.stdin.encoding
25-
except (AttributeError, IOError):
25+
except (AttributeError, OSError):
2626
pass
2727

2828
# try again for something better

pandas/_testing.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -1960,8 +1960,7 @@ def index_subclass_makers_generator():
19601960
makeCategoricalIndex,
19611961
makeMultiIndex,
19621962
]
1963-
for make_index_func in make_index_funcs:
1964-
yield make_index_func
1963+
yield from make_index_funcs
19651964

19661965

19671966
def all_timeseries_index_generator(k=10):

pandas/_vendored/typing_extensions.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -409,7 +409,7 @@ def __repr__(self):
409409

410410
def __getitem__(self, parameters):
411411
item = typing._type_check(
412-
parameters, "{} accepts only single type".format(self._name)
412+
parameters, f"{self._name} accepts only single type"
413413
)
414414
return _GenericAlias(self, (item,))
415415

@@ -1671,7 +1671,7 @@ def __class_getitem__(cls, params):
16711671
params = (params,)
16721672
if not params and cls is not Tuple:
16731673
raise TypeError(
1674-
"Parameter list to {}[...] cannot be empty".format(cls.__qualname__)
1674+
f"Parameter list to {cls.__qualname__}[...] cannot be empty"
16751675
)
16761676
msg = "Parameters to generic types must be types."
16771677
params = tuple(_type_check(p, msg) for p in params)
@@ -2113,7 +2113,7 @@ def __class_getitem__(cls, params):
21132113
return _AnnotatedAlias(origin, metadata)
21142114

21152115
def __init_subclass__(cls, *args, **kwargs):
2116-
raise TypeError("Cannot subclass {}.Annotated".format(cls.__module__))
2116+
raise TypeError(f"Cannot subclass {cls.__module__}.Annotated")
21172117

21182118
def _strip_annotations(t):
21192119
"""Strips the annotations from a given type.
@@ -2195,7 +2195,7 @@ def _tree_repr(self, tree):
21952195
else:
21962196
tp_repr = origin[0]._tree_repr(origin)
21972197
metadata_reprs = ", ".join(repr(arg) for arg in metadata)
2198-
return "%s[%s, %s]" % (cls, tp_repr, metadata_reprs)
2198+
return f"{cls}[{tp_repr}, {metadata_reprs}]"
21992199

22002200
def _subs_tree(self, tvars=None, args=None): # noqa
22012201
if self is Annotated:
@@ -2382,7 +2382,7 @@ def TypeAlias(self, parameters):
23822382
23832383
It's invalid when used anywhere except as in the example above.
23842384
"""
2385-
raise TypeError("{} is not subscriptable".format(self))
2385+
raise TypeError(f"{self} is not subscriptable")
23862386

23872387

23882388
elif sys.version_info[:2] >= (3, 7):

pandas/_version.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
7474
stderr=(subprocess.PIPE if hide_stderr else None),
7575
)
7676
break
77-
except EnvironmentError:
77+
except OSError:
7878
e = sys.exc_info()[1]
7979
if e.errno == errno.ENOENT:
8080
continue
@@ -121,7 +121,7 @@ def git_get_keywords(versionfile_abs):
121121
# _version.py.
122122
keywords = {}
123123
try:
124-
f = open(versionfile_abs, "r")
124+
f = open(versionfile_abs)
125125
for line in f.readlines():
126126
if line.strip().startswith("git_refnames ="):
127127
mo = re.search(r'=\s*"(.*)"', line)
@@ -132,7 +132,7 @@ def git_get_keywords(versionfile_abs):
132132
if mo:
133133
keywords["full"] = mo.group(1)
134134
f.close()
135-
except EnvironmentError:
135+
except OSError:
136136
pass
137137
return keywords
138138

pandas/io/clipboard/__init__.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -274,7 +274,7 @@ def copy_dev_clipboard(text):
274274
fo.write(text)
275275

276276
def paste_dev_clipboard() -> str:
277-
with open("/dev/clipboard", "rt") as fo:
277+
with open("/dev/clipboard") as fo:
278278
content = fo.read()
279279
return content
280280

@@ -521,7 +521,7 @@ def determine_clipboard():
521521
return init_windows_clipboard()
522522

523523
if platform.system() == "Linux":
524-
with open("/proc/version", "r") as f:
524+
with open("/proc/version") as f:
525525
if "Microsoft" in f.read():
526526
return init_wsl_clipboard()
527527

pandas/io/formats/excel.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -587,8 +587,7 @@ def _format_regular_rows(self):
587587
else:
588588
coloffset = 0
589589

590-
for cell in self._generate_body(coloffset):
591-
yield cell
590+
yield from self._generate_body(coloffset)
592591

593592
def _format_hierarchical_rows(self):
594593
has_aliases = isinstance(self.header, (tuple, list, np.ndarray, ABCIndex))
@@ -664,8 +663,7 @@ def _format_hierarchical_rows(self):
664663
)
665664
gcolidx += 1
666665

667-
for cell in self._generate_body(gcolidx):
668-
yield cell
666+
yield from self._generate_body(gcolidx)
669667

670668
def _generate_body(self, coloffset: int):
671669
if self.styler is None:

pandas/io/html.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -719,7 +719,7 @@ def _build_doc(self):
719719
r = r.getroot()
720720
except AttributeError:
721721
pass
722-
except (UnicodeDecodeError, IOError) as e:
722+
except (UnicodeDecodeError, OSError) as e:
723723
# if the input is a blob of html goop
724724
if not is_url(self.io):
725725
r = fromstring(self.io, parser=parser)

pandas/io/json/_json.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -821,7 +821,7 @@ def close(self):
821821
if self.should_close:
822822
try:
823823
self.open_stream.close()
824-
except (IOError, AttributeError):
824+
except (OSError, AttributeError):
825825
pass
826826
for file_handle in self.file_handles:
827827
file_handle.close()

pandas/io/pytables.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -364,7 +364,7 @@ def read_hdf(
364364

365365
if isinstance(path_or_buf, HDFStore):
366366
if not path_or_buf.is_open:
367-
raise IOError("The HDFStore must be open for reading.")
367+
raise OSError("The HDFStore must be open for reading.")
368368

369369
store = path_or_buf
370370
auto_close = False
@@ -693,7 +693,7 @@ def open(self, mode: str = "a", **kwargs):
693693

694694
try:
695695
self._handle = tables.open_file(self._path, self._mode, **kwargs)
696-
except IOError as err: # pragma: no cover
696+
except OSError as err: # pragma: no cover
697697
if "can not be written" in str(err):
698698
print(f"Opening {self._path} in read-only mode")
699699
self._handle = tables.open_file(self._path, "r", **kwargs)
@@ -724,7 +724,7 @@ def open(self, mode: str = "a", **kwargs):
724724
# trying to read from a non-existent file causes an error which
725725
# is not part of IOError, make it one
726726
if self._mode == "r" and "Unable to open/create file" in str(err):
727-
raise IOError(str(err)) from err
727+
raise OSError(str(err)) from err
728728
raise
729729

730730
def close(self):

pandas/io/stata.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1077,7 +1077,7 @@ def close(self) -> None:
10771077
""" close the handle if its open """
10781078
try:
10791079
self.path_or_buf.close()
1080-
except IOError:
1080+
except OSError:
10811081
pass
10821082

10831083
def _set_encoding(self) -> None:

pandas/plotting/_matplotlib/core.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -342,7 +342,7 @@ def _setup_subplots(self):
342342
valid_log = {False, True, "sym", None}
343343
input_log = {self.logx, self.logy, self.loglog}
344344
if input_log - valid_log:
345-
invalid_log = next(iter((input_log - valid_log)))
345+
invalid_log = next(iter(input_log - valid_log))
346346
raise ValueError(
347347
f"Boolean, None and 'sym' are valid options, '{invalid_log}' is given."
348348
)

pandas/tests/arrays/categorical/test_constructors.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,7 @@ def test_constructor_with_generator(self):
277277
# returned a scalar for a generator
278278

279279
exp = Categorical([0, 1, 2])
280-
cat = Categorical((x for x in [0, 1, 2]))
280+
cat = Categorical(x for x in [0, 1, 2])
281281
tm.assert_categorical_equal(cat, exp)
282282
cat = Categorical(range(3))
283283
tm.assert_categorical_equal(cat, exp)

pandas/tests/arrays/integer/test_construction.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ def test_from_dtype_from_float(data):
2929

3030
# from int / array
3131
expected = pd.Series(data).dropna().reset_index(drop=True)
32-
dropped = np.array(data.dropna()).astype(np.dtype((dtype.type)))
32+
dropped = np.array(data.dropna()).astype(np.dtype(dtype.type))
3333
result = pd.Series(dropped, dtype=str(dtype))
3434
tm.assert_series_equal(result, expected)
3535

pandas/tests/extension/decimal/array.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,7 @@ def _na_value(self):
167167

168168
def _formatter(self, boxed=False):
169169
if boxed:
170-
return "Decimal: {0}".format
170+
return "Decimal: {}".format
171171
return repr
172172

173173
@classmethod

pandas/tests/extension/test_categorical.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ def test_combine_add(self, data_repeated):
137137
s2 = pd.Series(orig_data2)
138138
result = s1.combine(s2, lambda x1, x2: x1 + x2)
139139
expected = pd.Series(
140-
([a + b for (a, b) in zip(list(orig_data1), list(orig_data2))])
140+
[a + b for (a, b) in zip(list(orig_data1), list(orig_data2))]
141141
)
142142
self.assert_series_equal(result, expected)
143143

pandas/tests/frame/test_constructors.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ def test_series_with_name_not_matching_column(self):
7171
lambda: DataFrame({}),
7272
lambda: DataFrame(()),
7373
lambda: DataFrame([]),
74-
lambda: DataFrame((_ for _ in [])),
74+
lambda: DataFrame(_ for _ in []),
7575
lambda: DataFrame(range(0)),
7676
lambda: DataFrame(data=None),
7777
lambda: DataFrame(data={}),

pandas/tests/groupby/test_groupby.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -249,8 +249,8 @@ def test_len():
249249

250250
# issue 11016
251251
df = pd.DataFrame(dict(a=[np.nan] * 3, b=[1, 2, 3]))
252-
assert len(df.groupby(("a"))) == 0
253-
assert len(df.groupby(("b"))) == 3
252+
assert len(df.groupby("a")) == 0
253+
assert len(df.groupby("b")) == 3
254254
assert len(df.groupby(["a", "b"])) == 3
255255

256256

pandas/tests/groupby/test_grouping.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -739,7 +739,7 @@ def test_get_group(self):
739739
with pytest.raises(ValueError, match=msg):
740740
g.get_group("foo")
741741
with pytest.raises(ValueError, match=msg):
742-
g.get_group(("foo"))
742+
g.get_group("foo")
743743
msg = "must supply a same-length tuple to get_group with multiple grouping keys"
744744
with pytest.raises(ValueError, match=msg):
745745
g.get_group(("foo", "bar", "baz"))

pandas/tests/indexes/test_base.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1360,7 +1360,7 @@ def test_get_indexer_strings_raises(self):
13601360
def test_get_indexer_numeric_index_boolean_target(self, idx_class):
13611361
# GH 16877
13621362

1363-
numeric_index = idx_class(RangeIndex((4)))
1363+
numeric_index = idx_class(RangeIndex(4))
13641364
result = numeric_index.get_indexer([True, False, True])
13651365
expected = np.array([-1, -1, -1], dtype=np.intp)
13661366
tm.assert_numpy_array_equal(result, expected)

pandas/tests/indexing/test_indexing.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -745,7 +745,7 @@ def run_tests(df, rhs, right):
745745
# make frames multi-type & re-run tests
746746
for frame in [df, rhs, right]:
747747
frame["joe"] = frame["joe"].astype("float64")
748-
frame["jolie"] = frame["jolie"].map("@{0}".format)
748+
frame["jolie"] = frame["jolie"].map("@{}".format)
749749

750750
run_tests(df, rhs, right)
751751

pandas/tests/io/formats/test_format.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -648,7 +648,7 @@ def test_to_string_unicode_columns(self, float_frame):
648648
assert isinstance(result, str)
649649

650650
def test_to_string_utf8_columns(self):
651-
n = "\u05d0".encode("utf-8")
651+
n = "\u05d0".encode()
652652

653653
with option_context("display.max_rows", 1):
654654
df = DataFrame([1, 2], columns=[n])

pandas/tests/io/formats/test_to_csv.py

+10-10
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ def test_to_csv_with_single_column(self):
2626
"""
2727
with tm.ensure_clean("test.csv") as path:
2828
df1.to_csv(path, header=None, index=None)
29-
with open(path, "r") as f:
29+
with open(path) as f:
3030
assert f.read() == expected1
3131

3232
df2 = DataFrame([1, None])
@@ -36,7 +36,7 @@ def test_to_csv_with_single_column(self):
3636
"""
3737
with tm.ensure_clean("test.csv") as path:
3838
df2.to_csv(path, header=None, index=None)
39-
with open(path, "r") as f:
39+
with open(path) as f:
4040
assert f.read() == expected2
4141

4242
def test_to_csv_defualt_encoding(self):
@@ -58,7 +58,7 @@ def test_to_csv_quotechar(self):
5858

5959
with tm.ensure_clean("test.csv") as path:
6060
df.to_csv(path, quoting=1) # 1=QUOTE_ALL
61-
with open(path, "r") as f:
61+
with open(path) as f:
6262
assert f.read() == expected
6363

6464
expected = """\
@@ -69,7 +69,7 @@ def test_to_csv_quotechar(self):
6969

7070
with tm.ensure_clean("test.csv") as path:
7171
df.to_csv(path, quoting=1, quotechar="$")
72-
with open(path, "r") as f:
72+
with open(path) as f:
7373
assert f.read() == expected
7474

7575
with tm.ensure_clean("test.csv") as path:
@@ -86,7 +86,7 @@ def test_to_csv_doublequote(self):
8686

8787
with tm.ensure_clean("test.csv") as path:
8888
df.to_csv(path, quoting=1, doublequote=True) # QUOTE_ALL
89-
with open(path, "r") as f:
89+
with open(path) as f:
9090
assert f.read() == expected
9191

9292
from _csv import Error
@@ -105,7 +105,7 @@ def test_to_csv_escapechar(self):
105105

106106
with tm.ensure_clean("test.csv") as path: # QUOTE_ALL
107107
df.to_csv(path, quoting=1, doublequote=False, escapechar="\\")
108-
with open(path, "r") as f:
108+
with open(path) as f:
109109
assert f.read() == expected
110110

111111
df = DataFrame({"col": ["a,a", ",bb,"]})
@@ -117,7 +117,7 @@ def test_to_csv_escapechar(self):
117117

118118
with tm.ensure_clean("test.csv") as path:
119119
df.to_csv(path, quoting=3, escapechar="\\") # QUOTE_NONE
120-
with open(path, "r") as f:
120+
with open(path) as f:
121121
assert f.read() == expected
122122

123123
def test_csv_to_string(self):
@@ -342,7 +342,7 @@ def test_to_csv_string_array_ascii(self):
342342
"""
343343
with tm.ensure_clean("str_test.csv") as path:
344344
df.to_csv(path, encoding="ascii")
345-
with open(path, "r") as f:
345+
with open(path) as f:
346346
assert f.read() == expected_ascii
347347

348348
def test_to_csv_string_array_utf8(self):
@@ -356,7 +356,7 @@ def test_to_csv_string_array_utf8(self):
356356
"""
357357
with tm.ensure_clean("unicode_test.csv") as path:
358358
df.to_csv(path, encoding="utf-8")
359-
with open(path, "r") as f:
359+
with open(path) as f:
360360
assert f.read() == expected_utf8
361361

362362
def test_to_csv_string_with_lf(self):
@@ -467,7 +467,7 @@ def test_to_csv_write_to_open_file(self):
467467
with open(path, "w") as f:
468468
f.write("manual header\n")
469469
df.to_csv(f, header=None, index=None)
470-
with open(path, "r") as f:
470+
with open(path) as f:
471471
assert f.read() == expected
472472

473473
def test_to_csv_write_to_open_file_with_newline_py3(self):

pandas/tests/io/formats/test_to_html.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ def test_to_html_encoding(float_frame, tmp_path):
137137
# GH 28663
138138
path = tmp_path / "test.html"
139139
float_frame.to_html(path, encoding="gbk")
140-
with open(str(path), "r", encoding="gbk") as f:
140+
with open(str(path), encoding="gbk") as f:
141141
assert float_frame.to_html() == f.read()
142142

143143

pandas/tests/io/formats/test_to_latex.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ def test_to_latex_filename(self, float_frame):
2121
with tm.ensure_clean("test.tex") as path:
2222
float_frame.to_latex(path)
2323

24-
with open(path, "r") as f:
24+
with open(path) as f:
2525
assert float_frame.to_latex() == f.read()
2626

2727
# test with utf-8 and encoding option (GH 7061)

0 commit comments

Comments
 (0)