Pylint raise-missing-from
Asked Answered
E

1

102

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.

Eubanks answered 4/9, 2020 at 9:57 Comment(2)
See https://mcmap.net/q/80444/-python-quot-raise-from-quot-usageClinquant
I implemented this warning. See more details and background here: blog.ram.rachum.com/post/621791438475296768/…Surely
O
158

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.

Once answered 11/9, 2020 at 18:13 Comment(3)
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"?Zephyrus
The following article does a good explanation of why: stefan.sofa-rockers.org/2020/10/28/raise-from It boils down to how the exception is presented - what wording is used.Counterblast
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://mcmap.net/q/80444/-python-quot-raise-from-quot-usage)Once

© 2022 - 2024 — McMap. All rights reserved.