Skip to content

Commit 14f03ce

Browse files
jschendeljreback
authored andcommitted
CLN: Use pandas.compat instead of sys.version_info for Python version checks (#20545)
1 parent 89813f5 commit 14f03ce

File tree

16 files changed

+30
-82
lines changed

16 files changed

+30
-82
lines changed

pandas/_version.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
import re
1313
import subprocess
1414
import sys
15+
from pandas.compat import PY3
1516

1617

1718
def get_keywords():
@@ -83,7 +84,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
8384
print("unable to find command, tried %s" % (commands,))
8485
return None
8586
stdout = p.communicate()[0].strip()
86-
if sys.version_info[0] >= 3:
87+
if PY3:
8788
stdout = stdout.decode()
8889
if p.returncode != 0:
8990
if verbose:

pandas/compat/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -369,7 +369,7 @@ def callable(obj):
369369
return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
370370

371371

372-
if sys.version_info[0] < 3:
372+
if PY2:
373373
# In PY2 functools.wraps doesn't provide metadata pytest needs to generate
374374
# decorated tests using parametrization. See pytest GH issue #2782
375375
def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS,

pandas/io/clipboard/clipboards.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
1-
import sys
21
import subprocess
32
from .exceptions import PyperclipException
3+
from pandas.compat import PY2, text_type
44

55
EXCEPT_MSG = """
66
Pyperclip could not find a copy/paste mechanism for your system.
77
For more information, please visit https://pyperclip.readthedocs.org """
8-
PY2 = sys.version_info[0] == 2
9-
text_type = unicode if PY2 else str # noqa
108

119

1210
def init_osx_clipboard():

pandas/io/formats/terminal.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,9 @@
1414
from __future__ import print_function
1515

1616
import os
17-
import sys
1817
import shutil
18+
from pandas.compat import PY3
19+
1920

2021
__all__ = ['get_terminal_size', 'is_terminal']
2122

@@ -29,7 +30,7 @@ def get_terminal_size():
2930
"""
3031
import platform
3132

32-
if sys.version_info[0] >= 3:
33+
if PY3:
3334
return shutil.get_terminal_size()
3435

3536
current_os = platform.system()

pandas/tests/frame/test_analytics.py

+2-9
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,7 @@
44

55
import warnings
66
from datetime import timedelta
7-
from distutils.version import LooseVersion
87
import operator
9-
import sys
108
import pytest
119

1210
from string import ascii_lowercase
@@ -1857,13 +1855,8 @@ def test_round(self):
18571855
'col1': [1.123, 2.123, 3.123],
18581856
'col2': [1.2, 2.2, 3.2]})
18591857

1860-
if LooseVersion(sys.version) < LooseVersion('2.7'):
1861-
# Rounding with decimal is a ValueError in Python < 2.7
1862-
with pytest.raises(ValueError):
1863-
df.round(nan_round_Series)
1864-
else:
1865-
with pytest.raises(TypeError):
1866-
df.round(nan_round_Series)
1858+
with pytest.raises(TypeError):
1859+
df.round(nan_round_Series)
18671860

18681861
# Make sure this doesn't break existing Series.round
18691862
tm.assert_series_equal(df['col1'].round(1), expected_rounded['col1'])

pandas/tests/frame/test_api.py

+4-10
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,6 @@
77
# pylint: disable-msg=W0612,E1101
88
from copy import deepcopy
99
import pydoc
10-
import sys
11-
from distutils.version import LooseVersion
1210

1311
from pandas.compat import range, lrange, long
1412
from pandas import compat
@@ -253,18 +251,14 @@ def test_itertuples(self):
253251
'[(0, 1, 4), (1, 2, 5), (2, 3, 6)]')
254252

255253
tup = next(df.itertuples(name='TestName'))
256-
257-
if LooseVersion(sys.version) >= LooseVersion('2.7'):
258-
assert tup._fields == ('Index', 'a', 'b')
259-
assert (tup.Index, tup.a, tup.b) == tup
260-
assert type(tup).__name__ == 'TestName'
254+
assert tup._fields == ('Index', 'a', 'b')
255+
assert (tup.Index, tup.a, tup.b) == tup
256+
assert type(tup).__name__ == 'TestName'
261257

262258
df.columns = ['def', 'return']
263259
tup2 = next(df.itertuples(name='TestName'))
264260
assert tup2 == (0, 1, 4)
265-
266-
if LooseVersion(sys.version) >= LooseVersion('2.7'):
267-
assert tup2._fields == ('Index', '_1', '_2')
261+
assert tup2._fields == ('Index', '_1', '_2')
268262

269263
df3 = DataFrame({'f' + str(i): [i] for i in range(1024)})
270264
# will raise SyntaxError if trying to create namedtuple

pandas/tests/indexes/datetimes/test_tools.py

-4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
""" test to_datetime """
22

3-
import sys
43
import pytz
54
import pytest
65
import locale
@@ -149,9 +148,6 @@ def test_to_datetime_with_non_exact(self, cache):
149148
# GH 10834
150149
# 8904
151150
# exact kw
152-
if sys.version_info < (2, 7):
153-
pytest.skip('on python version < 2.7')
154-
155151
s = Series(['19MAY11', 'foobar19MAY11', '19MAY11:00:00:00',
156152
'19MAY11 00:00:00Z'])
157153
result = to_datetime(s, format='%d%b%y', exact=False, cache=cache)

pandas/tests/io/formats/test_format.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -1256,8 +1256,6 @@ def test_to_string_float_formatting(self):
12561256

12571257
df_s = df.to_string()
12581258

1259-
# Python 2.5 just wants me to be sad. And debian 32-bit
1260-
# sys.version_info[0] == 2 and sys.version_info[1] < 6:
12611259
if _three_digit_exp():
12621260
expected = (' x\n0 0.00000e+000\n1 2.50000e-001\n'
12631261
'2 3.45600e+003\n3 1.20000e+046\n4 1.64000e+006\n'
@@ -1281,8 +1279,7 @@ def test_to_string_float_formatting(self):
12811279

12821280
df = DataFrame({'x': [1e9, 0.2512]})
12831281
df_s = df.to_string()
1284-
# Python 2.5 just wants me to be sad. And debian 32-bit
1285-
# sys.version_info[0] == 2 and sys.version_info[1] < 6:
1282+
12861283
if _three_digit_exp():
12871284
expected = (' x\n'
12881285
'0 1.000000e+009\n'

pandas/tests/io/parser/common.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -1275,10 +1275,8 @@ def test_verbose_import(self):
12751275
else: # Python engine
12761276
assert output == 'Filled 1 NA values in column a\n'
12771277

1278+
@pytest.mark.skipif(PY3, reason="won't work in Python 3")
12781279
def test_iteration_open_handle(self):
1279-
if PY3:
1280-
pytest.skip(
1281-
"won't work in Python 3 {0}".format(sys.version_info))
12821280

12831281
with tm.ensure_clean() as path:
12841282
with open(path, 'wb') as f:

pandas/tests/io/test_excel.py

+2-8
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
# pylint: disable=E1101
22
import os
3-
import sys
43
import warnings
54
from datetime import datetime, date, time, timedelta
65
from distutils.version import LooseVersion
@@ -16,7 +15,7 @@
1615
import pandas.util.testing as tm
1716
import pandas.util._test_decorators as td
1817
from pandas import DataFrame, Index, MultiIndex
19-
from pandas.compat import u, range, map, BytesIO, iteritems
18+
from pandas.compat import u, range, map, BytesIO, iteritems, PY36
2019
from pandas.core.config import set_option, get_option
2120
from pandas.io.common import URLError
2221
from pandas.io.excel import (
@@ -585,9 +584,6 @@ def test_read_from_s3_url(self, ext):
585584
def test_read_from_file_url(self, ext):
586585

587586
# FILE
588-
if sys.version_info[:2] < (2, 6):
589-
pytest.skip("file:// not supported with Python < 2.6")
590-
591587
localtable = os.path.join(self.dirpath, 'test1' + ext)
592588
local_table = read_excel(localtable)
593589

@@ -2314,9 +2310,9 @@ def custom_converter(css):
23142310

23152311

23162312
@td.skip_if_no('openpyxl')
2313+
@pytest.mark.skipif(not PY36, reason='requires fspath')
23172314
class TestFSPath(object):
23182315

2319-
@pytest.mark.skipif(sys.version_info < (3, 6), reason='requires fspath')
23202316
def test_excelfile_fspath(self):
23212317
with tm.ensure_clean('foo.xlsx') as path:
23222318
df = DataFrame({"A": [1, 2]})
@@ -2325,8 +2321,6 @@ def test_excelfile_fspath(self):
23252321
result = os.fspath(xl)
23262322
assert result == path
23272323

2328-
@pytest.mark.skipif(sys.version_info < (3, 6), reason='requires fspath')
2329-
# @pytest.mark.xfail
23302324
def test_excelwriter_fspath(self):
23312325
with tm.ensure_clean('foo.xlsx') as path:
23322326
writer = ExcelWriter(path)

pandas/tests/io/test_packers.py

-6
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
import os
55
import datetime
66
import numpy as np
7-
import sys
87
from distutils.version import LooseVersion
98

109
from pandas import compat
@@ -298,11 +297,6 @@ def test_nat(self):
298297

299298
def test_datetimes(self):
300299

301-
# fails under 2.6/win32 (np.datetime64 seems broken)
302-
303-
if LooseVersion(sys.version) < LooseVersion('2.7'):
304-
pytest.skip('2.6 with np.datetime64 is broken')
305-
306300
for i in [datetime.datetime(2013, 1, 1),
307301
datetime.datetime(2013, 1, 1, 5, 1),
308302
datetime.date(2013, 1, 1),

pandas/tests/io/test_pickle.py

+6-16
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,12 @@
2020
from distutils.version import LooseVersion
2121
import pandas as pd
2222
from pandas import Index
23-
from pandas.compat import is_platform_little_endian
23+
from pandas.compat import is_platform_little_endian, PY3
2424
import pandas
2525
import pandas.util.testing as tm
2626
import pandas.util._test_decorators as td
2727
from pandas.tseries.offsets import Day, MonthEnd
2828
import shutil
29-
import sys
3029

3130

3231
@pytest.fixture(scope='module')
@@ -474,21 +473,12 @@ def test_read(self, protocol, get_random_path):
474473
tm.assert_frame_equal(df, df2)
475474

476475
@pytest.mark.parametrize('protocol', [3, 4])
477-
@pytest.mark.skipif(sys.version_info[:2] >= (3, 4),
478-
reason="Testing invalid parameters for "
479-
"Python 2.x and 3.y (y < 4).")
476+
@pytest.mark.skipif(PY3, reason="Testing invalid parameters for Python 2")
480477
def test_read_bad_versions(self, protocol, get_random_path):
481-
# For Python 2.x (respectively 3.y with y < 4), [expected]
482-
# HIGHEST_PROTOCOL should be 2 (respectively 3). Hence, the protocol
483-
# parameter should not exceed 2 (respectively 3).
484-
if sys.version_info[:2] < (3, 0):
485-
expect_hp = 2
486-
else:
487-
expect_hp = 3
488-
with tm.assert_raises_regex(ValueError,
489-
"pickle protocol %d asked for; the highest"
490-
" available protocol is %d" % (protocol,
491-
expect_hp)):
478+
# For Python 2, HIGHEST_PROTOCOL should be 2.
479+
msg = ("pickle protocol {protocol} asked for; the highest available "
480+
"protocol is 2").format(protocol=protocol)
481+
with tm.assert_raises_regex(ValueError, msg):
492482
with tm.ensure_clean(get_random_path) as path:
493483
df = tm.makeDataFrame()
494484
df.to_pickle(path, protocol=protocol)

pandas/tests/io/test_stata.py

-4
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,8 @@
44
import datetime as dt
55
import os
66
import struct
7-
import sys
87
import warnings
98
from datetime import datetime
10-
from distutils.version import LooseVersion
119
from collections import OrderedDict
1210

1311
import numpy as np
@@ -144,8 +142,6 @@ def test_read_dta1(self, file):
144142
tm.assert_frame_equal(parsed, expected)
145143

146144
def test_read_dta2(self):
147-
if LooseVersion(sys.version) < LooseVersion('2.7'):
148-
pytest.skip('datetime interp under 2.6 is faulty')
149145

150146
expected = DataFrame.from_records(
151147
[

pandas/tests/scalar/timestamp/test_comparisons.py

+4-5
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
# -*- coding: utf-8 -*-
2-
import sys
32
from datetime import datetime
43
import operator
54

@@ -9,7 +8,7 @@
98
from dateutil.tz import tzutc
109
from pytz import utc
1110

12-
from pandas.compat import long
11+
from pandas.compat import long, PY2
1312
from pandas import Timestamp
1413

1514

@@ -104,7 +103,7 @@ def test_cant_compare_tz_naive_w_aware(self):
104103
pytest.raises(Exception, b.__lt__, a)
105104
pytest.raises(Exception, b.__gt__, a)
106105

107-
if sys.version_info < (3, 3):
106+
if PY2:
108107
pytest.raises(Exception, a.__eq__, b.to_pydatetime())
109108
pytest.raises(Exception, a.to_pydatetime().__eq__, b)
110109
else:
@@ -125,7 +124,7 @@ def test_cant_compare_tz_naive_w_aware_explicit_pytz(self):
125124
pytest.raises(Exception, b.__lt__, a)
126125
pytest.raises(Exception, b.__gt__, a)
127126

128-
if sys.version_info < (3, 3):
127+
if PY2:
129128
pytest.raises(Exception, a.__eq__, b.to_pydatetime())
130129
pytest.raises(Exception, a.to_pydatetime().__eq__, b)
131130
else:
@@ -146,7 +145,7 @@ def test_cant_compare_tz_naive_w_aware_dateutil(self):
146145
pytest.raises(Exception, b.__lt__, a)
147146
pytest.raises(Exception, b.__gt__, a)
148147

149-
if sys.version_info < (3, 3):
148+
if PY2:
150149
pytest.raises(Exception, a.__eq__, b.to_pydatetime())
151150
pytest.raises(Exception, a.to_pydatetime().__eq__, b)
152151
else:

pandas/tests/util/test_util.py

+2-5
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from collections import OrderedDict
88

99
import pytest
10-
from pandas.compat import intern
10+
from pandas.compat import intern, PY3
1111
import pandas.core.common as com
1212
from pandas.util._move import move_into_mutable_buffer, BadMove, stolenbuf
1313
from pandas.util._decorators import deprecate_kwarg, make_signature
@@ -374,10 +374,7 @@ def test_exactly_one_ref(self):
374374
# materialize as bytearray to show that it is mutable
375375
assert bytearray(as_stolen_buf) == b'test'
376376

377-
@pytest.mark.skipif(
378-
sys.version_info[0] > 2,
379-
reason='bytes objects cannot be interned in py3',
380-
)
377+
@pytest.mark.skipif(PY3, reason='bytes objects cannot be interned in py3')
381378
def test_interned(self):
382379
salt = uuid4().hex
383380

pandas/util/testing.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2088,7 +2088,7 @@ def dec(f):
20882088
# and conditionally raise on these exception types
20892089
_network_error_classes = (IOError, httplib.HTTPException)
20902090

2091-
if sys.version_info >= (3, 3):
2091+
if PY3:
20922092
_network_error_classes += (TimeoutError,) # noqa
20932093

20942094

0 commit comments

Comments
 (0)