Python:使用 `yield from` 时的奇怪行为

Python: Weird behavior while using `yield from`

在下面的代码中,我把运行变成了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))

如果我使用 some_list = [1, [2, [3]]],这很好用,但当我尝试使用字符串时,它就不行了。

我怀疑我在 python 方面缺乏知识。任何指导表示赞赏。

字符串是可以无限迭代的。即使是 one-character 字符串也是可迭代的。

因此,除非对字符串添加特殊处理,否则总会出现堆栈溢出:

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)

注意: 使用 hasattr(i, '__iter__') 不足以检查 i 是否可迭代,因为还有其他方法可以满足迭代器协议。 only 确定对象是否可迭代的可靠方法是调用 iter(obj)