6 | def is_iterable(obj): |
7 | """ |
8 | Robustly test whether an object is iterable. |
9 | |
10 | Parameters |
11 | ---------- |
12 | obj : object |
13 | The object to be checked. |
14 | |
15 | Returns |
16 | ------- |
17 | is_iterable : boolean |
18 | `True` if the object is iterable, `False` otherwise. |
19 | |
20 | Notes |
21 | ----- |
22 | This test iterability by calling `iter()` and catching a `TypeError`. |
23 | Various other ways might occur to you, but they all have flaws: |
24 | |
25 | * `hasattr(obj, '__len__')` will fail for objects that can be iterated |
26 | on despite not knowing their length a priori. |
27 | * `hasattr(obj, '__iter__')` will fail on objects like Theano tensors |
28 | that implement it solely to raise a `TypeError` (because Theano |
29 | tensors implement `__getitem__` semantics, Python 2.x will try |
30 | to iterate on them via this legacy method if `__iter__` is not |
31 | defined). |
32 | * `hasattr` has a tendency to swallow other exception-like objects |
33 | (`KeyboardInterrupt`, etc.) anyway, and should be avoided for this |
34 | reason in Python 2.x, but `getattr()` with a sentinel value suffers |
35 | from the exact same pitfalls above. |
36 | """ |
37 | try: |
38 | iter(obj) |
39 | except TypeError: |
40 | return False |
41 | return True |