Python Exceptions: EAFP and What is Really Exceptional?

前端 未结 5 2086
情话喂你
情话喂你 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 21:55

    Looking at the docs I think you can safely re-write the function as follows:

    import heapq
    ...
    pq = heapq.heapify(a_list)
    while pq:
        min1 = heapq.heappop(pq)
        if pq:
            min2 = heapq.heappop(pq)
            heapq.heappush(pq, min1 + min2)
    # do something with min1
    

    ..and thereby avoid the try-except.

    Getting to the end of a list which is something you know is going to happen here isn't exceptional - it's garaunteed! So better practice would be to handle it in advance. If you had something else in another thread which was consuming from the same heap then using try-except there would make a lot more sense (i.e. handling a special / unpredictable case).

    More generally, I would avoid try-excepts wherever I can test for and avoid a failure in advance. This forces you to say "I know this bad situation might happen so here's how I deal with it". In my opinion, you'll tend to write more readable code as a result.

    [Edit] Updated the example as per Alex's suggestion

提交回复
热议问题