Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of this `while False:` in Python's standard library? [duplicate]

Tags:

cpython

CPython's implementation of collections.abc.Iterable has this bizarre idiom:

while False:
    yield None

Seems like the second line will never be executed. So why not just use pass instead?

The full code for the Iterable class is as follows:

class Iterable(metaclass=ABCMeta):

    __slots__ = ()

    @abstractmethod
    def __iter__(self):
        while False:
            yield None

    @classmethod
    def __subclasshook__(cls, C):
        if cls is Iterable:
            return _check_methods(C, "__iter__")
        return NotImplemented

    __class_getitem__ = classmethod(GenericAlias)
like image 593
Wood Avatar asked Oct 21 '25 20:10

Wood


1 Answers

This idiom's use of yield means it will return an empty generator, as opposed to None:

>>> def iter():
...   if False:
...     yield None
... 
>>> iter()
<generator object iter at 0x7fd2cc134660>
>>> [i for i in iter()]
[]

If pass were used:

>>> def iter2():
...   pass
... 
>>> iter2()
>>> [i for i in iter2()]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not iterable

That TypeError is what is being avoided.

like image 146
Joe Avatar answered Oct 26 '25 16:10

Joe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!