Skip to content

Commit

Permalink
CLN: Misc Python 2 references (#26085)
Browse files Browse the repository at this point in the history
  • Loading branch information
mroeschke authored and jreback committed Apr 15, 2019
1 parent d9c9e2f commit 81f5c01
Show file tree
Hide file tree
Showing 23 changed files with 24 additions and 129 deletions.
21 changes: 0 additions & 21 deletions LICENSES/SIX

This file was deleted.

5 changes: 1 addition & 4 deletions pandas/_libs/tslibs/period.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -2224,10 +2224,7 @@ cdef class _Period(object):

def __unicode__(self):
"""
Return a string representation for a particular DataFrame
Invoked by unicode(df) in py2 only. Yields a Unicode String in both
py2/py3.
Return a unicode string representation for a particular DataFrame
"""
base, mult = get_freq_code(self.freq)
formatted = period_format(self.ordinal, base)
Expand Down
14 changes: 1 addition & 13 deletions pandas/_libs/tslibs/strptime.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,7 @@ import calendar
import re
from datetime import date as datetime_date


# Python 2 vs Python 3
try:
from thread import allocate_lock as _thread_allocate_lock
except:
try:
from _thread import allocate_lock as _thread_allocate_lock
except:
try:
from dummy_thread import allocate_lock as _thread_allocate_lock
except:
from _dummy_thread import allocate_lock as _thread_allocate_lock

from _thread import allocate_lock as _thread_allocate_lock

import pytz

Expand Down
7 changes: 1 addition & 6 deletions pandas/core/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -699,12 +699,7 @@ def item(self):
"""
Return the first element of the underlying data as a python scalar.
"""
try:
return self.values.item()
except IndexError:
# copy numpy's message here because Py26 raises an IndexError
raise ValueError('can only convert an array of size 1 to a '
'Python scalar')
return self.values.item()

@property
def data(self):
Expand Down
1 change: 0 additions & 1 deletion pandas/core/dtypes/cast.py
Original file line number Diff line number Diff line change
Expand Up @@ -636,7 +636,6 @@ def astype_nansafe(arr, dtype, copy=True, skipna=False):
dtype = pandas_dtype(dtype)

if issubclass(dtype.type, str):
# in Py3 that's str, in Py2 that's unicode
return lib.astype_unicode(arr.ravel(),
skipna=skipna).reshape(arr.shape)

Expand Down
17 changes: 4 additions & 13 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -612,10 +612,7 @@ def _info_repr(self):

def __unicode__(self):
"""
Return a string representation for a particular DataFrame.
Invoked by unicode(df) in py2 only. Yields a Unicode String in both
py2/py3.
Return a unicode string representation for a particular DataFrame.
"""
buf = StringIO("")
if self._info_repr():
Expand Down Expand Up @@ -901,16 +898,10 @@ def itertuples(self, index=True, name="Pandas"):
# use integer indexing because of possible duplicate column names
arrays.extend(self.iloc[:, k] for k in range(len(self.columns)))

# Python 3 supports at most 255 arguments to constructor, and
# things get slow with this many fields in Python 2
# Python 3 supports at most 255 arguments to constructor
if name is not None and len(self.columns) + index < 256:
# `rename` is unsupported in Python 2.6
try:
itertuple = collections.namedtuple(name, fields, rename=True)
return map(itertuple._make, zip(*arrays))

except Exception:
pass
itertuple = collections.namedtuple(name, fields, rename=True)
return map(itertuple._make, zip(*arrays))

# fallback to regular tuples
return zip(*arrays)
Expand Down
11 changes: 4 additions & 7 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -2579,11 +2579,8 @@ def to_pickle(self, path, compression='infer',
protocol : int
Int which indicates which protocol should be used by the pickler,
default HIGHEST_PROTOCOL (see [1]_ paragraph 12.1.2). The possible
values for this parameter depend on the version of Python. For
Python 2.x, possible values are 0, 1, 2. For Python>=3.0, 3 is a
valid value. For Python >= 3.4, 4 is a valid value. A negative
value for the protocol parameter is equivalent to setting its value
to HIGHEST_PROTOCOL.
values are 0, 1, 2, 3, 4. A negative value for the protocol
parameter is equivalent to setting its value to HIGHEST_PROTOCOL.
.. [1] https://docs.python.org/3/library/pickle.html
.. versionadded:: 0.21.0
Expand Down Expand Up @@ -2836,7 +2833,7 @@ def to_latex(self, buf=None, columns=None, col_space=None, header=True,
characters in column names.
encoding : str, optional
A string representing the encoding to use in the output file,
defaults to 'ascii' on Python 2 and 'utf-8' on Python 3.
defaults to 'utf-8'.
decimal : str, default '.'
Character recognized as decimal separator, e.g. ',' in Europe.
Expand Down Expand Up @@ -2965,7 +2962,7 @@ def to_csv(self, path_or_buf=None, sep=",", na_rep='', float_format=None,
Python write mode, default 'w'.
encoding : str, optional
A string representing the encoding to use in the output file,
defaults to 'ascii' on Python 2 and 'utf-8' on Python 3.
defaults to 'utf-8'.
compression : str, default 'infer'
Compression mode among the following possible values: {'infer',
'gzip', 'bz2', 'zip', 'xz', None}. If 'infer' and `path_or_buf`
Expand Down
5 changes: 1 addition & 4 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -920,10 +920,7 @@ def __deepcopy__(self, memo=None):

def __unicode__(self):
"""
Return a string representation for this object.
Invoked by unicode(df) in py2 only. Yields a Unicode String in both
py2/py3.
Return a unicode string representation for this object.
"""
klass = self.__class__.__name__
data = self._format_data()
Expand Down
5 changes: 1 addition & 4 deletions pandas/core/indexes/frozen.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,10 +151,7 @@ def values(self):

def __unicode__(self):
"""
Return a string representation for this object.
Invoked by unicode(df) in py2 only. Yields a Unicode String in both
py2/py3.
Return a unicode string representation for this object.
"""
prepr = pprint_thing(self, escape_chars=('\t', '\r', '\n'),
quote_strings=True)
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/indexes/range.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ def ensure_int(value, field):

@classmethod
def from_range(cls, data, name=None, dtype=None, **kwargs):
""" Create RangeIndex from a range (py3), or xrange (py2) object. """
""" Create RangeIndex from a range object. """
if not isinstance(data, range):
raise TypeError(
'{0}(...) must be called with object coercible to a '
Expand Down
5 changes: 1 addition & 4 deletions pandas/core/panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -344,10 +344,7 @@ def _compare_constructor(self, other, func):

def __unicode__(self):
"""
Return a string representation for a particular Panel.
Invoked by unicode(df) in py2 only.
Yields a Unicode String in both py2/py3.
Return a unicode string representation for a particular Panel.
"""

class_name = str(self.__class__)
Expand Down
5 changes: 1 addition & 4 deletions pandas/core/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -1369,10 +1369,7 @@ def reset_index(self, level=None, drop=False, name=None, inplace=False):

def __unicode__(self):
"""
Return a string representation for a particular DataFrame.
Invoked by unicode(df) in py2 only. Yields a Unicode String in both
py2/py3.
Return a unicode string representation for a particular DataFrame.
"""
buf = StringIO("")
width, height = get_terminal_size()
Expand Down
6 changes: 1 addition & 5 deletions pandas/io/clipboard/clipboards.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,7 @@ def copy_gtk(text):

def paste_gtk():
clipboardContents = gtk.Clipboard().wait_for_text()
# for python 2, returns None if the clipboard is blank.
if clipboardContents is None:
return ''
else:
return clipboardContents
return clipboardContents

return copy_gtk, paste_gtk

Expand Down
2 changes: 1 addition & 1 deletion pandas/io/formats/printing.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ def pprint_thing(thing, _nest_lvl=0, escape_chars=None, default_escapes=False,
Returns
-------
result - unicode object on py2, str on py3. Always Unicode.
result - unicode str
"""

Expand Down
6 changes: 0 additions & 6 deletions pandas/io/parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1326,12 +1326,6 @@ def _validate_usecols_arg(usecols):

usecols = set(usecols)

if usecols_dtype == "unicode":
# see gh-13253
#
# Python 2.x compatibility
usecols = {col.encode("utf-8") for col in usecols}

return usecols, usecols_dtype
return usecols, None

Expand Down
7 changes: 1 addition & 6 deletions pandas/tests/extension/json/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,7 @@
class JSONDtype(ExtensionDtype):
type = abc.Mapping
name = 'json'

try:
na_value = UserDict()
except AttributeError:
# source compatibility with Py2.
na_value = {}
na_value = UserDict()

@classmethod
def construct_array_type(cls):
Expand Down
5 changes: 1 addition & 4 deletions pandas/tests/extension/test_integer.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,10 +113,7 @@ def _check_op(self, s, op, other, op_name, exc=NotImplementedError):
result = op(s, other)
expected = s.combine(other, op)

if op_name == '__rdiv__':
# combine is not giving the correct result for this case
pytest.skip("skipping reverse div in python 2")
elif op_name in ('__rtruediv__', '__truediv__', '__div__'):
if op_name in ('__rtruediv__', '__truediv__', '__div__'):
expected = expected.astype(float)
if op_name == '__rtruediv__':
# TODO reverse operators result in object dtype
Expand Down
7 changes: 1 addition & 6 deletions pandas/tests/indexes/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import math
import operator
import re
import sys

import numpy as np
import pytest
Expand Down Expand Up @@ -414,9 +413,6 @@ def test_constructor_dtypes_datetime(self, tz_naive_fixture, attr, utc,
index = index.tz_localize(tz_naive_fixture)
dtype = index.dtype

# TODO(GH-24559): Remove the sys.modules and warnings
# not sure what this is from. It's Py2 only.
modules = [sys.modules['pandas.core.indexes.base']]
if (tz_naive_fixture and attr == "asi8" and
str(tz_naive_fixture) not in ('UTC', 'tzutc()', 'UTC+00:00')):
ex_warn = FutureWarning
Expand All @@ -425,8 +421,7 @@ def test_constructor_dtypes_datetime(self, tz_naive_fixture, attr, utc,

# stacklevel is checked elsewhere. We don't do it here since
# Index will have an frame, throwing off the expected.
with tm.assert_produces_warning(ex_warn, check_stacklevel=False,
clear=modules):
with tm.assert_produces_warning(ex_warn, check_stacklevel=False):
result = klass(arg, tz=tz_naive_fixture)
tm.assert_index_equal(result, index)

Expand Down
3 changes: 1 addition & 2 deletions pandas/tests/io/formats/test_to_csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,7 @@ def test_to_csv_defualt_encoding(self):
df = DataFrame({'col': ["AAAAA", "ÄÄÄÄÄ", "ßßßßß", "聞聞聞聞聞"]})

with tm.ensure_clean('test.csv') as path:
# the default to_csv encoding in Python 2 is ascii, and that in
# Python 3 is uft-8.
# the default to_csv encoding is uft-8.
df.to_csv(path)
tm.assert_frame_equal(pd.read_csv(path, index_col=0), df)

Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/io/parser/test_c_parser_only.py
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,7 @@ def test_read_nrows_large(c_parser_only):


def test_float_precision_round_trip_with_text(c_parser_only):
# see gh-15140 - This should not segfault on Python 2.7+
# see gh-15140
parser = c_parser_only
df = parser.read_csv(StringIO("a"), header=None,
float_precision="round_trip")
Expand Down
5 changes: 0 additions & 5 deletions pandas/tests/io/test_compression.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,6 @@ def test_series_compression_defaults_to_infer(
def test_compression_warning(compression_only):
# Assert that passing a file object to to_csv while explicitly specifying a
# compression protocol triggers a RuntimeWarning, as per GH21227.
# Note that pytest has an issue that causes assert_produces_warning to fail
# in Python 2 if the warning has occurred in previous tests
# (see https://git.io/fNEBm & https://git.io/fNEBC). Hence, should this
# test fail in just Python 2 builds, it likely indicates that other tests
# are producing RuntimeWarnings, thereby triggering the pytest bug.
df = pd.DataFrame(100 * [[0.123456, 0.234567, 0.567567],
[12.32112, 123123.2, 321321.2]],
columns=['X', 'Y', 'Z'])
Expand Down
10 changes: 1 addition & 9 deletions pandas/tests/io/test_pickle.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,15 +65,7 @@ def compare_element(result, expected, typ, version=None):

def compare(data, vf, version):

# py3 compat when reading py2 pickle
try:
data = pd.read_pickle(vf)
except (ValueError) as e:
if 'unsupported pickle protocol:' in str(e):
# trying to read a py3 pickle in py2
return
else:
raise
data = pd.read_pickle(vf)

m = globals()
for typ, dv in data.items():
Expand Down
2 changes: 0 additions & 2 deletions scripts/merge-pr.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@
import sys
import textwrap

from six.moves import input

PANDAS_HOME = '.'
PROJECT_NAME = 'pandas'
print("PANDAS_HOME = " + PANDAS_HOME)
Expand Down

0 comments on commit 81f5c01

Please sign in to comment.