Python: Weird behavior while using `yield from`

蓝咒 提交于 2019-12-19 10:29:28

问题


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__'):
            yield from unpack(i)
        else:
            yield i

some_list = ['a', ['b', 'c'], 'd']

unpacked = list(unpack(some_list))

This works fine if I use some_list = [1, [2, [3]]], but not when I try it with strings.

I suspect my lack of knowledge in python. Any guidance appreciated.


回答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:

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).



来源:https://stackoverflow.com/questions/49641930/python-weird-behavior-while-using-yield-from

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!