Issue
For reasons of readability and re-usability, I have a function that always raises a specific exception if called. However, this does not seem to be considered by static code analysis, i.e. I get unnecessary warnings. Is there any good way to avoid these warning, e.g., by making the static code analysis aware of the fact that this function will always raise an exception?
Minimal working example:
def raise_an_exception():
raise Exception("...description...")
def foo(arg):
if arg:
x = 1
else:
raise_an_exception()
# causes warning "Local variable 'x' might be referenced before assignment":
return x + 1
def bar(arg):
if arg:
x = 1
else:
raise Exception("...description...")
# causes no warning:
return x + 1
Boundary condition: I do not want to declare x
in foo()
before the if
statement or set x
to any value in the else
code block, or any other workaround like that. It is not necessary in bar()
and it shouldn't be necessary in foo()
.
Solution
There's a NoReturn
annotation for functions that can't return normally:
from typing import NoReturn
def raise_an_exception() -> NoReturn:
raise Exception("...description...")
Static analysis tools that understand type annotations should understand this and not report an error for foo
.
Answered By - user2357112 Answer Checked By - Mildred Charles (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.