Skip to content

Commit 96a5274

Browse files
authored
TST: clean up some tests issues & style (pandas-dev#18232)
* STYLE: clean up flake8 exceptions * TST: skip if no bs4 for some html tests * TST: fix local timezone checking with .timestamp()
1 parent 85e6864 commit 96a5274

File tree

8 files changed

+51
-38
lines changed

8 files changed

+51
-38
lines changed

pandas/core/dtypes/cast.py

+17-17
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ def trans(x): # noqa
136136
try:
137137
if np.allclose(new_result, result, rtol=0):
138138
return new_result
139-
except:
139+
except Exception:
140140

141141
# comparison of an object dtype with a number type could
142142
# hit here
@@ -151,14 +151,14 @@ def trans(x): # noqa
151151
elif dtype.kind in ['M', 'm'] and result.dtype.kind in ['i', 'f']:
152152
try:
153153
result = result.astype(dtype)
154-
except:
154+
except Exception:
155155
if dtype.tz:
156156
# convert to datetime and change timezone
157157
from pandas import to_datetime
158158
result = to_datetime(result).tz_localize('utc')
159159
result = result.tz_convert(dtype.tz)
160160

161-
except:
161+
except Exception:
162162
pass
163163

164164
return result
@@ -210,7 +210,7 @@ def changeit():
210210
new_result[mask] = om_at
211211
result[:] = new_result
212212
return result, False
213-
except:
213+
except Exception:
214214
pass
215215

216216
# we are forced to change the dtype of the result as the input
@@ -243,7 +243,7 @@ def changeit():
243243

244244
try:
245245
np.place(result, mask, other)
246-
except:
246+
except Exception:
247247
return changeit()
248248

249249
return result, False
@@ -274,14 +274,14 @@ def maybe_promote(dtype, fill_value=np.nan):
274274
if issubclass(dtype.type, np.datetime64):
275275
try:
276276
fill_value = tslib.Timestamp(fill_value).value
277-
except:
277+
except Exception:
278278
# the proper thing to do here would probably be to upcast
279279
# to object (but numpy 1.6.1 doesn't do this properly)
280280
fill_value = iNaT
281281
elif issubclass(dtype.type, np.timedelta64):
282282
try:
283283
fill_value = lib.Timedelta(fill_value).value
284-
except:
284+
except Exception:
285285
# as for datetimes, cannot upcast to object
286286
fill_value = iNaT
287287
else:
@@ -592,12 +592,12 @@ def maybe_convert_scalar(values):
592592

593593
def coerce_indexer_dtype(indexer, categories):
594594
""" coerce the indexer input array to the smallest dtype possible """
595-
l = len(categories)
596-
if l < _int8_max:
595+
length = len(categories)
596+
if length < _int8_max:
597597
return _ensure_int8(indexer)
598-
elif l < _int16_max:
598+
elif length < _int16_max:
599599
return _ensure_int16(indexer)
600-
elif l < _int32_max:
600+
elif length < _int32_max:
601601
return _ensure_int32(indexer)
602602
return _ensure_int64(indexer)
603603

@@ -629,7 +629,7 @@ def conv(r, dtype):
629629
r = float(r)
630630
elif dtype.kind == 'i':
631631
r = int(r)
632-
except:
632+
except Exception:
633633
pass
634634

635635
return r
@@ -756,7 +756,7 @@ def maybe_convert_objects(values, convert_dates=True, convert_numeric=True,
756756
if not isna(new_values).all():
757757
values = new_values
758758

759-
except:
759+
except Exception:
760760
pass
761761
else:
762762
# soft-conversion
@@ -817,7 +817,7 @@ def soft_convert_objects(values, datetime=True, numeric=True, timedelta=True,
817817
# If all NaNs, then do not-alter
818818
values = converted if not isna(converted).all() else values
819819
values = values.copy() if copy else values
820-
except:
820+
except Exception:
821821
pass
822822

823823
return values
@@ -888,10 +888,10 @@ def try_datetime(v):
888888
try:
889889
from pandas import to_datetime
890890
return to_datetime(v)
891-
except:
891+
except Exception:
892892
pass
893893

894-
except:
894+
except Exception:
895895
pass
896896

897897
return v.reshape(shape)
@@ -903,7 +903,7 @@ def try_timedelta(v):
903903
from pandas import to_timedelta
904904
try:
905905
return to_timedelta(v)._values.reshape(shape)
906-
except:
906+
except Exception:
907907
return v.reshape(shape)
908908

909909
inferred_type = lib.infer_datetimelike_array(_ensure_object(v))

pandas/core/indexes/base.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -2032,7 +2032,7 @@ def equals(self, other):
20322032
try:
20332033
return array_equivalent(_values_from_object(self),
20342034
_values_from_object(other))
2035-
except:
2035+
except Exception:
20362036
return False
20372037

20382038
def identical(self, other):
@@ -2315,7 +2315,7 @@ def intersection(self, other):
23152315
try:
23162316
indexer = Index(other._values).get_indexer(self._values)
23172317
indexer = indexer.take((indexer != -1).nonzero()[0])
2318-
except:
2318+
except Exception:
23192319
# duplicates
23202320
indexer = algos.unique1d(
23212321
Index(other._values).get_indexer_non_unique(self._values)[0])
@@ -3022,13 +3022,13 @@ def _reindex_non_unique(self, target):
30223022
new_indexer = None
30233023

30243024
if len(missing):
3025-
l = np.arange(len(indexer))
3025+
length = np.arange(len(indexer))
30263026

30273027
missing = _ensure_platform_int(missing)
30283028
missing_labels = target.take(missing)
3029-
missing_indexer = _ensure_int64(l[~check])
3029+
missing_indexer = _ensure_int64(length[~check])
30303030
cur_labels = self.take(indexer[check]).values
3031-
cur_indexer = _ensure_int64(l[check])
3031+
cur_indexer = _ensure_int64(length[check])
30323032

30333033
new_labels = np.empty(tuple([len(indexer)]), dtype=object)
30343034
new_labels[cur_indexer] = cur_labels

pandas/core/indexes/datetimes.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -449,7 +449,7 @@ def _generate(cls, start, end, periods, name, offset,
449449

450450
try:
451451
inferred_tz = timezones.infer_tzinfo(start, end)
452-
except:
452+
except Exception:
453453
raise TypeError('Start and end cannot both be tz-aware with '
454454
'different timezones')
455455

@@ -1176,12 +1176,12 @@ def __iter__(self):
11761176

11771177
# convert in chunks of 10k for efficiency
11781178
data = self.asi8
1179-
l = len(self)
1179+
length = len(self)
11801180
chunksize = 10000
1181-
chunks = int(l / chunksize) + 1
1181+
chunks = int(length / chunksize) + 1
11821182
for i in range(chunks):
11831183
start_i = i * chunksize
1184-
end_i = min((i + 1) * chunksize, l)
1184+
end_i = min((i + 1) * chunksize, length)
11851185
converted = libts.ints_to_pydatetime(data[start_i:end_i],
11861186
tz=self.tz, freq=self.freq,
11871187
box=True)

pandas/core/indexes/timedeltas.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -841,7 +841,7 @@ def insert(self, loc, item):
841841
if _is_convertible_to_td(item):
842842
try:
843843
item = Timedelta(item)
844-
except:
844+
except Exception:
845845
pass
846846

847847
freq = None

pandas/core/series.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -597,7 +597,7 @@ def _ixs(self, i, axis=0):
597597
return values[i]
598598
except IndexError:
599599
raise
600-
except:
600+
except Exception:
601601
if isinstance(i, slice):
602602
indexer = self.index._convert_slice_indexer(i, kind='iloc')
603603
return self._get_values(indexer)
@@ -675,7 +675,7 @@ def _get_with(self, key):
675675
if isinstance(key, tuple):
676676
try:
677677
return self._get_values_tuple(key)
678-
except:
678+
except Exception:
679679
if len(key) == 1:
680680
key = key[0]
681681
if isinstance(key, slice):
@@ -818,7 +818,7 @@ def _set_with(self, key, value):
818818
if not isinstance(key, (list, Series, np.ndarray, Series)):
819819
try:
820820
key = list(key)
821-
except:
821+
except Exception:
822822
key = [key]
823823

824824
if isinstance(key, Index):

pandas/tests/io/test_html.py

+2
Original file line numberDiff line numberDiff line change
@@ -973,6 +973,7 @@ def test_importcheck_thread_safety():
973973
def test_parse_failure_unseekable():
974974
# Issue #17975
975975
_skip_if_no('lxml')
976+
_skip_if_no('bs4')
976977

977978
class UnseekableStringIO(StringIO):
978979
def seekable(self):
@@ -996,6 +997,7 @@ def seekable(self):
996997
def test_parse_failure_rewinds():
997998
# Issue #17975
998999
_skip_if_no('lxml')
1000+
_skip_if_no('bs4')
9991001

10001002
class MockFile(object):
10011003
def __init__(self, data):

pandas/tests/scalar/test_timestamp.py

+8-3
Original file line numberDiff line numberDiff line change
@@ -1101,13 +1101,18 @@ def test_timestamp(self):
11011101

11021102
tsc = Timestamp('2014-10-11 11:00:01.12345678', tz='US/Central')
11031103
utsc = tsc.tz_convert('UTC')
1104+
11041105
# utsc is a different representation of the same time
11051106
assert tsc.timestamp() == utsc.timestamp()
11061107

11071108
if PY3:
1108-
# should agree with datetime.timestamp method
1109-
dt = ts.to_pydatetime()
1110-
assert dt.timestamp() == ts.timestamp()
1109+
1110+
# datetime.timestamp() converts in the local timezone
1111+
with tm.set_timezone('UTC'):
1112+
1113+
# should agree with datetime.timestamp method
1114+
dt = ts.to_pydatetime()
1115+
assert dt.timestamp() == ts.timestamp()
11111116

11121117

11131118
class TestTimestampNsOperations(object):

pandas/tests/tseries/test_timezones.py

+11-5
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313

1414
import pandas.util.testing as tm
1515
import pandas.tseries.offsets as offsets
16-
from pandas.compat import lrange, zip
16+
from pandas.compat import lrange, zip, PY3
1717
from pandas.core.indexes.datetimes import bdate_range, date_range
1818
from pandas.core.dtypes.dtypes import DatetimeTZDtype
1919
from pandas._libs import tslib
@@ -1278,16 +1278,22 @@ def test_replace_tzinfo(self):
12781278
result_dt = dt.replace(tzinfo=tzinfo)
12791279
result_pd = Timestamp(dt).replace(tzinfo=tzinfo)
12801280

1281-
if hasattr(result_dt, 'timestamp'): # New method in Py 3.3
1282-
assert result_dt.timestamp() == result_pd.timestamp()
1281+
if PY3:
1282+
# datetime.timestamp() converts in the local timezone
1283+
with tm.set_timezone('UTC'):
1284+
assert result_dt.timestamp() == result_pd.timestamp()
1285+
12831286
assert result_dt == result_pd
12841287
assert result_dt == result_pd.to_pydatetime()
12851288

12861289
result_dt = dt.replace(tzinfo=tzinfo).replace(tzinfo=None)
12871290
result_pd = Timestamp(dt).replace(tzinfo=tzinfo).replace(tzinfo=None)
12881291

1289-
if hasattr(result_dt, 'timestamp'): # New method in Py 3.3
1290-
assert result_dt.timestamp() == result_pd.timestamp()
1292+
if PY3:
1293+
# datetime.timestamp() converts in the local timezone
1294+
with tm.set_timezone('UTC'):
1295+
assert result_dt.timestamp() == result_pd.timestamp()
1296+
12911297
assert result_dt == result_pd
12921298
assert result_dt == result_pd.to_pydatetime()
12931299

0 commit comments

Comments
 (0)