Skip to content

Commit 93d46cf

Browse files
authored
PERF: is_list_like (#39852)
1 parent dfd99f9 commit 93d46cf

File tree

2 files changed

+45
-2
lines changed

2 files changed

+45
-2
lines changed

asv_bench/benchmarks/libs.py

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""
2+
Benchmarks for code in pandas/_libs, excluding pandas/_libs/tslibs,
3+
which has its own directory
4+
"""
5+
import numpy as np
6+
7+
from pandas._libs.lib import (
8+
is_list_like,
9+
is_scalar,
10+
)
11+
12+
from pandas import (
13+
NA,
14+
NaT,
15+
)
16+
17+
# TODO: share with something in pd._testing?
18+
scalars = [
19+
0,
20+
1.0,
21+
1 + 2j,
22+
True,
23+
"foo",
24+
b"bar",
25+
None,
26+
np.datetime64(123, "ns"),
27+
np.timedelta64(123, "ns"),
28+
NaT,
29+
NA,
30+
]
31+
zero_dims = [np.array("123")]
32+
listlikes = [np.array([1, 2, 3]), {0: 1}, {1, 2, 3}, [1, 2, 3], (1, 2, 3)]
33+
34+
35+
class ScalarListLike:
36+
params = scalars + zero_dims + listlikes
37+
38+
def time_is_list_like(self, param):
39+
is_list_like(param)
40+
41+
def time_is_scalar(self, param):
42+
is_scalar(param)

pandas/_libs/lib.pyx

+3-2
Original file line numberDiff line numberDiff line change
@@ -1059,11 +1059,12 @@ def is_list_like(obj: object, allow_sets: bool = True) -> bool:
10591059

10601060
cdef inline bint c_is_list_like(object obj, bint allow_sets) except -1:
10611061
return (
1062-
isinstance(obj, abc.Iterable)
1062+
# equiv: `isinstance(obj, abc.Iterable)`
1063+
hasattr(obj, "__iter__") and not isinstance(obj, type)
10631064
# we do not count strings/unicode/bytes as list-like
10641065
and not isinstance(obj, (str, bytes))
10651066
# exclude zero-dimensional numpy arrays, effectively scalars
1066-
and not (util.is_array(obj) and obj.ndim == 0)
1067+
and not cnp.PyArray_IsZeroDim(obj)
10671068
# exclude sets if allow_sets is False
10681069
and not (allow_sets is False and isinstance(obj, abc.Set))
10691070
)

0 commit comments

Comments
 (0)