Skip to content

Commit 882961d

Browse files
jschendelgfyoung
authored andcommitted
CLN: Remove miscellaneous rarely used items from pandas.compat (pandas-dev#25873)
xref pandas-devgh-25725
1 parent 850fbb5 commit 882961d

File tree

18 files changed

+46
-176
lines changed

18 files changed

+46
-176
lines changed

pandas/_libs/parsers.pyx

+4-5
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
11
# Copyright (c) 2012, Lambda Foundry, Inc.
22
# See LICENSE for the license
3+
import bz2
4+
import gzip
5+
import lzma
36
import os
47
import sys
58
import time
69
import warnings
10+
import zipfile
711

812
from csv import QUOTE_MINIMAL, QUOTE_NONNUMERIC, QUOTE_NONE
913
from errno import ENOENT
@@ -624,16 +628,13 @@ cdef class TextReader:
624628

625629
if self.compression:
626630
if self.compression == 'gzip':
627-
import gzip
628631
if isinstance(source, basestring):
629632
source = gzip.GzipFile(source, 'rb')
630633
else:
631634
source = gzip.GzipFile(fileobj=source)
632635
elif self.compression == 'bz2':
633-
import bz2
634636
source = bz2.BZ2File(source, 'rb')
635637
elif self.compression == 'zip':
636-
import zipfile
637638
zip_file = zipfile.ZipFile(source)
638639
zip_names = zip_file.namelist()
639640

@@ -648,8 +649,6 @@ cdef class TextReader:
648649
raise ValueError('Multiple files found in compressed '
649650
'zip file %s', str(zip_names))
650651
elif self.compression == 'xz':
651-
lzma = compat.import_lzma()
652-
653652
if isinstance(source, basestring):
654653
source = lzma.LZMAFile(source, 'rb')
655654
else:

pandas/compat/__init__.py

-64
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
Cross-compatible functions for Python 2 and 3.
66
77
Key items to import for 2/3 compatible code:
8-
* iterators: reduce()
98
* lists: lrange(), lmap(), lzip(), lfilter()
109
* iterable method compatibility: iteritems, iterkeys, itervalues
1110
* Uses the original method if available, otherwise uses items, keys, values.
@@ -100,15 +99,6 @@ def signature(f):
10099
'varargs', 'keywords'])
101100
return argspec(args, defaults, varargs, keywords)
102101

103-
def get_range_parameters(data):
104-
"""Gets the start, stop, and step parameters from a range object"""
105-
return data.start, data.stop, data.step
106-
107-
# have to explicitly put builtins into the namespace
108-
intern = sys.intern
109-
reduce = functools.reduce
110-
unichr = chr
111-
112102
# list-producing versions of the major Python iterating functions
113103
def lrange(*args, **kwargs):
114104
return list(range(*args, **kwargs))
@@ -122,8 +112,6 @@ def lmap(*args, **kwargs):
122112
def lfilter(*args, **kwargs):
123113
return list(filter(*args, **kwargs))
124114

125-
from importlib import reload
126-
reload = reload
127115
Hashable = collections.abc.Hashable
128116
Iterable = collections.abc.Iterable
129117
Iterator = collections.abc.Iterator
@@ -149,37 +137,12 @@ def bytes_to_str(b, encoding='ascii'):
149137
def signature(f):
150138
return inspect.getargspec(f)
151139

152-
def get_range_parameters(data):
153-
"""Gets the start, stop, and step parameters from a range object"""
154-
# seems we only have indexing ops to infer
155-
# rather than direct accessors
156-
if len(data) > 1:
157-
step = data[1] - data[0]
158-
stop = data[-1] + step
159-
start = data[0]
160-
elif len(data):
161-
start = data[0]
162-
stop = data[0] + 1
163-
step = 1
164-
else:
165-
start = stop = 0
166-
step = 1
167-
168-
return start, stop, step
169-
170-
# import iterator versions of these functions
171-
intern = intern
172-
reduce = reduce
173-
unichr = unichr
174-
175140
# Python 2-builtin ranges produce lists
176141
lrange = builtins.range
177142
lzip = builtins.zip
178143
lmap = builtins.map
179144
lfilter = builtins.filter
180145

181-
reload = builtins.reload
182-
183146
Hashable = collections.Hashable
184147
Iterable = collections.Iterable
185148
Iterator = collections.Iterator
@@ -247,7 +210,6 @@ class to receive bound method
247210

248211
if PY3:
249212
string_types = str,
250-
class_types = type,
251213
text_type = str
252214
binary_type = bytes
253215

@@ -274,11 +236,6 @@ def east_asian_len(data, encoding=None, ambiguous_width=1):
274236
else:
275237
return len(data)
276238

277-
def import_lzma():
278-
""" import lzma from the std library """
279-
import lzma
280-
return lzma
281-
282239
def set_function_name(f, name, cls):
283240
""" Bind the name/qualname attributes of the function """
284241
f.__name__ = name
@@ -289,7 +246,6 @@ def set_function_name(f, name, cls):
289246
return f
290247
else:
291248
string_types = basestring,
292-
class_types = (type, types.ClassType)
293249
text_type = unicode
294250
binary_type = str
295251

@@ -321,12 +277,6 @@ def east_asian_len(data, encoding=None, ambiguous_width=1):
321277
else:
322278
return len(data)
323279

324-
def import_lzma():
325-
""" import the backported lzma library
326-
or raise ImportError if not available """
327-
from backports import lzma
328-
return lzma
329-
330280
def set_function_name(f, name, cls):
331281
""" Bind the name attributes of the function """
332282
f.__name__ = name
@@ -335,20 +285,6 @@ def set_function_name(f, name, cls):
335285
string_and_binary_types = string_types + (binary_type,)
336286

337287

338-
if PY2:
339-
# In PY2 functools.wraps doesn't provide metadata pytest needs to generate
340-
# decorated tests using parametrization. See pytest GH issue #2782
341-
def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS,
342-
updated=functools.WRAPPER_UPDATES):
343-
def wrapper(f):
344-
f = functools.wraps(wrapped, assigned, updated)(f)
345-
f.__wrapped__ = wrapped
346-
return f
347-
return wrapper
348-
else:
349-
wraps = functools.wraps
350-
351-
352288
def add_metaclass(metaclass):
353289
"""Class decorator for creating a class with a metaclass."""
354290
def wrapper(cls):

pandas/conftest.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -218,17 +218,15 @@ def all_compare_operators(request):
218218
return request.param
219219

220220

221-
@pytest.fixture(params=[None, 'gzip', 'bz2', 'zip',
222-
pytest.param('xz', marks=td.skip_if_no_lzma)])
221+
@pytest.fixture(params=[None, 'gzip', 'bz2', 'zip', 'xz'])
223222
def compression(request):
224223
"""
225224
Fixture for trying common compression types in compression tests
226225
"""
227226
return request.param
228227

229228

230-
@pytest.fixture(params=['gzip', 'bz2', 'zip',
231-
pytest.param('xz', marks=td.skip_if_no_lzma)])
229+
@pytest.fixture(params=['gzip', 'bz2', 'zip', 'xz'])
232230
def compression_only(request):
233231
"""
234232
Fixture for trying common compression types in compression tests excluding

pandas/core/computation/common.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1+
from functools import reduce
2+
13
import numpy as np
24

3-
from pandas.compat import reduce, string_types
5+
from pandas.compat import string_types
46

57
import pandas as pd
68

pandas/core/computation/expr.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,14 @@
22
"""
33

44
import ast
5-
from functools import partial
5+
from functools import partial, reduce
66
import itertools as it
77
import operator
88
import tokenize
99

1010
import numpy as np
1111

12-
from pandas.compat import StringIO, lmap, reduce, string_types
12+
from pandas.compat import StringIO, lmap, string_types
1313

1414
import pandas as pd
1515
from pandas import compat

pandas/core/indexes/range.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
from pandas._libs import index as libindex, lib
99
import pandas.compat as compat
10-
from pandas.compat import get_range_parameters, lrange
10+
from pandas.compat import lrange
1111
from pandas.compat.numpy import function as nv
1212
from pandas.util._decorators import Appender, cache_readonly
1313

@@ -132,7 +132,7 @@ def from_range(cls, data, name=None, dtype=None, **kwargs):
132132
'{0}(...) must be called with object coercible to a '
133133
'range, {1} was passed'.format(cls.__name__, repr(data)))
134134

135-
start, stop, step = get_range_parameters(data)
135+
start, stop, step = data.start, data.stop, data.step
136136
return RangeIndex(start, stop, step, dtype=dtype, name=name, **kwargs)
137137

138138
@classmethod

pandas/core/internals/construction.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,7 @@
1010
from pandas._libs import lib
1111
from pandas._libs.tslibs import IncompatibleFrequency
1212
import pandas.compat as compat
13-
from pandas.compat import (
14-
get_range_parameters, lmap, lrange, raise_with_traceback)
13+
from pandas.compat import lmap, lrange, raise_with_traceback
1514

1615
from pandas.core.dtypes.cast import (
1716
construct_1d_arraylike_from_scalar, construct_1d_ndarray_preserving_na,
@@ -612,8 +611,7 @@ def sanitize_array(data, index, dtype=None, copy=False,
612611

613612
elif isinstance(data, range):
614613
# GH#16804
615-
start, stop, step = get_range_parameters(data)
616-
arr = np.arange(start, stop, step, dtype='int64')
614+
arr = np.arange(data.start, data.stop, data.step, dtype='int64')
617615
subarr = _try_cast(arr, False, dtype, copy, raise_cast_failure)
618616
else:
619617
subarr = _try_cast(data, False, dtype, copy, raise_cast_failure)

pandas/io/common.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
"""Common IO api utilities"""
22

3+
import bz2
34
import codecs
45
from contextlib import closing, contextmanager
56
import csv
7+
import gzip
8+
import lzma
69
import mmap
710
import os
811
import zipfile
@@ -364,15 +367,13 @@ def _get_handle(path_or_buf, mode, encoding=None, compression=None,
364367

365368
# GZ Compression
366369
if compression == 'gzip':
367-
import gzip
368370
if is_path:
369371
f = gzip.open(path_or_buf, mode)
370372
else:
371373
f = gzip.GzipFile(fileobj=path_or_buf)
372374

373375
# BZ Compression
374376
elif compression == 'bz2':
375-
import bz2
376377
if is_path:
377378
f = bz2.BZ2File(path_or_buf, mode)
378379
elif compat.PY2:
@@ -404,7 +405,6 @@ def _get_handle(path_or_buf, mode, encoding=None, compression=None,
404405

405406
# XZ Compression
406407
elif compression == 'xz':
407-
lzma = compat.import_lzma()
408408
f = lzma.LZMAFile(path_or_buf, mode)
409409

410410
# Unrecognized Compression

pandas/io/formats/excel.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
11
"""Utilities for conversion to writer-agnostic Excel representation
22
"""
33

4+
from functools import reduce
45
import itertools
56
import re
67
import warnings
78

89
import numpy as np
910

10-
from pandas.compat import reduce
11-
1211
from pandas.core.dtypes import missing
1312
from pandas.core.dtypes.common import is_float, is_scalar
1413
from pandas.core.dtypes.generic import ABCMultiIndex, ABCPeriodIndex

pandas/io/formats/html.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,11 @@
88

99
from pandas._config import get_option
1010

11-
from pandas.compat import lzip, unichr
11+
from pandas.compat import lzip
1212

1313
from pandas.core.dtypes.generic import ABCMultiIndex
1414

15-
from pandas import compat, option_context
15+
from pandas import option_context
1616

1717
from pandas.io.common import _is_url
1818
from pandas.io.formats.format import TableFormatter, get_level_lengths
@@ -145,7 +145,7 @@ def render(self):
145145
self._write_table()
146146

147147
if self.should_show_dimensions:
148-
by = chr(215) if compat.PY3 else unichr(215) # ×
148+
by = chr(215)
149149
self.write('<p>{rows} rows {by} {cols} columns</p>'
150150
.format(rows=len(self.frame),
151151
by=by,

pandas/tests/computation/test_eval.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from distutils.version import LooseVersion
2+
from functools import reduce
23
from itertools import product
34
import operator
45
import warnings
@@ -7,7 +8,6 @@
78
from numpy.random import rand, randint, randn
89
import pytest
910

10-
from pandas.compat import reduce
1111
from pandas.errors import PerformanceWarning
1212
import pandas.util._test_decorators as td
1313

pandas/tests/io/parser/test_network.py

+2-6
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,8 @@
1919

2020

2121
@pytest.mark.network
22-
@pytest.mark.parametrize(
23-
"compress_type, extension", [
24-
('gzip', '.gz'), ('bz2', '.bz2'), ('zip', '.zip'),
25-
pytest.param('xz', '.xz', marks=td.skip_if_no_lzma)
26-
]
27-
)
22+
@pytest.mark.parametrize("compress_type, extension", [
23+
('gzip', '.gz'), ('bz2', '.bz2'), ('zip', '.zip'), ('xz', '.xz')])
2824
@pytest.mark.parametrize('mode', ['explicit', 'infer'])
2925
@pytest.mark.parametrize('engine', ['python', 'c'])
3026
def test_compressed_urls(salaries_table, compress_type, extension, mode,

pandas/tests/io/test_html.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from functools import partial
2+
from importlib import reload
23
import os
34
import re
45
import threading
@@ -7,7 +8,7 @@
78
from numpy.random import rand
89
import pytest
910

10-
from pandas.compat import BytesIO, StringIO, is_platform_windows, reload
11+
from pandas.compat import BytesIO, StringIO, is_platform_windows
1112
from pandas.errors import ParserError
1213
import pandas.util._test_decorators as td
1314

0 commit comments

Comments
 (0)