Coverage for /home/martinb/.local/share/virtualenvs/camcops/lib/python3.6/site-packages/pandas/core/dtypes/inference.py : 50%

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 """
3from collections import abc
4from numbers import Number
5import re
6from typing import Pattern
8import numpy as np
10from pandas._libs import lib
12is_bool = lib.is_bool
14is_integer = lib.is_integer
16is_float = lib.is_float
18is_complex = lib.is_complex
20is_scalar = lib.is_scalar
22is_decimal = lib.is_decimal
24is_interval = lib.is_interval
26is_list_like = lib.is_list_like
29def is_number(obj) -> bool:
30 """
31 Check if the object is a number.
33 Returns True when the object is a number, and False if is not.
35 Parameters
36 ----------
37 obj : any type
38 The object to check if is a number.
40 Returns
41 -------
42 is_number : bool
43 Whether `obj` is a number or not.
45 See Also
46 --------
47 api.types.is_integer: Checks a subgroup of numbers.
49 Examples
50 --------
51 >>> pd.api.types.is_number(1)
52 True
53 >>> pd.api.types.is_number(7.15)
54 True
56 Booleans are valid because they are int subclass.
58 >>> pd.api.types.is_number(False)
59 True
61 >>> pd.api.types.is_number("foo")
62 False
63 >>> pd.api.types.is_number("5")
64 False
65 """
67 return isinstance(obj, (Number, np.number))
70def _iterable_not_string(obj) -> bool:
71 """
72 Check if the object is an iterable but not a string.
74 Parameters
75 ----------
76 obj : The object to check.
78 Returns
79 -------
80 is_iter_not_string : bool
81 Whether `obj` is a non-string iterable.
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 """
93 return isinstance(obj, abc.Iterable) and not isinstance(obj, str)
96def is_iterator(obj) -> bool:
97 """
98 Check if the object is an iterator.
100 For example, lists are considered iterators
101 but not strings or datetime objects.
103 Parameters
104 ----------
105 obj : The object to check
107 Returns
108 -------
109 is_iter : bool
110 Whether `obj` is an iterator.
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 """
124 if not hasattr(obj, "__iter__"):
125 return False
127 return hasattr(obj, "__next__")
130def is_file_like(obj) -> bool:
131 """
132 Check if the object is a file-like object.
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.
138 Note: file-like objects must be iterable, but
139 iterable objects need not be file-like.
141 Parameters
142 ----------
143 obj : The object to check
145 Returns
146 -------
147 is_file_like : bool
148 Whether `obj` has file-like properties.
150 Examples
151 --------
152 >>> buffer(StringIO("data"))
153 >>> is_file_like(buffer)
154 True
155 >>> is_file_like([1, 2, 3])
156 False
157 """
159 if not (hasattr(obj, "read") or hasattr(obj, "write")):
160 return False
162 if not hasattr(obj, "__iter__"):
163 return False
165 return True
168def is_re(obj) -> bool:
169 """
170 Check if the object is a regex pattern instance.
172 Parameters
173 ----------
174 obj : The object to check
176 Returns
177 -------
178 is_regex : bool
179 Whether `obj` is a regex pattern.
181 Examples
182 --------
183 >>> is_re(re.compile(".*"))
184 True
185 >>> is_re("foo")
186 False
187 """
188 return isinstance(obj, Pattern)
191def is_re_compilable(obj) -> bool:
192 """
193 Check if the object can be compiled into a regex pattern instance.
195 Parameters
196 ----------
197 obj : The object to check
199 Returns
200 -------
201 is_regex_compilable : bool
202 Whether `obj` can be compiled as a regex pattern.
204 Examples
205 --------
206 >>> is_re_compilable(".*")
207 True
208 >>> is_re_compilable(1)
209 False
210 """
212 try:
213 re.compile(obj)
214 except TypeError:
215 return False
216 else:
217 return True
220def is_array_like(obj) -> bool:
221 """
222 Check if the object is array-like.
224 For an object to be considered array-like, it must be list-like and
225 have a `dtype` attribute.
227 Parameters
228 ----------
229 obj : The object to check
231 Returns
232 -------
233 is_array_like : bool
234 Whether `obj` has array-like properties.
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 """
250 return is_list_like(obj) and hasattr(obj, "dtype")
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.
258 Parameters
259 ----------
260 obj : The object to check
262 Returns
263 -------
264 is_list_like : bool
265 Whether `obj` has list-like properties.
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
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__`.
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 )
299def is_dict_like(obj) -> bool:
300 """
301 Check if the object is dict-like.
303 Parameters
304 ----------
305 obj : The object to check
307 Returns
308 -------
309 is_dict_like : bool
310 Whether `obj` has dict-like properties.
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 )
331def is_named_tuple(obj) -> bool:
332 """
333 Check if the object is a named tuple.
335 Parameters
336 ----------
337 obj : The object to check
339 Returns
340 -------
341 is_named_tuple : bool
342 Whether `obj` is a named tuple.
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 """
355 return isinstance(obj, tuple) and hasattr(obj, "_fields")
358def is_hashable(obj) -> bool:
359 """
360 Return True if hash(obj) will succeed, False otherwise.
362 Some types will pass a test against collections.abc.Hashable but fail when
363 they are actually hashed with hash().
365 Distinguish between these and other types by trying the call to hash() and
366 seeing if they raise TypeError.
368 Returns
369 -------
370 bool
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.
384 # Reconsider this decision once this numpy bug is fixed:
385 # https://github.com/numpy/numpy/issues/5562
387 try:
388 hash(obj)
389 except TypeError:
390 return False
391 else:
392 return True
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.
400 Parameters
401 ----------
402 obj : The object to check
404 Returns
405 -------
406 is_sequence : bool
407 Whether `obj` is a sequence of objects.
409 Examples
410 --------
411 >>> l = [1, 2, 3]
412 >>>
413 >>> is_sequence(l)
414 True
415 >>> is_sequence(iter(l))
416 False
417 """
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