In the following code, I have run into a RecursionError: maximum recursion depth exceeded
.
def unpack(given):
for i in given:
if has
Strings are infinitely iterable. Even a one-character string is iterable.
Therefore, you will always get a stack overflow unless you add special handling for strings:
def flatten(x):
try:
it = iter(x)
except TypeError:
yield x
return
if isinstance(x, (str, bytes)):
yield x
return
for elem in it:
yield from flatten(elem)
Note: using hasattr(i, '__iter__')
is not sufficient to check if i
is iterable, because there are other ways to satisfy the iterator protocol. The only reliable way to determine whether an object is iterable is to call iter(obj)
.