Pylint raise-missing-from

Question:

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.

Asked By: Andre Rivoallan

||

Answers:

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.

Answered By: Dan Streeter
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.