MCPcopy Index your code
hub / github.com/python/cpython / always_iterable

Function always_iterable

Lib/importlib/metadata/_itertools.py:24–74  ·  view source on GitHub ↗

If *obj* is iterable, return an iterator over its items:: >>> obj = (1, 2, 3) >>> list(always_iterable(obj)) [1, 2, 3] If *obj* is not iterable, return a one-item iterable containing *obj*:: >>> obj = 1 >>> list(always_iterable(obj)) [1] If

(obj, base_type=(str, bytes))

Source from the content-addressed store, hash-verified

22
23# copied from more_itertools 8.8
24def always_iterable(obj, base_type=(str, bytes)):
25 """If *obj* is iterable, return an iterator over its items::
26
27 >>> obj = (1, 2, 3)
28 >>> list(always_iterable(obj))
29 [1, 2, 3]
30
31 If *obj* is not iterable, return a one-item iterable containing *obj*::
32
33 >>> obj = 1
34 >>> list(always_iterable(obj))
35 [1]
36
37 If *obj* is ``None``, return an empty iterable:
38
39 >>> obj = None
40 >>> list(always_iterable(None))
41 []
42
43 By default, binary and text strings are not considered iterable::
44
45 >>> obj = 'foo'
46 >>> list(always_iterable(obj))
47 ['foo']
48
49 If *base_type* is set, objects for which ``isinstance(obj, base_type)``
50 returns ``True`` won't be considered iterable.
51
52 >>> obj = {'a': 1}
53 >>> list(always_iterable(obj)) # Iterate over the dict's keys
54 ['a']
55 >>> list(always_iterable(obj, base_type=dict)) # Treat dicts as a unit
56 [{'a': 1}]
57
58 Set *base_type* to ``None`` to avoid any special handling and treat objects
59 Python considers iterable as iterable:
60
61 >>> obj = 'foo'
62 >>> list(always_iterable(obj, base_type=None))
63 ['f', 'o', 'o']
64 """
65 if obj is None:
66 return iter(())
67
68 if (base_type is not None) and isinstance(obj, base_type):
69 return iter((obj,))
70
71 try:
72 return iter(obj)
73 except TypeError:
74 return iter((obj,))
75
76
77# Copied from more_itertools 10.3

Callers 1

_top_level_inferredFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…