Skip to content

Commit 44b08f2

Browse files
jschendelBrian Tu
authored and
Brian Tu
committed
CLN: Use pandas.core.common for None checks (pandas-dev#17816)
1 parent bbe248c commit 44b08f2

21 files changed

+90
-75
lines changed

pandas/core/common.py

+20-7
Original file line numberDiff line numberDiff line change
@@ -223,24 +223,44 @@ def _mut_exclusive(**kwargs):
223223

224224

225225
def _not_none(*args):
226+
"""Returns a generator consisting of the arguments that are not None"""
226227
return (arg for arg in args if arg is not None)
227228

228229

229230
def _any_none(*args):
231+
"""Returns a boolean indicating if any argument is None"""
230232
for arg in args:
231233
if arg is None:
232234
return True
233235
return False
234236

235237

238+
def _all_none(*args):
239+
"""Returns a boolean indicating if all arguments are None"""
240+
for arg in args:
241+
if arg is not None:
242+
return False
243+
return True
244+
245+
246+
def _any_not_none(*args):
247+
"""Returns a boolean indicating if any argument is not None"""
248+
for arg in args:
249+
if arg is not None:
250+
return True
251+
return False
252+
253+
236254
def _all_not_none(*args):
255+
"""Returns a boolean indicating if all arguments are not None"""
237256
for arg in args:
238257
if arg is None:
239258
return False
240259
return True
241260

242261

243262
def _count_not_none(*args):
263+
"""Returns the count of arguments that are not None"""
244264
return sum(x is not None for x in args)
245265

246266

@@ -459,13 +479,6 @@ def _apply_if_callable(maybe_callable, obj, **kwargs):
459479
return maybe_callable
460480

461481

462-
def _all_none(*args):
463-
for arg in args:
464-
if arg is not None:
465-
return False
466-
return True
467-
468-
469482
def _where_compat(mask, arr1, arr2):
470483
if arr1.dtype == _NS_DTYPE and arr2.dtype == _NS_DTYPE:
471484
new_vals = np.where(mask, arr1.view('i8'), arr2.view('i8'))

pandas/core/generic.py

+5-7
Original file line numberDiff line numberDiff line change
@@ -28,12 +28,10 @@
2828
from pandas.core.dtypes.cast import maybe_promote, maybe_upcast_putmask
2929
from pandas.core.dtypes.missing import isna, notna
3030
from pandas.core.dtypes.generic import ABCSeries, ABCPanel, ABCDataFrame
31-
32-
from pandas.core.common import (_all_not_none,
33-
_values_from_object,
34-
_maybe_box_datetimelike,
35-
SettingWithCopyError, SettingWithCopyWarning,
36-
AbstractMethodError)
31+
from pandas.core.common import (_all_not_none, _count_not_none,
32+
_maybe_box_datetimelike, _values_from_object,
33+
AbstractMethodError, SettingWithCopyError,
34+
SettingWithCopyWarning)
3735

3836
from pandas.core.base import PandasObject, SelectionMixin
3937
from pandas.core.index import (Index, MultiIndex, _ensure_index,
@@ -3252,7 +3250,7 @@ def filter(self, items=None, like=None, regex=None, axis=None):
32523250
"""
32533251
import re
32543252

3255-
nkw = sum([x is not None for x in [items, like, regex]])
3253+
nkw = _count_not_none(items, like, regex)
32563254
if nkw > 1:
32573255
raise TypeError('Keyword arguments `items`, `like`, or `regex` '
32583256
'are mutually exclusive')

pandas/core/groupby.py

+13-15
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,8 @@
3939
from pandas.core.dtypes.missing import isna, notna, _maybe_fill
4040

4141
from pandas.core.common import (_values_from_object, AbstractMethodError,
42-
_default_index)
42+
_default_index, _not_none, _get_callable_name,
43+
_asarray_tuplesafe)
4344

4445
from pandas.core.base import (PandasObject, SelectionMixin, GroupByError,
4546
DataError, SpecificationError)
@@ -60,7 +61,6 @@
6061
from pandas.util._validators import validate_kwargs
6162

6263
import pandas.core.algorithms as algorithms
63-
import pandas.core.common as com
6464
from pandas.core.config import option_context
6565

6666
from pandas.plotting._core import boxplot_frame_groupby
@@ -877,10 +877,9 @@ def _concat_objects(self, keys, values, not_indexed_same=False):
877877
def reset_identity(values):
878878
# reset the identities of the components
879879
# of the values to prevent aliasing
880-
for v in values:
881-
if v is not None:
882-
ax = v._get_axis(self.axis)
883-
ax._reset_identity()
880+
for v in _not_none(*values):
881+
ax = v._get_axis(self.axis)
882+
ax._reset_identity()
884883
return values
885884

886885
if not not_indexed_same:
@@ -1806,7 +1805,7 @@ def apply(self, f, data, axis=0):
18061805
group_keys = self._get_group_keys()
18071806

18081807
# oh boy
1809-
f_name = com._get_callable_name(f)
1808+
f_name = _get_callable_name(f)
18101809
if (f_name not in _plotting_methods and
18111810
hasattr(splitter, 'fast_apply') and axis == 0):
18121811
try:
@@ -2533,7 +2532,7 @@ def __init__(self, index, grouper=None, obj=None, name=None, level=None,
25332532
self.grouper = self.obj[self.name]
25342533

25352534
elif isinstance(self.grouper, (list, tuple)):
2536-
self.grouper = com._asarray_tuplesafe(self.grouper)
2535+
self.grouper = _asarray_tuplesafe(self.grouper)
25372536

25382537
# a passed Categorical
25392538
elif is_categorical_dtype(self.grouper):
@@ -2739,7 +2738,7 @@ def _get_grouper(obj, key=None, axis=0, level=None, sort=True,
27392738
if not any_callable and not all_in_columns_index and \
27402739
not any_arraylike and not any_groupers and \
27412740
match_axis_length and level is None:
2742-
keys = [com._asarray_tuplesafe(keys)]
2741+
keys = [_asarray_tuplesafe(keys)]
27432742

27442743
if isinstance(level, (tuple, list)):
27452744
if key is None:
@@ -3028,7 +3027,7 @@ def _aggregate_multiple_funcs(self, arg, _level):
30283027
columns.append(f)
30293028
else:
30303029
# protect against callables without names
3031-
columns.append(com._get_callable_name(f))
3030+
columns.append(_get_callable_name(f))
30323031
arg = lzip(columns, arg)
30333032

30343033
results = {}
@@ -3686,14 +3685,13 @@ def _wrap_applied_output(self, keys, values, not_indexed_same=False):
36863685
key_names = self.grouper.names
36873686

36883687
# GH12824.
3689-
def first_non_None_value(values):
3688+
def first_not_none(values):
36903689
try:
3691-
v = next(v for v in values if v is not None)
3690+
return next(_not_none(*values))
36923691
except StopIteration:
36933692
return None
3694-
return v
36953693

3696-
v = first_non_None_value(values)
3694+
v = first_not_none(values)
36973695

36983696
if v is None:
36993697
# GH9684. If all values are None, then this will throw an error.
@@ -3726,7 +3724,7 @@ def first_non_None_value(values):
37263724
key_index = None
37273725

37283726
# make Nones an empty object
3729-
v = first_non_None_value(values)
3727+
v = first_not_none(values)
37303728
if v is None:
37313729
return DataFrame()
37323730
elif isinstance(v, NDFrame):

pandas/core/indexes/api.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ def _get_consensus_names(indexes):
123123
# find the non-none names, need to tupleify to make
124124
# the set hashable, then reverse on return
125125
consensus_names = set([tuple(i.names) for i in indexes
126-
if any(n is not None for n in i.names)])
126+
if com._any_not_none(*i.names)])
127127
if len(consensus_names) == 1:
128128
return list(list(consensus_names)[0])
129129
return [None] * indexes[0].nlevels

pandas/core/indexes/base.py

+6-7
Original file line numberDiff line numberDiff line change
@@ -42,16 +42,15 @@
4242
needs_i8_conversion,
4343
is_iterator, is_list_like,
4444
is_scalar)
45-
from pandas.core.common import (is_bool_indexer,
46-
_values_from_object,
47-
_asarray_tuplesafe)
45+
from pandas.core.common import (is_bool_indexer, _values_from_object,
46+
_asarray_tuplesafe, _not_none,
47+
_index_labels_to_array)
4848

4949
from pandas.core.base import PandasObject, IndexOpsMixin
5050
import pandas.core.base as base
5151
from pandas.util._decorators import (
5252
Appender, Substitution, cache_readonly, deprecate_kwarg)
5353
from pandas.core.indexes.frozen import FrozenList
54-
import pandas.core.common as com
5554
import pandas.core.dtypes.concat as _concat
5655
import pandas.core.missing as missing
5756
import pandas.core.algorithms as algos
@@ -3168,8 +3167,8 @@ def _join_multi(self, other, how, return_indexers=True):
31683167
other_is_mi = isinstance(other, MultiIndex)
31693168

31703169
# figure out join names
3171-
self_names = [n for n in self.names if n is not None]
3172-
other_names = [n for n in other.names if n is not None]
3170+
self_names = _not_none(*self.names)
3171+
other_names = _not_none(*other.names)
31733172
overlap = list(set(self_names) & set(other_names))
31743173

31753174
# need at least 1 in common, but not more than 1
@@ -3714,7 +3713,7 @@ def drop(self, labels, errors='raise'):
37143713
-------
37153714
dropped : Index
37163715
"""
3717-
labels = com._index_labels_to_array(labels)
3716+
labels = _index_labels_to_array(labels)
37183717
indexer = self.get_indexer(labels)
37193718
mask = indexer == -1
37203719
if mask.any():

pandas/core/indexes/multi.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@
2121
is_scalar)
2222
from pandas.core.dtypes.missing import isna, array_equivalent
2323
from pandas.errors import PerformanceWarning, UnsortedIndexError
24-
from pandas.core.common import (_values_from_object,
24+
from pandas.core.common import (_any_not_none,
25+
_values_from_object,
2526
is_bool_indexer,
2627
is_null_slice,
2728
is_true_slices)
@@ -509,7 +510,7 @@ def _format_attrs(self):
509510
max_seq_items=False)),
510511
('labels', ibase.default_pprint(self._labels,
511512
max_seq_items=False))]
512-
if not all(name is None for name in self.names):
513+
if _any_not_none(*self.names):
513514
attrs.append(('names', ibase.default_pprint(self.names)))
514515
if self.sortorder is not None:
515516
attrs.append(('sortorder', ibase.default_pprint(self.sortorder)))

pandas/core/indexes/range.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from pandas import compat
1313
from pandas.compat import lrange, range
1414
from pandas.compat.numpy import function as nv
15+
from pandas.core.common import _all_none
1516
from pandas.core.indexes.base import Index, _index_shared_docs
1617
from pandas.util._decorators import Appender, cache_readonly
1718
import pandas.core.dtypes.concat as _concat
@@ -83,7 +84,7 @@ def _ensure_int(value, field):
8384

8485
return new_value
8586

86-
if start is None and stop is None and step is None:
87+
if _all_none(start, stop, step):
8788
msg = "RangeIndex(...) must be called with integers"
8889
raise TypeError(msg)
8990
elif start is None:

pandas/core/panel.py

+9-7
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,13 @@
1515
is_string_like, is_scalar)
1616
from pandas.core.dtypes.missing import notna
1717

18-
import pandas.core.common as com
1918
import pandas.core.ops as ops
2019
import pandas.core.missing as missing
2120
from pandas import compat
2221
from pandas.compat import (map, zip, range, u, OrderedDict)
2322
from pandas.compat.numpy import function as nv
24-
from pandas.core.common import _try_sort, _default_index
23+
from pandas.core.common import (_try_sort, _default_index, _all_not_none,
24+
_any_not_none, _apply_if_callable)
2525
from pandas.core.frame import DataFrame
2626
from pandas.core.generic import NDFrame, _shared_docs
2727
from pandas.core.index import (Index, MultiIndex, _ensure_index,
@@ -166,7 +166,7 @@ def _init_data(self, data, copy, dtype, **kwargs):
166166

167167
axes = None
168168
if isinstance(data, BlockManager):
169-
if any(x is not None for x in passed_axes):
169+
if _any_not_none(*passed_axes):
170170
axes = [x if x is not None else y
171171
for x, y in zip(passed_axes, data.axes)]
172172
mgr = data
@@ -178,7 +178,7 @@ def _init_data(self, data, copy, dtype, **kwargs):
178178
mgr = self._init_matrix(data, passed_axes, dtype=dtype, copy=copy)
179179
copy = False
180180
dtype = None
181-
elif is_scalar(data) and all(x is not None for x in passed_axes):
181+
elif is_scalar(data) and _all_not_none(*passed_axes):
182182
values = cast_scalar_to_array([len(x) for x in passed_axes],
183183
data, dtype=dtype)
184184
mgr = self._init_matrix(values, passed_axes, dtype=values.dtype,
@@ -279,7 +279,7 @@ def from_dict(cls, data, intersect=False, orient='items', dtype=None):
279279
return cls(**d)
280280

281281
def __getitem__(self, key):
282-
key = com._apply_if_callable(key, self)
282+
key = _apply_if_callable(key, self)
283283

284284
if isinstance(self._info_axis, MultiIndex):
285285
return self._getitem_multilevel(key)
@@ -594,7 +594,7 @@ def _box_item_values(self, key, values):
594594
return self._constructor_sliced(values, **d)
595595

596596
def __setitem__(self, key, value):
597-
key = com._apply_if_callable(key, self)
597+
key = _apply_if_callable(key, self)
598598
shape = tuple(self.shape)
599599
if isinstance(value, self._constructor_sliced):
600600
value = value.reindex(
@@ -616,7 +616,9 @@ def __setitem__(self, key, value):
616616

617617
def _unpickle_panel_compat(self, state): # pragma: no cover
618618
"Unpickle the panel"
619-
_unpickle = com._unpickle_array
619+
from pandas.io.pickle import _unpickle_array
620+
621+
_unpickle = _unpickle_array
620622
vals, items, major, minor = state
621623

622624
items = _unpickle(items)

pandas/core/reshape/concat.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -241,7 +241,7 @@ def __init__(self, objs, axis=0, join='outer', join_axes=None,
241241
raise ValueError('No objects to concatenate')
242242

243243
if keys is None:
244-
objs = [obj for obj in objs if obj is not None]
244+
objs = list(com._not_none(*objs))
245245
else:
246246
# #1649
247247
clean_keys = []

pandas/core/reshape/merge.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1550,4 +1550,4 @@ def _should_fill(lname, rname):
15501550

15511551

15521552
def _any(x):
1553-
return x is not None and len(x) > 0 and any([y is not None for y in x])
1553+
return x is not None and com._any_not_none(*x)

pandas/core/series.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,8 @@
4545
SettingWithCopyError,
4646
_maybe_box_datetimelike,
4747
_dict_compat,
48-
standardize_mapping)
48+
standardize_mapping,
49+
_any_none)
4950
from pandas.core.index import (Index, MultiIndex, InvalidIndexError,
5051
Float64Index, _ensure_index)
5152
from pandas.core.indexing import check_bool_indexer, maybe_convert_indices
@@ -713,7 +714,7 @@ def _get_with(self, key):
713714

714715
def _get_values_tuple(self, key):
715716
# mpl hackaround
716-
if any(k is None for k in key):
717+
if _any_none(*key):
717718
return self._get_values(key)
718719

719720
if not isinstance(self.index, MultiIndex):

pandas/core/window.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232

3333
from pandas.core.base import (PandasObject, SelectionMixin,
3434
GroupByMixin)
35-
import pandas.core.common as com
35+
from pandas.core.common import _asarray_tuplesafe, _count_not_none
3636
import pandas._libs.window as _window
3737

3838
from pandas import compat
@@ -535,7 +535,7 @@ def _prep_window(self, **kwargs):
535535

536536
window = self._get_window()
537537
if isinstance(window, (list, tuple, np.ndarray)):
538-
return com._asarray_tuplesafe(window).astype(float)
538+
return _asarray_tuplesafe(window).astype(float)
539539
elif is_integer(window):
540540
import scipy.signal as sig
541541

@@ -1972,8 +1972,7 @@ def dataframe_from_int_dict(data, frame_template):
19721972

19731973

19741974
def _get_center_of_mass(com, span, halflife, alpha):
1975-
valid_count = len([x for x in [com, span, halflife, alpha]
1976-
if x is not None])
1975+
valid_count = _count_not_none(com, span, halflife, alpha)
19771976
if valid_count > 1:
19781977
raise ValueError("com, span, halflife, and alpha "
19791978
"are mutually exclusive")

0 commit comments

Comments
 (0)