Python Exceptions: EAFP and What is Really Exceptional?

前端 未结 5 2092
情话喂你
情话喂你 2020-12-02 21:37

It\'s been said in a couple places (here and here) that Python\'s emphasis on \"it\'s easier to ask for forgiveness than permission\" (EAFP) should be tempered with the idea

5条回答
  •  情书的邮戳
    2020-12-02 22:03

    Just for the record, i'd write is like this:

    import heapq
    a_list = range(20)
    pq = a_list[:]
    heapq.heapify(pq)
    try:
        while True:
            min1 = heapq.heappop(pq)
            min2 = heapq.heappop(pq)
            heapq.heappush(pq, min1 + min2)
    except IndexError:
        pass # we ran out of numbers in pq
    

    Exceptions can leave a loop (even functions) and you can use them for that. Since Python throws them everywhere, I think this pattern is quite useful (even pythonic).

提交回复
热议问题