Python: Weird behavior while using `yield from`

前端 未结 1 2052
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-14 21:30

In the following code, I have run into a RecursionError: maximum recursion depth exceeded.

def unpack(given):
    for i in given:
        if has         


        
相关标签:
1条回答
  • 2021-01-14 21:54

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

    0 讨论(0)
提交回复
热议问题