Python: Weird Behavior While Using `yield From`
In the following code, I have run into a RecursionError: maximum recursion depth exceeded. def unpack(given): for i in given: if hasattr(i, '__iter__'): yie
Solution 1:
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:
defflatten(x):
try:
it = iter(x)
except TypeError:
yield x
returnifisinstance(x, (str, bytes)):
yield x
returnfor elem in it:
yieldfrom 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)
.
Post a Comment for "Python: Weird Behavior While Using `yield From`"