Infinite for loops possible in Python?

后端 未结 10 2201
误落风尘
误落风尘 2020-12-06 10:39

Is it possible to get an infinite loop in for loop?

My guess is that there can be an infinite for loop in Python. I\'d like to know this for future refe

10条回答
  •  感动是毒
    2020-12-06 11:23

    While there have been many answers with nice examples of how an infinite for loop can be done, none have answered why (it wasn't asked, though, but still...)

    A for loop in Python is syntactic sugar for handling the iterator object of an iterable an its methods. For example, this is your typical for loop:

    for element in iterable:
        foo(element)
    

    And this is what's sorta happening behind the scenes:

    iterator = iterable.__iter__()
    try:
        while True:
            element = iterator.next()
            foo(element)
    except StopIteration:
        pass
    

    An iterator object has to have, as it can be seen, anextmethod that returns an element and advances once (if it can, or else it raises a StopIteration exception).

    So every iterable object of which iterator'snextmethod does never raise said exception has an infinite for loop. For example:

    class InfLoopIter(object):
        def __iter__(self):
            return self # an iterator object must always have this
        def next(self):
            return None
    
    class InfLoop(object):
        def __iter__(self):
            return InfLoopIter()
    
    for i in InfLoop():
        print "Hello World!" # infinite loop yay!
    

提交回复
热议问题