Skip to content

Commit 37ff082

Browse files
Standard library imports style check (#50116)
* put stdlib imports in pandas/tests at top of file * Update .pre-commit-config.yaml Removed ^pandas/core/generic\.py from .pre-commit-config.yaml * requested changes from @MarcoGorelli to fix tests and revert one unrelated docstring change. * Restore ugly docstring Co-authored-by: Marco Edward Gorelli <[email protected]>
1 parent 47c9ee7 commit 37ff082

25 files changed

+77
-102
lines changed

pandas/tests/apply/test_series_apply.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
Counter,
33
defaultdict,
44
)
5+
from decimal import Decimal
6+
import math
57

68
import numpy as np
79
import pytest
@@ -37,8 +39,6 @@ def test_apply(datetime_series):
3739
tm.assert_series_equal(datetime_series.apply(np.sqrt), np.sqrt(datetime_series))
3840

3941
# element-wise apply
40-
import math
41-
4242
tm.assert_series_equal(datetime_series.apply(math.exp), np.exp(datetime_series))
4343

4444
# empty series
@@ -525,8 +525,6 @@ def test_map_type_inference():
525525

526526

527527
def test_map_decimal(string_series):
528-
from decimal import Decimal
529-
530528
result = string_series.map(lambda x: Decimal(str(x)))
531529
assert result.dtype == np.object_
532530
assert isinstance(result[0], Decimal)

pandas/tests/arrays/test_datetimelike.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from __future__ import annotations
22

3+
import array
34
import re
45

56
import numpy as np
@@ -1346,9 +1347,6 @@ def array_likes(request):
13461347
if name == "memoryview":
13471348
data = memoryview(arr)
13481349
elif name == "array":
1349-
# stdlib array
1350-
import array
1351-
13521350
data = array.array("i", arr)
13531351
elif name == "dask":
13541352
import dask.array

pandas/tests/frame/indexing/test_indexing.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
datetime,
44
timedelta,
55
)
6+
from decimal import Decimal
67
import re
78

89
import numpy as np
@@ -467,8 +468,6 @@ def test_setitem_corner2(self):
467468

468469
def test_setitem_ambig(self):
469470
# Difficulties with mixed-type data
470-
from decimal import Decimal
471-
472471
# Created as float type
473472
dm = DataFrame(index=range(3), columns=range(3))
474473

pandas/tests/frame/methods/test_to_records.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
from collections import abc
2+
import email
3+
from email.parser import Parser
24

35
import numpy as np
46
import pytest
@@ -58,9 +60,6 @@ def test_to_records_with_multindex(self):
5860
assert "one" not in r
5961

6062
def test_to_records_with_Mapping_type(self):
61-
import email
62-
from email.parser import Parser
63-
6463
abc.Mapping.register(email.message.Message)
6564

6665
headers = Parser().parsestr(

pandas/tests/frame/test_constructors.py

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,18 @@
1+
import array
12
from collections import (
23
OrderedDict,
34
abc,
5+
defaultdict,
6+
namedtuple,
47
)
8+
from dataclasses import make_dataclass
59
from datetime import (
610
date,
711
datetime,
812
timedelta,
913
)
1014
import functools
15+
import random
1116
import re
1217
from typing import Iterator
1318
import warnings
@@ -466,8 +471,6 @@ def test_constructor_numpy_uints(self, values):
466471
assert result[0][0] == value
467472

468473
def test_constructor_ordereddict(self):
469-
import random
470-
471474
nitems = 100
472475
nums = list(range(nitems))
473476
random.shuffle(nums)
@@ -718,8 +721,6 @@ def test_constructor_subclass_dict(self, dict_subclass):
718721

719722
def test_constructor_defaultdict(self, float_frame):
720723
# try with defaultdict
721-
from collections import defaultdict
722-
723724
data = {}
724725
float_frame.loc[: float_frame.index[10], "B"] = np.nan
725726

@@ -1343,8 +1344,6 @@ def __len__(self) -> int:
13431344
def test_constructor_stdlib_array(self):
13441345
# GH 4297
13451346
# support Array
1346-
import array
1347-
13481347
result = DataFrame({"A": array.array("i", range(10))})
13491348
expected = DataFrame({"A": list(range(10))})
13501349
tm.assert_frame_equal(result, expected, check_dtype=False)
@@ -1544,8 +1543,6 @@ def test_constructor_list_of_tuples(self):
15441543

15451544
def test_constructor_list_of_namedtuples(self):
15461545
# GH11181
1547-
from collections import namedtuple
1548-
15491546
named_tuple = namedtuple("Pandas", list("ab"))
15501547
tuples = [named_tuple(1, 3), named_tuple(2, 4)]
15511548
expected = DataFrame({"a": [1, 2], "b": [3, 4]})
@@ -1559,8 +1556,6 @@ def test_constructor_list_of_namedtuples(self):
15591556

15601557
def test_constructor_list_of_dataclasses(self):
15611558
# GH21910
1562-
from dataclasses import make_dataclass
1563-
15641559
Point = make_dataclass("Point", [("x", int), ("y", int)])
15651560

15661561
data = [Point(0, 3), Point(1, 3)]
@@ -1570,8 +1565,6 @@ def test_constructor_list_of_dataclasses(self):
15701565

15711566
def test_constructor_list_of_dataclasses_with_varying_types(self):
15721567
# GH21910
1573-
from dataclasses import make_dataclass
1574-
15751568
# varying types
15761569
Point = make_dataclass("Point", [("x", int), ("y", int)])
15771570
HLine = make_dataclass("HLine", [("x0", int), ("x1", int), ("y", int)])
@@ -1586,8 +1579,6 @@ def test_constructor_list_of_dataclasses_with_varying_types(self):
15861579

15871580
def test_constructor_list_of_dataclasses_error_thrown(self):
15881581
# GH21910
1589-
from dataclasses import make_dataclass
1590-
15911582
Point = make_dataclass("Point", [("x", int), ("y", int)])
15921583

15931584
# expect TypeError

pandas/tests/groupby/test_filters.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from string import ascii_lowercase
2+
13
import numpy as np
24
import pytest
35

@@ -192,8 +194,6 @@ def test_filter_against_workaround():
192194
tm.assert_series_equal(new_way.sort_values(), old_way.sort_values())
193195

194196
# Set up DataFrame of ints, floats, strings.
195-
from string import ascii_lowercase
196-
197197
letters = np.array(list(ascii_lowercase))
198198
N = 1000
199199
random_letters = letters.take(np.random.randint(0, 26, N))

pandas/tests/groupby/test_grouping.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,10 @@
1-
""" test where we are determining what we are grouping, or getting groups """
1+
"""
2+
test where we are determining what we are grouping, or getting groups
3+
"""
4+
from datetime import (
5+
date,
6+
timedelta,
7+
)
28

39
import numpy as np
410
import pytest
@@ -167,14 +173,8 @@ def test_grouper_index_types(self, index):
167173
df.groupby(list("abcde"), group_keys=False).apply(lambda x: x)
168174

169175
def test_grouper_multilevel_freq(self):
170-
171176
# GH 7885
172177
# with level and freq specified in a Grouper
173-
from datetime import (
174-
date,
175-
timedelta,
176-
)
177-
178178
d0 = date.today() - timedelta(days=14)
179179
dates = date_range(d0, date.today())
180180
date_index = MultiIndex.from_product([dates, dates], names=["foo", "bar"])

pandas/tests/groupby/test_timegrouper.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
1-
""" test with the TimeGrouper / grouping with datetimes """
2-
3-
from datetime import datetime
1+
"""
2+
test with the TimeGrouper / grouping with datetimes
3+
"""
4+
from datetime import (
5+
datetime,
6+
timedelta,
7+
)
48
from io import StringIO
59

610
import numpy as np
@@ -763,8 +767,6 @@ def test_first_last_max_min_on_time_data(self):
763767
# GH 10295
764768
# Verify that NaT is not in the result of max, min, first and last on
765769
# Dataframe with datetime or timedelta values.
766-
from datetime import timedelta as td
767-
768770
df_test = DataFrame(
769771
{
770772
"dt": [
@@ -774,7 +776,13 @@ def test_first_last_max_min_on_time_data(self):
774776
"2015-07-23 12:12",
775777
np.nan,
776778
],
777-
"td": [np.nan, td(days=1), td(days=2), td(days=3), np.nan],
779+
"td": [
780+
np.nan,
781+
timedelta(days=1),
782+
timedelta(days=2),
783+
timedelta(days=3),
784+
np.nan,
785+
],
778786
}
779787
)
780788
df_test.dt = pd.to_datetime(df_test.dt)

pandas/tests/indexes/test_common.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@
33
any index subclass except for MultiIndex. Makes use of the `index_flat`
44
fixture defined in pandas/conftest.py.
55
"""
6+
from copy import (
7+
copy,
8+
deepcopy,
9+
)
610
import re
711

812
import numpy as np
@@ -132,11 +136,6 @@ def test_set_name_methods(self, index_flat):
132136
assert index.names == [name]
133137

134138
def test_copy_and_deepcopy(self, index_flat):
135-
from copy import (
136-
copy,
137-
deepcopy,
138-
)
139-
140139
index = index_flat
141140

142141
for func in (copy, deepcopy):

pandas/tests/indexing/multiindex/test_slice.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
from datetime import (
2+
datetime,
3+
timedelta,
4+
)
5+
16
import numpy as np
27
import pytest
38

@@ -248,12 +253,7 @@ def test_multiindex_slicers_datetimelike(self):
248253

249254
# GH 7429
250255
# buggy/inconsistent behavior when slicing with datetime-like
251-
import datetime
252-
253-
dates = [
254-
datetime.datetime(2012, 1, 1, 12, 12, 12) + datetime.timedelta(days=i)
255-
for i in range(6)
256-
]
256+
dates = [datetime(2012, 1, 1, 12, 12, 12) + timedelta(days=i) for i in range(6)]
257257
freq = [1, 2]
258258
index = MultiIndex.from_product([dates, freq], names=["date", "frequency"])
259259

pandas/tests/io/excel/test_readers.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from functools import partial
66
import os
77
from pathlib import Path
8+
import platform
89
from urllib.error import URLError
910
from zipfile import BadZipFile
1011

@@ -897,8 +898,6 @@ def test_read_from_file_url(self, read_ext, datapath):
897898
url_table = pd.read_excel("file://localhost/" + localtable)
898899
except URLError:
899900
# fails on some systems
900-
import platform
901-
902901
platform_info = " ".join(platform.uname()).strip()
903902
pytest.skip(f"failing on {platform_info}")
904903

pandas/tests/io/formats/test_printing.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import string
2+
13
import numpy as np
24
import pytest
35

@@ -19,8 +21,6 @@ def test_adjoin():
1921

2022

2123
def test_repr_binary_type():
22-
import string
23-
2424
letters = string.ascii_letters
2525
try:
2626
raw = bytes(letters, encoding=cf.get_option("display.encoding"))

pandas/tests/io/formats/test_to_csv.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import sys
44
from zipfile import ZipFile
55

6+
from _csv import Error
67
import numpy as np
78
import pytest
89

@@ -94,8 +95,6 @@ def test_to_csv_doublequote(self):
9495
with open(path) as f:
9596
assert f.read() == expected
9697

97-
from _csv import Error
98-
9998
with tm.ensure_clean("test.csv") as path:
10099
with pytest.raises(Error, match="escapechar"):
101100
df.to_csv(path, doublequote=False) # no escapechar set

pandas/tests/io/json/test_pandas.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import json
66
import os
77
import sys
8+
import time
89

910
import numpy as np
1011
import pytest
@@ -1730,8 +1731,6 @@ def test_json_multiindex(self, dataframe, expected):
17301731

17311732
@pytest.mark.single_cpu
17321733
def test_to_s3(self, s3_resource, s3so):
1733-
import time
1734-
17351734
# GH 28375
17361735
mock_bucket_name, target_file = "pandas-test", "test.json"
17371736
df = DataFrame({"x": [1, 2, 3], "y": [2, 4, 6]})

pandas/tests/io/parser/test_c_parser_only.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
these tests out of this module as soon as the Python parser can accept
55
further arguments when parsing.
66
"""
7-
7+
from decimal import Decimal
88
from io import (
99
BytesIO,
1010
StringIO,
@@ -169,8 +169,6 @@ def test_unsupported_dtype(c_parser_only, match, kwargs):
169169
@td.skip_if_32bit
170170
@pytest.mark.slow
171171
def test_precise_conversion(c_parser_only):
172-
from decimal import Decimal
173-
174172
parser = c_parser_only
175173

176174
normal_errors = []

pandas/tests/io/parser/test_encoding.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@
22
Tests encoding functionality during parsing
33
for all of the parsers defined in parsers.py
44
"""
5-
from io import BytesIO
5+
from io import (
6+
BytesIO,
7+
TextIOWrapper,
8+
)
69
import os
710
import tempfile
811
import uuid
@@ -59,8 +62,6 @@ def test_utf16_bom_skiprows(all_parsers, sep, encoding):
5962
utf8 = "utf-8"
6063

6164
with tm.ensure_clean(path) as path:
62-
from io import TextIOWrapper
63-
6465
bytes_data = data.encode(encoding)
6566

6667
with open(path, "wb") as f:

0 commit comments

Comments
 (0)