Skip to content

Exception handling not working. #6091

Closed

Description

@sp1rs
from typing import Union

def post(path: str) -> Union[requests.models.Response, ManualException]
      try:
            return requests.post(path)
      except:  
            raise ManualException 


def call() -> List:
        try:
              resp = post('path')
        except ManualException:
               return []

        return resp.content

On running mypy

Item "ManualException" of "Union[Response, ManualException]" has no attribute "content"

Ideally mypy should not raise any error, because I am handling the case when exception is raised.

Activity

  1. JelleZijlstra commented on Dec 20, 2018

    @JelleZijlstra
    Member

    Exceptions should not be included in the return type. Your post function should simply return requests.models.Response.

    The Python type system doesn't provide a way to specify what exceptions may be raised from a function.

  2. sp1rs commented on Dec 20, 2018

    @sp1rs
    ContributorAuthor

    @JelleZijlstra There are lots of places where we raise exception. This is common practice. Any work around? In django codebase, raising exception is a common thing.

  3. JukkaL commented on Dec 20, 2018

    @JukkaL
    Collaborator

    Mypy can't check that exceptions are correctly caught or annotated, so your best is to document them in a docstring or invent some custom way of annotating them (but that won't be checked by mypy).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions