Skip to content

Commit 0e99111

Browse files
datapythonistajreback
authored andcommitted
CLN: Removing Python 3.6 or higher references that are always true (#29492)
1 parent 33181d9 commit 0e99111

27 files changed

+43
-235
lines changed

pandas/_libs/tslibs/timestamps.pyx

+2-4
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@ from pandas._libs.tslibs.tzconversion import (
3636
# Constants
3737
_zero_time = datetime_time(0, 0)
3838
_no_input = object()
39-
PY36 = sys.version_info >= (3, 6)
4039

4140
# ----------------------------------------------------------------------
4241

@@ -982,9 +981,8 @@ default 'raise'
982981
else:
983982
kwargs = {'year': dts.year, 'month': dts.month, 'day': dts.day,
984983
'hour': dts.hour, 'minute': dts.min, 'second': dts.sec,
985-
'microsecond': dts.us, 'tzinfo': _tzinfo}
986-
if PY36:
987-
kwargs['fold'] = fold
984+
'microsecond': dts.us, 'tzinfo': _tzinfo,
985+
'fold': fold}
988986
ts_input = datetime(**kwargs)
989987

990988
ts = convert_datetime_to_tsobject(ts_input, _tzinfo)

pandas/compat/__init__.py

-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
import sys
1313
import warnings
1414

15-
PY36 = sys.version_info >= (3, 6)
1615
PY37 = sys.version_info >= (3, 7)
1716
PY38 = sys.version_info >= (3, 8)
1817
PYPY = platform.python_implementation() == "PyPy"

pandas/core/common.py

+1-12
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
"""
66

77
import collections
8-
from collections import OrderedDict, abc
8+
from collections import abc
99
from datetime import datetime, timedelta
1010
from functools import partial
1111
import inspect
@@ -14,7 +14,6 @@
1414
import numpy as np
1515

1616
from pandas._libs import lib, tslibs
17-
from pandas.compat import PY36
1817

1918
from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike
2019
from pandas.core.dtypes.common import (
@@ -215,16 +214,6 @@ def try_sort(iterable):
215214
return listed
216215

217216

218-
def dict_keys_to_ordered_list(mapping):
219-
# when pandas drops support for Python < 3.6, this function
220-
# can be replaced by a simple list(mapping.keys())
221-
if PY36 or isinstance(mapping, OrderedDict):
222-
keys = list(mapping.keys())
223-
else:
224-
keys = try_sort(mapping)
225-
return keys
226-
227-
228217
def asarray_tuplesafe(values, dtype=None):
229218

230219
if not (isinstance(values, (list, tuple)) or hasattr(values, "__array__")):

pandas/core/dtypes/common.py

+2-10
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66

77
from pandas._libs import algos, lib
88
from pandas._libs.tslibs import conversion
9-
from pandas.compat import PY36
109

1110
from pandas.core.dtypes.dtypes import (
1211
CategoricalDtype,
@@ -1266,24 +1265,17 @@ def _is_unorderable_exception(e: TypeError) -> bool:
12661265
"""
12671266
Check if the exception raised is an unorderable exception.
12681267
1269-
The error message differs for 3 <= PY <= 3.5 and PY >= 3.6, so
1270-
we need to condition based on Python version.
1271-
12721268
Parameters
12731269
----------
12741270
e : Exception or sub-class
12751271
The exception object to check.
12761272
12771273
Returns
12781274
-------
1279-
boolean
1275+
bool
12801276
Whether or not the exception raised is an unorderable exception.
12811277
"""
1282-
1283-
if PY36:
1284-
return "'>' not supported between instances of" in str(e)
1285-
1286-
return "unorderable" in str(e)
1278+
return "'>' not supported between instances of" in str(e)
12871279

12881280

12891281
def needs_i8_conversion(arr_or_dtype) -> bool:

pandas/core/frame.py

+7-26
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@
3434
from pandas._config import get_option
3535

3636
from pandas._libs import algos as libalgos, lib
37-
from pandas.compat import PY36
3837
from pandas.compat.numpy import function as nv
3938
from pandas.util._decorators import (
4039
Appender,
@@ -3498,16 +3497,12 @@ def assign(self, **kwargs):
34983497
Notes
34993498
-----
35003499
Assigning multiple columns within the same ``assign`` is possible.
3501-
For Python 3.6 and above, later items in '\*\*kwargs' may refer to
3502-
newly created or modified columns in 'df'; items are computed and
3503-
assigned into 'df' in order. For Python 3.5 and below, the order of
3504-
keyword arguments is not specified, you cannot refer to newly created
3505-
or modified columns. All items are computed first, and then assigned
3506-
in alphabetical order.
3500+
Later items in '\*\*kwargs' may refer to newly created or modified
3501+
columns in 'df'; items are computed and assigned into 'df' in order.
35073502
35083503
.. versionchanged:: 0.23.0
35093504
3510-
Keyword argument order is maintained for Python 3.6 and later.
3505+
Keyword argument order is maintained.
35113506
35123507
Examples
35133508
--------
@@ -3533,9 +3528,8 @@ def assign(self, **kwargs):
35333528
Portland 17.0 62.6
35343529
Berkeley 25.0 77.0
35353530
3536-
In Python 3.6+, you can create multiple columns within the same assign
3537-
where one of the columns depends on another one defined within the same
3538-
assign:
3531+
You can create multiple columns within the same assign where one
3532+
of the columns depends on another one defined within the same assign:
35393533
35403534
>>> df.assign(temp_f=lambda x: x['temp_c'] * 9 / 5 + 32,
35413535
... temp_k=lambda x: (x['temp_f'] + 459.67) * 5 / 9)
@@ -3545,21 +3539,8 @@ def assign(self, **kwargs):
35453539
"""
35463540
data = self.copy()
35473541

3548-
# >= 3.6 preserve order of kwargs
3549-
if PY36:
3550-
for k, v in kwargs.items():
3551-
data[k] = com.apply_if_callable(v, data)
3552-
else:
3553-
# <= 3.5: do all calculations first...
3554-
results = OrderedDict()
3555-
for k, v in kwargs.items():
3556-
results[k] = com.apply_if_callable(v, data)
3557-
3558-
# <= 3.5 and earlier
3559-
results = sorted(results.items())
3560-
# ... and then assign
3561-
for k, v in results:
3562-
data[k] = v
3542+
for k, v in kwargs.items():
3543+
data[k] = com.apply_if_callable(v, data)
35633544
return data
35643545

35653546
def _sanitize_column(self, key, value, broadcast=True):

pandas/core/generic.py

+1-7
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
import re
99
from textwrap import dedent
1010
from typing import (
11-
TYPE_CHECKING,
1211
Any,
1312
Callable,
1413
Dict,
@@ -190,12 +189,7 @@ class NDFrame(PandasObject, SelectionMixin):
190189
_metadata = [] # type: List[str]
191190
_is_copy = None
192191
_data = None # type: BlockManager
193-
194-
if TYPE_CHECKING:
195-
# TODO(PY36): replace with _attrs : Dict[Hashable, Any]
196-
# We need the TYPE_CHECKING, because _attrs is not a class attribute
197-
# and Py35 doesn't support the new syntax.
198-
_attrs = {} # type: Dict[Optional[Hashable], Any]
192+
_attrs: Dict[Optional[Hashable], Any]
199193

200194
# ----------------------------------------------------------------------
201195
# Constructors

pandas/core/groupby/generic.py

-8
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@
2828
import numpy as np
2929

3030
from pandas._libs import Timestamp, lib
31-
from pandas.compat import PY36
3231
from pandas.util._decorators import Appender, Substitution
3332

3433
from pandas.core.dtypes.cast import (
@@ -233,10 +232,6 @@ def aggregate(self, func=None, *args, **kwargs):
233232
no_arg_message = "Must provide 'func' or named aggregation **kwargs."
234233
if relabeling:
235234
columns = list(kwargs)
236-
if not PY36:
237-
# sort for 3.5 and earlier
238-
columns = list(sorted(columns))
239-
240235
func = [kwargs[col] for col in columns]
241236
kwargs = {}
242237
if not columns:
@@ -1804,9 +1799,6 @@ def _normalize_keyword_aggregation(kwargs):
18041799
>>> _normalize_keyword_aggregation({'output': ('input', 'sum')})
18051800
(OrderedDict([('input', ['sum'])]), ('output',), [('input', 'sum')])
18061801
"""
1807-
if not PY36:
1808-
kwargs = OrderedDict(sorted(kwargs.items()))
1809-
18101802
# Normalize the aggregation functions as Dict[column, List[func]],
18111803
# process normally, then fixup the names.
18121804
# TODO(Py35): When we drop python 3.5, change this to

pandas/core/internals/construction.py

+5-11
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,12 @@
22
Functions for preparing various inputs passed to the DataFrame or Series
33
constructors before passing them to a BlockManager.
44
"""
5-
from collections import OrderedDict, abc
5+
from collections import abc
66

77
import numpy as np
88
import numpy.ma as ma
99

1010
from pandas._libs import lib
11-
import pandas.compat as compat
12-
from pandas.compat import PY36
1311

1412
from pandas.core.dtypes.cast import (
1513
construct_1d_arraylike_from_scalar,
@@ -235,7 +233,7 @@ def init_dict(data, index, columns, dtype=None):
235233
arrays.loc[missing] = [val] * missing.sum()
236234

237235
else:
238-
keys = com.dict_keys_to_ordered_list(data)
236+
keys = list(data.keys())
239237
columns = data_names = Index(keys)
240238
arrays = (com.maybe_iterable_to_list(data[k]) for k in keys)
241239
# GH#24096 need copy to be deep for datetime64tz case
@@ -331,16 +329,13 @@ def extract_index(data):
331329
have_raw_arrays = False
332330
have_series = False
333331
have_dicts = False
334-
have_ordered = False
335332

336333
for val in data:
337334
if isinstance(val, ABCSeries):
338335
have_series = True
339336
indexes.append(val.index)
340337
elif isinstance(val, dict):
341338
have_dicts = True
342-
if isinstance(val, OrderedDict):
343-
have_ordered = True
344339
indexes.append(list(val.keys()))
345340
elif is_list_like(val) and getattr(val, "ndim", 1) == 1:
346341
have_raw_arrays = True
@@ -352,7 +347,7 @@ def extract_index(data):
352347
if have_series:
353348
index = _union_indexes(indexes)
354349
elif have_dicts:
355-
index = _union_indexes(indexes, sort=not (compat.PY36 or have_ordered))
350+
index = _union_indexes(indexes, sort=False)
356351

357352
if have_raw_arrays:
358353
lengths = list(set(raw_lengths))
@@ -531,7 +526,7 @@ def _list_of_dict_to_arrays(data, columns, coerce_float=False, dtype=None):
531526
"""Convert list of dicts to numpy arrays
532527
533528
if `columns` is not passed, column names are inferred from the records
534-
- for OrderedDict and (on Python>=3.6) dicts, the column names match
529+
- for OrderedDict and dicts, the column names match
535530
the key insertion-order from the first record to the last.
536531
- For other kinds of dict-likes, the keys are lexically sorted.
537532
@@ -551,8 +546,7 @@ def _list_of_dict_to_arrays(data, columns, coerce_float=False, dtype=None):
551546

552547
if columns is None:
553548
gen = (list(x.keys()) for x in data)
554-
types = (dict, OrderedDict) if PY36 else OrderedDict
555-
sort = not any(isinstance(d, types) for d in data)
549+
sort = not any(isinstance(d, dict) for d in data)
556550
columns = lib.fast_unique_multiple_list_gen(gen, sort=sort)
557551

558552
# assure that they are of the base dict class and not of derived

pandas/core/reshape/concat.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -293,7 +293,7 @@ def __init__(
293293

294294
if isinstance(objs, dict):
295295
if keys is None:
296-
keys = com.dict_keys_to_ordered_list(objs)
296+
keys = list(objs.keys())
297297
objs = [objs[k] for k in keys]
298298
else:
299299
objs = list(objs)

pandas/core/series.py

-9
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
"""
22
Data structure for 1-dimensional cross-sectional and time series data
33
"""
4-
from collections import OrderedDict
54
from io import StringIO
65
from shutil import get_terminal_size
76
from textwrap import dedent
@@ -13,7 +12,6 @@
1312
from pandas._config import get_option
1413

1514
from pandas._libs import index as libindex, lib, reshape, tslibs
16-
from pandas.compat import PY36
1715
from pandas.compat.numpy import function as nv
1816
from pandas.util._decorators import Appender, Substitution, deprecate
1917
from pandas.util._validators import validate_bool_kwarg, validate_percentile
@@ -364,13 +362,6 @@ def _init_dict(self, data, index=None, dtype=None):
364362
# Now we just make sure the order is respected, if any
365363
if data and index is not None:
366364
s = s.reindex(index, copy=False)
367-
elif not PY36 and not isinstance(data, OrderedDict) and data:
368-
# Need the `and data` to avoid sorting Series(None, index=[...])
369-
# since that isn't really dict-like
370-
try:
371-
s = s.sort_index()
372-
except TypeError:
373-
pass
374365
return s._data, s.index
375366

376367
@classmethod

pandas/io/pickle.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import pickle
33
import warnings
44

5-
from pandas.compat import PY36, pickle_compat as pc
5+
from pandas.compat import pickle_compat as pc
66

77
from pandas.io.common import _get_handle, _stringify_path
88

@@ -140,9 +140,7 @@ def read_pickle(path, compression="infer"):
140140
# 1) try standard library Pickle
141141
# 2) try pickle_compat (older pandas version) to handle subclass changes
142142

143-
excs_to_catch = (AttributeError, ImportError)
144-
if PY36:
145-
excs_to_catch += (ModuleNotFoundError,)
143+
excs_to_catch = (AttributeError, ImportError, ModuleNotFoundError)
146144

147145
try:
148146
with warnings.catch_warnings(record=True):

pandas/tests/extension/json/test_json.py

-10
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33

44
import pytest
55

6-
from pandas.compat import PY36
7-
86
import pandas as pd
97
from pandas.tests.extension import base
108
import pandas.util.testing as tm
@@ -180,9 +178,6 @@ def test_fillna_frame(self):
180178

181179

182180
unhashable = pytest.mark.skip(reason="Unhashable")
183-
unstable = pytest.mark.skipif(
184-
not PY36, reason="Dictionary order unstable" # 3.6 or higher
185-
)
186181

187182

188183
class TestReduce(base.BaseNoReduceTests):
@@ -199,20 +194,16 @@ def test_sort_values_frame(self):
199194
# TODO (EA.factorize): see if _values_for_factorize allows this.
200195
pass
201196

202-
@unstable
203197
def test_argsort(self, data_for_sorting):
204198
super().test_argsort(data_for_sorting)
205199

206-
@unstable
207200
def test_argsort_missing(self, data_missing_for_sorting):
208201
super().test_argsort_missing(data_missing_for_sorting)
209202

210-
@unstable
211203
@pytest.mark.parametrize("ascending", [True, False])
212204
def test_sort_values(self, data_for_sorting, ascending):
213205
super().test_sort_values(data_for_sorting, ascending)
214206

215-
@unstable
216207
@pytest.mark.parametrize("ascending", [True, False])
217208
def test_sort_values_missing(self, data_missing_for_sorting, ascending):
218209
super().test_sort_values_missing(data_missing_for_sorting, ascending)
@@ -280,7 +271,6 @@ def test_groupby_extension_apply(self):
280271
we'll be able to dispatch unique.
281272
"""
282273

283-
@unstable
284274
@pytest.mark.parametrize("as_index", [True, False])
285275
def test_groupby_extension_agg(self, as_index, data_for_grouping):
286276
super().test_groupby_extension_agg(as_index, data_for_grouping)

0 commit comments

Comments
 (0)