Skip to content

Commit 0f5a7e3

Browse files
jschendeljreback
authored andcommitted
CLN: Remove u and u_safe from pandas.compat (#25852)
1 parent 6e0f9a9 commit 0f5a7e3

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

60 files changed

+352
-665
lines changed

pandas/compat/__init__.py

-16
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
Key items to import for 2/3 compatible code:
88
* iterators: reduce()
99
* lists: lrange(), lmap(), lzip(), lfilter()
10-
* unicode: u() [no unicode builtin in Python 3]
1110
* longs: long (int in Python 3)
1211
* iterable method compatibility: iteritems, iterkeys, itervalues
1312
* Uses the original method if available, otherwise uses items, keys, values.
@@ -256,12 +255,6 @@ class to receive bound method
256255
text_type = str
257256
binary_type = bytes
258257

259-
def u(s):
260-
return s
261-
262-
def u_safe(s):
263-
return s
264-
265258
def to_str(s):
266259
"""
267260
Convert bytes and non-string into Python 3 str
@@ -305,15 +298,6 @@ def set_function_name(f, name, cls):
305298
text_type = unicode
306299
binary_type = str
307300

308-
def u(s):
309-
return unicode(s, "unicode_escape")
310-
311-
def u_safe(s):
312-
try:
313-
return unicode(s, "unicode_escape")
314-
except:
315-
return s
316-
317301
def to_str(s):
318302
"""
319303
Convert unicode and non-string into Python 2 str

pandas/compat/pickle_compat.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import pickle as pkl
77
import sys
88

9-
from pandas.compat import string_types, u # noqa
9+
from pandas.compat import string_types # noqa
1010

1111
import pandas # noqa
1212
from pandas import Index, compat

pandas/conftest.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import pytest
1010
from pytz import FixedOffset, utc
1111

12-
from pandas.compat import PY3, u
12+
from pandas.compat import PY3
1313
import pandas.util._test_decorators as td
1414

1515
import pandas as pd
@@ -561,7 +561,7 @@ def any_numpy_dtype(request):
561561
# categoricals are handled separately
562562
_any_skipna_inferred_dtype = [
563563
('string', ['a', np.nan, 'c']),
564-
('unicode' if not PY3 else 'string', [u('a'), np.nan, u('c')]),
564+
('unicode' if not PY3 else 'string', ['a', np.nan, 'c']),
565565
('bytes' if PY3 else 'string', [b'a', np.nan, b'c']),
566566
('empty', [np.nan, np.nan, np.nan]),
567567
('empty', []),

pandas/core/arrays/categorical.py

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

88
from pandas._libs import algos as libalgos, lib
99
import pandas.compat as compat
10-
from pandas.compat import lzip, u
10+
from pandas.compat import lzip
1111
from pandas.compat.numpy import function as nv
1212
from pandas.util._decorators import (
1313
Appender, Substitution, cache_readonly, deprecate_kwarg)
@@ -1947,10 +1947,10 @@ def _tidy_repr(self, max_vals=10, footer=True):
19471947
head = self[:num]._get_repr(length=False, footer=False)
19481948
tail = self[-(max_vals - num):]._get_repr(length=False, footer=False)
19491949

1950-
result = u('{head}, ..., {tail}').format(head=head[:-1], tail=tail[1:])
1950+
result = '{head}, ..., {tail}'.format(head=head[:-1], tail=tail[1:])
19511951
if footer:
1952-
result = u('{result}\n{footer}').format(result=result,
1953-
footer=self._repr_footer())
1952+
result = '{result}\n{footer}'.format(
1953+
result=result, footer=self._repr_footer())
19541954

19551955
return compat.text_type(result)
19561956

@@ -2008,7 +2008,7 @@ def _repr_categories_info(self):
20082008

20092009
def _repr_footer(self):
20102010

2011-
return u('Length: {length}\n{info}').format(
2011+
return 'Length: {length}\n{info}'.format(
20122012
length=len(self), info=self._repr_categories_info())
20132013

20142014
def _get_repr(self, length=True, na_rep='NaN', footer=True):

pandas/core/computation/pytables.py

+12-12
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import numpy as np
77

88
from pandas._libs.tslibs import Timedelta, Timestamp
9-
from pandas.compat import DeepChainMap, string_types, u
9+
from pandas.compat import DeepChainMap, string_types
1010

1111
from pandas.core.dtypes.common import is_list_like
1212

@@ -182,43 +182,43 @@ def stringify(value):
182182

183183
kind = _ensure_decoded(self.kind)
184184
meta = _ensure_decoded(self.meta)
185-
if kind == u('datetime64') or kind == u('datetime'):
185+
if kind == 'datetime64' or kind == 'datetime':
186186
if isinstance(v, (int, float)):
187187
v = stringify(v)
188188
v = _ensure_decoded(v)
189189
v = Timestamp(v)
190190
if v.tz is not None:
191191
v = v.tz_convert('UTC')
192192
return TermValue(v, v.value, kind)
193-
elif kind == u('timedelta64') or kind == u('timedelta'):
193+
elif kind == 'timedelta64' or kind == 'timedelta':
194194
v = Timedelta(v, unit='s').value
195195
return TermValue(int(v), v, kind)
196-
elif meta == u('category'):
196+
elif meta == 'category':
197197
metadata = com.values_from_object(self.metadata)
198198
result = metadata.searchsorted(v, side='left')
199199

200200
# result returns 0 if v is first element or if v is not in metadata
201201
# check that metadata contains v
202202
if not result and v not in metadata:
203203
result = -1
204-
return TermValue(result, result, u('integer'))
205-
elif kind == u('integer'):
204+
return TermValue(result, result, 'integer')
205+
elif kind == 'integer':
206206
v = int(float(v))
207207
return TermValue(v, v, kind)
208-
elif kind == u('float'):
208+
elif kind == 'float':
209209
v = float(v)
210210
return TermValue(v, v, kind)
211-
elif kind == u('bool'):
211+
elif kind == 'bool':
212212
if isinstance(v, string_types):
213-
v = not v.strip().lower() in [u('false'), u('f'), u('no'),
214-
u('n'), u('none'), u('0'),
215-
u('[]'), u('{}'), u('')]
213+
v = not v.strip().lower() in ['false', 'f', 'no',
214+
'n', 'none', '0',
215+
'[]', '{}', '']
216216
else:
217217
v = bool(v)
218218
return TermValue(v, v, kind)
219219
elif isinstance(v, string_types):
220220
# string quoting
221-
return TermValue(v, stringify(v), u('string'))
221+
return TermValue(v, stringify(v), 'string')
222222
else:
223223
raise TypeError("Cannot compare {v} of type {typ} to {kind} column"
224224
.format(v=v, typ=type(v), kind=kind))

pandas/core/frame.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
from pandas import compat
3636
from pandas.compat import (
3737
PY36, Iterator, StringIO, lmap, lzip, raise_with_traceback,
38-
string_and_binary_types, u)
38+
string_and_binary_types)
3939
from pandas.compat.numpy import function as nv
4040
from pandas.core.dtypes.cast import (
4141
maybe_upcast,
@@ -620,7 +620,7 @@ def __unicode__(self):
620620
Invoked by unicode(df) in py2 only. Yields a Unicode String in both
621621
py2/py3.
622622
"""
623-
buf = StringIO(u(""))
623+
buf = StringIO("")
624624
if self._info_repr():
625625
self.info(buf=buf)
626626
return buf.getvalue()
@@ -644,7 +644,7 @@ def _repr_html_(self):
644644
Mainly for IPython notebook.
645645
"""
646646
if self._info_repr():
647-
buf = StringIO(u(""))
647+
buf = StringIO("")
648648
self.info(buf=buf)
649649
# need to escape the <class>, should be the first line.
650650
val = buf.getvalue().replace('<', r'&lt;', 1)

pandas/core/indexes/base.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
from pandas._libs.tslibs import OutOfBoundsDatetime, Timedelta, Timestamp
1313
from pandas._libs.tslibs.timezones import tz_compare
1414
import pandas.compat as compat
15-
from pandas.compat import set_function_name, u
15+
from pandas.compat import set_function_name
1616
from pandas.compat.numpy import function as nv
1717
from pandas.util._decorators import Appender, Substitution, cache_readonly
1818

@@ -931,14 +931,14 @@ def __unicode__(self):
931931
attrs = self._format_attrs()
932932
space = self._format_space()
933933

934-
prepr = (u(",%s") %
935-
space).join(u("%s=%s") % (k, v) for k, v in attrs)
934+
prepr = (",%s" %
935+
space).join("%s=%s" % (k, v) for k, v in attrs)
936936

937937
# no data provided, just attributes
938938
if data is None:
939939
data = ''
940940

941-
res = u("%s(%s%s)") % (klass, data, prepr)
941+
res = "%s(%s%s)" % (klass, data, prepr)
942942

943943
return res
944944

pandas/core/panel.py

+6-7
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
import numpy as np
1111

1212
import pandas.compat as compat
13-
from pandas.compat import u
1413
from pandas.compat.numpy import function as nv
1514
from pandas.util._decorators import Appender, Substitution, deprecate_kwarg
1615
from pandas.util._validators import validate_axis_style_args
@@ -356,18 +355,18 @@ def __unicode__(self):
356355

357356
class_name = str(self.__class__)
358357

359-
dims = u('Dimensions: {dimensions}'.format(dimensions=' x '.join(
358+
dims = 'Dimensions: {dimensions}'.format(dimensions=' x '.join(
360359
["{shape} ({axis})".format(shape=shape, axis=axis) for axis, shape
361-
in zip(self._AXIS_ORDERS, self.shape)])))
360+
in zip(self._AXIS_ORDERS, self.shape)]))
362361

363362
def axis_pretty(a):
364363
v = getattr(self, a)
365364
if len(v) > 0:
366-
return u('{ax} axis: {x} to {y}'.format(ax=a.capitalize(),
367-
x=pprint_thing(v[0]),
368-
y=pprint_thing(v[-1])))
365+
return '{ax} axis: {x} to {y}'.format(ax=a.capitalize(),
366+
x=pprint_thing(v[0]),
367+
y=pprint_thing(v[-1]))
369368
else:
370-
return u('{ax} axis: None'.format(ax=a.capitalize()))
369+
return '{ax} axis: None'.format(ax=a.capitalize())
371370

372371
output = '\n'.join(
373372
[class_name, dims] + [axis_pretty(a) for a in self._AXIS_ORDERS])

pandas/core/reshape/reshape.py

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

88
from pandas._libs import algos as _algos, reshape as _reshape
99
from pandas._libs.sparse import IntIndex
10-
from pandas.compat import PY2, text_type, u
10+
from pandas.compat import PY2, text_type
1111

1212
from pandas.core.dtypes.cast import maybe_promote
1313
from pandas.core.dtypes.common import (
@@ -914,7 +914,7 @@ def _make_col_name(prefix, prefix_sep, level):
914914
if PY2 and (isinstance(prefix, text_type) or
915915
isinstance(prefix_sep, text_type) or
916916
isinstance(level, text_type)):
917-
fstr = u(fstr)
917+
fstr = fstr
918918
return fstr.format(prefix=prefix,
919919
prefix_sep=prefix_sep,
920920
level=level)

pandas/core/series.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
from pandas._libs import iNaT, index as libindex, lib, tslibs
1313
import pandas.compat as compat
14-
from pandas.compat import PY36, StringIO, u
14+
from pandas.compat import PY36, StringIO
1515
from pandas.compat.numpy import function as nv
1616
from pandas.util._decorators import Appender, Substitution, deprecate
1717
from pandas.util._validators import validate_bool_kwarg
@@ -1379,7 +1379,7 @@ def __unicode__(self):
13791379
Invoked by unicode(df) in py2 only. Yields a Unicode String in both
13801380
py2/py3.
13811381
"""
1382-
buf = StringIO(u(""))
1382+
buf = StringIO("")
13831383
width, height = get_terminal_size()
13841384
max_rows = (height if get_option("display.max_rows") == 0 else
13851385
get_option("display.max_rows"))

pandas/core/strings.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -2833,7 +2833,7 @@ def normalize(self, form):
28332833
normalized : Series/Index of objects
28342834
"""
28352835
import unicodedata
2836-
f = lambda x: unicodedata.normalize(form, compat.u_safe(x))
2836+
f = lambda x: unicodedata.normalize(form, x)
28372837
result = _na_map(f, self._parent)
28382838
return self._wrap_result(result)
28392839

@@ -3187,10 +3187,10 @@ def rindex(self, sub, start=0, end=None):
31873187
istitle = _noarg_wrapper(lambda x: x.istitle(),
31883188
docstring=_shared_docs['ismethods'] %
31893189
_shared_docs['istitle'])
3190-
isnumeric = _noarg_wrapper(lambda x: compat.u_safe(x).isnumeric(),
3190+
isnumeric = _noarg_wrapper(lambda x: x.isnumeric(),
31913191
docstring=_shared_docs['ismethods'] %
31923192
_shared_docs['isnumeric'])
3193-
isdecimal = _noarg_wrapper(lambda x: compat.u_safe(x).isdecimal(),
3193+
isdecimal = _noarg_wrapper(lambda x: x.isdecimal(),
31943194
docstring=_shared_docs['ismethods'] %
31953195
_shared_docs['isdecimal'])
31963196

pandas/io/excel/_base.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import warnings
77

88
import pandas.compat as compat
9-
from pandas.compat import add_metaclass, string_types, u
9+
from pandas.compat import add_metaclass, string_types
1010
from pandas.errors import EmptyDataError
1111
from pandas.util._decorators import Appender, deprecate_kwarg
1212

@@ -715,7 +715,7 @@ def check_extension(cls, ext):
715715
if ext.startswith('.'):
716716
ext = ext[1:]
717717
if not any(ext in extension for extension in cls.supported_extensions):
718-
msg = (u("Invalid extension for engine '{engine}': '{ext}'")
718+
msg = ("Invalid extension for engine '{engine}': '{ext}'"
719719
.format(engine=pprint_thing(cls.engine),
720720
ext=pprint_thing(ext)))
721721
raise ValueError(msg)

0 commit comments

Comments
 (0)