Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1""" basic inference routines """ 

2 

3from collections import abc 

4from numbers import Number 

5import re 

6from typing import Pattern 

7 

8import numpy as np 

9 

10from pandas._libs import lib 

11 

12is_bool = lib.is_bool 

13 

14is_integer = lib.is_integer 

15 

16is_float = lib.is_float 

17 

18is_complex = lib.is_complex 

19 

20is_scalar = lib.is_scalar 

21 

22is_decimal = lib.is_decimal 

23 

24is_interval = lib.is_interval 

25 

26is_list_like = lib.is_list_like 

27 

28 

29def is_number(obj) -> bool: 

30 """ 

31 Check if the object is a number. 

32 

33 Returns True when the object is a number, and False if is not. 

34 

35 Parameters 

36 ---------- 

37 obj : any type 

38 The object to check if is a number. 

39 

40 Returns 

41 ------- 

42 is_number : bool 

43 Whether `obj` is a number or not. 

44 

45 See Also 

46 -------- 

47 api.types.is_integer: Checks a subgroup of numbers. 

48 

49 Examples 

50 -------- 

51 >>> pd.api.types.is_number(1) 

52 True 

53 >>> pd.api.types.is_number(7.15) 

54 True 

55 

56 Booleans are valid because they are int subclass. 

57 

58 >>> pd.api.types.is_number(False) 

59 True 

60 

61 >>> pd.api.types.is_number("foo") 

62 False 

63 >>> pd.api.types.is_number("5") 

64 False 

65 """ 

66 

67 return isinstance(obj, (Number, np.number)) 

68 

69 

70def _iterable_not_string(obj) -> bool: 

71 """ 

72 Check if the object is an iterable but not a string. 

73 

74 Parameters 

75 ---------- 

76 obj : The object to check. 

77 

78 Returns 

79 ------- 

80 is_iter_not_string : bool 

81 Whether `obj` is a non-string iterable. 

82 

83 Examples 

84 -------- 

85 >>> _iterable_not_string([1, 2, 3]) 

86 True 

87 >>> _iterable_not_string("foo") 

88 False 

89 >>> _iterable_not_string(1) 

90 False 

91 """ 

92 

93 return isinstance(obj, abc.Iterable) and not isinstance(obj, str) 

94 

95 

96def is_iterator(obj) -> bool: 

97 """ 

98 Check if the object is an iterator. 

99 

100 For example, lists are considered iterators 

101 but not strings or datetime objects. 

102 

103 Parameters 

104 ---------- 

105 obj : The object to check 

106 

107 Returns 

108 ------- 

109 is_iter : bool 

110 Whether `obj` is an iterator. 

111 

112 Examples 

113 -------- 

114 >>> is_iterator([1, 2, 3]) 

115 True 

116 >>> is_iterator(datetime(2017, 1, 1)) 

117 False 

118 >>> is_iterator("foo") 

119 False 

120 >>> is_iterator(1) 

121 False 

122 """ 

123 

124 if not hasattr(obj, "__iter__"): 

125 return False 

126 

127 return hasattr(obj, "__next__") 

128 

129 

130def is_file_like(obj) -> bool: 

131 """ 

132 Check if the object is a file-like object. 

133 

134 For objects to be considered file-like, they must 

135 be an iterator AND have either a `read` and/or `write` 

136 method as an attribute. 

137 

138 Note: file-like objects must be iterable, but 

139 iterable objects need not be file-like. 

140 

141 Parameters 

142 ---------- 

143 obj : The object to check 

144 

145 Returns 

146 ------- 

147 is_file_like : bool 

148 Whether `obj` has file-like properties. 

149 

150 Examples 

151 -------- 

152 >>> buffer(StringIO("data")) 

153 >>> is_file_like(buffer) 

154 True 

155 >>> is_file_like([1, 2, 3]) 

156 False 

157 """ 

158 

159 if not (hasattr(obj, "read") or hasattr(obj, "write")): 

160 return False 

161 

162 if not hasattr(obj, "__iter__"): 

163 return False 

164 

165 return True 

166 

167 

168def is_re(obj) -> bool: 

169 """ 

170 Check if the object is a regex pattern instance. 

171 

172 Parameters 

173 ---------- 

174 obj : The object to check 

175 

176 Returns 

177 ------- 

178 is_regex : bool 

179 Whether `obj` is a regex pattern. 

180 

181 Examples 

182 -------- 

183 >>> is_re(re.compile(".*")) 

184 True 

185 >>> is_re("foo") 

186 False 

187 """ 

188 return isinstance(obj, Pattern) 

189 

190 

191def is_re_compilable(obj) -> bool: 

192 """ 

193 Check if the object can be compiled into a regex pattern instance. 

194 

195 Parameters 

196 ---------- 

197 obj : The object to check 

198 

199 Returns 

200 ------- 

201 is_regex_compilable : bool 

202 Whether `obj` can be compiled as a regex pattern. 

203 

204 Examples 

205 -------- 

206 >>> is_re_compilable(".*") 

207 True 

208 >>> is_re_compilable(1) 

209 False 

210 """ 

211 

212 try: 

213 re.compile(obj) 

214 except TypeError: 

215 return False 

216 else: 

217 return True 

218 

219 

220def is_array_like(obj) -> bool: 

221 """ 

222 Check if the object is array-like. 

223 

224 For an object to be considered array-like, it must be list-like and 

225 have a `dtype` attribute. 

226 

227 Parameters 

228 ---------- 

229 obj : The object to check 

230 

231 Returns 

232 ------- 

233 is_array_like : bool 

234 Whether `obj` has array-like properties. 

235 

236 Examples 

237 -------- 

238 >>> is_array_like(np.array([1, 2, 3])) 

239 True 

240 >>> is_array_like(pd.Series(["a", "b"])) 

241 True 

242 >>> is_array_like(pd.Index(["2016-01-01"])) 

243 True 

244 >>> is_array_like([1, 2, 3]) 

245 False 

246 >>> is_array_like(("a", "b")) 

247 False 

248 """ 

249 

250 return is_list_like(obj) and hasattr(obj, "dtype") 

251 

252 

253def is_nested_list_like(obj) -> bool: 

254 """ 

255 Check if the object is list-like, and that all of its elements 

256 are also list-like. 

257 

258 Parameters 

259 ---------- 

260 obj : The object to check 

261 

262 Returns 

263 ------- 

264 is_list_like : bool 

265 Whether `obj` has list-like properties. 

266 

267 Examples 

268 -------- 

269 >>> is_nested_list_like([[1, 2, 3]]) 

270 True 

271 >>> is_nested_list_like([{1, 2, 3}, {1, 2, 3}]) 

272 True 

273 >>> is_nested_list_like(["foo"]) 

274 False 

275 >>> is_nested_list_like([]) 

276 False 

277 >>> is_nested_list_like([[1, 2, 3], 1]) 

278 False 

279 

280 Notes 

281 ----- 

282 This won't reliably detect whether a consumable iterator (e. g. 

283 a generator) is a nested-list-like without consuming the iterator. 

284 To avoid consuming it, we always return False if the outer container 

285 doesn't define `__len__`. 

286 

287 See Also 

288 -------- 

289 is_list_like 

290 """ 

291 return ( 

292 is_list_like(obj) 

293 and hasattr(obj, "__len__") 

294 and len(obj) > 0 

295 and all(is_list_like(item) for item in obj) 

296 ) 

297 

298 

299def is_dict_like(obj) -> bool: 

300 """ 

301 Check if the object is dict-like. 

302 

303 Parameters 

304 ---------- 

305 obj : The object to check 

306 

307 Returns 

308 ------- 

309 is_dict_like : bool 

310 Whether `obj` has dict-like properties. 

311 

312 Examples 

313 -------- 

314 >>> is_dict_like({1: 2}) 

315 True 

316 >>> is_dict_like([1, 2, 3]) 

317 False 

318 >>> is_dict_like(dict) 

319 False 

320 >>> is_dict_like(dict()) 

321 True 

322 """ 

323 dict_like_attrs = ("__getitem__", "keys", "__contains__") 

324 return ( 

325 all(hasattr(obj, attr) for attr in dict_like_attrs) 

326 # [GH 25196] exclude classes 

327 and not isinstance(obj, type) 

328 ) 

329 

330 

331def is_named_tuple(obj) -> bool: 

332 """ 

333 Check if the object is a named tuple. 

334 

335 Parameters 

336 ---------- 

337 obj : The object to check 

338 

339 Returns 

340 ------- 

341 is_named_tuple : bool 

342 Whether `obj` is a named tuple. 

343 

344 Examples 

345 -------- 

346 >>> Point = namedtuple("Point", ["x", "y"]) 

347 >>> p = Point(1, 2) 

348 >>> 

349 >>> is_named_tuple(p) 

350 True 

351 >>> is_named_tuple((1, 2)) 

352 False 

353 """ 

354 

355 return isinstance(obj, tuple) and hasattr(obj, "_fields") 

356 

357 

358def is_hashable(obj) -> bool: 

359 """ 

360 Return True if hash(obj) will succeed, False otherwise. 

361 

362 Some types will pass a test against collections.abc.Hashable but fail when 

363 they are actually hashed with hash(). 

364 

365 Distinguish between these and other types by trying the call to hash() and 

366 seeing if they raise TypeError. 

367 

368 Returns 

369 ------- 

370 bool 

371 

372 Examples 

373 -------- 

374 >>> a = ([],) 

375 >>> isinstance(a, collections.abc.Hashable) 

376 True 

377 >>> is_hashable(a) 

378 False 

379 """ 

380 # Unfortunately, we can't use isinstance(obj, collections.abc.Hashable), 

381 # which can be faster than calling hash. That is because numpy scalars 

382 # fail this test. 

383 

384 # Reconsider this decision once this numpy bug is fixed: 

385 # https://github.com/numpy/numpy/issues/5562 

386 

387 try: 

388 hash(obj) 

389 except TypeError: 

390 return False 

391 else: 

392 return True 

393 

394 

395def is_sequence(obj) -> bool: 

396 """ 

397 Check if the object is a sequence of objects. 

398 String types are not included as sequences here. 

399 

400 Parameters 

401 ---------- 

402 obj : The object to check 

403 

404 Returns 

405 ------- 

406 is_sequence : bool 

407 Whether `obj` is a sequence of objects. 

408 

409 Examples 

410 -------- 

411 >>> l = [1, 2, 3] 

412 >>> 

413 >>> is_sequence(l) 

414 True 

415 >>> is_sequence(iter(l)) 

416 False 

417 """ 

418 

419 try: 

420 iter(obj) # Can iterate over it. 

421 len(obj) # Has a length associated with it. 

422 return not isinstance(obj, (str, bytes)) 

423 except (TypeError, AttributeError): 

424 return False