101

I have a pylint message (w0707) on this piece of code (from https://www.django-rest-framework.org/tutorial/3-class-based-views/):

class SnippetDetail(APIView):
    """
    Retrieve, update or delete a snippet instance.
    """
    def get_object(self, pk):
        try:
            return Snippet.objects.get(pk=pk)
        except Snippet.DoesNotExist:
            raise Http404

the message is:

Consider explicitly re-raising using the 'from' keyword

I don't quite understand how to act to correct the problem.

cottontail
  • 10,268
  • 18
  • 50
  • 51
Andre Rivoallan
  • 1,113
  • 2
  • 5
  • 9
  • 7
    See https://stackoverflow.com/questions/24752395/python-raise-from-usage – 9769953 Sep 04 '20 at 10:00
  • 2
    I implemented this warning. See more details and background here: https://blog.ram.rachum.com/post/621791438475296768/improving-python-exception-chaining-with – Ram Rachum Jan 22 '21 at 13:35

1 Answers1

156

The link in the comment on your question above outlines the issue and provides a solution, but for clarity of those landing straight on this page like myself, without having to go off to another thread, read and gain context, here is the answer to your specific problem:

TL;DR;

This is simply solved by aliasing the Exception you are 'excepting' and refering to it in your second raise.

Taking your code snippet above, see the bottom two lines, I've added 'under-carets' to denote what I've added.

class SnippetDetail(APIView):
    """
    Retrieve, update or delete a snippet instance.
    """
    def get_object(self, pk):
        try:
            return Snippet.objects.get(pk=pk)
        except Snippet.DoesNotExist as snip_no_exist:
#                                   ^^^^^^^^^^^^^^^^
            raise Http404 from snip_no_exist
#                         ^^^^^^^^^^^^^^^^^^

Note: The alias can be any well formed string.

Dan Streeter
  • 2,259
  • 2
  • 16
  • 16
  • 46
    This explains how to solve it, but not *why*. The traceback with/without the "from" clase are almost identical. And I don't see an added value from using the "from" statement. Is there a *technical* reason that reinforces the argument to use a "from"? – exhuma Nov 18 '20 at 09:24
  • 28
    The following article does a good explanation of why: https://stefan.sofa-rockers.org/2020/10/28/raise-from/ It boils down to how the exception is presented - what wording is used. – Daemonic Nov 18 '20 at 19:34
  • 4
    Correct, it does - and that was the intention of the answer as a TLDR to those hitting this page on the first result of google like I did and wanting the quick answer. For those wanting the technical reason behind why, the link on the comment of the question does a fantastic job of doing this. (https://stackoverflow.com/questions/24752395/python-raise-from-usage) – Dan Streeter Nov 18 '20 at 19:36