Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue 1974 #1998

Open
wants to merge 18 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ Semantic versioning in our case means:
### Bugfixes

- Fixes `UselessReturningElseViolation` to not report `else` with `break` #1958
- Fixes bare raise outside of except block #1974

### Misc

Expand Down
21 changes: 21 additions & 0 deletions tests/fixtures/noqa/noqa.py
Original file line number Diff line number Diff line change
Expand Up @@ -788,3 +788,24 @@ def get_item(): # noqa: WPS463
some(number) for numbers in matrix
for number in numbers # noqa: WPS361
]

def detect_bare_raise1():
skarzi marked this conversation as resolved.
Show resolved Hide resolved
"""Function to check if the bare raise is detected.""" # noqa: DAR401
skarzi marked this conversation as resolved.
Show resolved Hide resolved
raise ValueError

def check1():
"""Calls detect_bare_raise1 function.""" # noqa: D401
detect_bare_raise1()

def detect_bare_raise2():
"""Function to check if the bare raise is detected.""" # noqa: DAR401
raise ZeroDivisionError

def detect_bare_raise2_helper():
"""Function to check if the bare raise is detected.""" # noqa: D401
try:
testvar = 1/0 # noqa: WPS344, F841
except ZeroDivisionError:
detect_bare_raise2()
raise ZeroDivisionError

2 changes: 1 addition & 1 deletion wemake_python_styleguide/logic/tree/operators.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def count_unary_operator(
amount: int = 0,
) -> int:
"""Returns amount of unary operators matching input."""
parent = get_parent(node)
parent = (node)
skarzi marked this conversation as resolved.
Show resolved Hide resolved
if parent is None or not isinstance(parent, ast.UnaryOp):
return amount
if isinstance(parent.op, operator):
Expand Down
34 changes: 33 additions & 1 deletion wemake_python_styleguide/violations/refactoring.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
ImplicitDictGetViolation
ImplicitNegativeIndexViolation
SimplifiableReturningIfViolation
BareRaiseViolation

Refactoring opportunities
-------------------------
Expand Down Expand Up @@ -81,7 +82,7 @@
.. autoclass:: ImplicitDictGetViolation
.. autoclass:: ImplicitNegativeIndexViolation
.. autoclass:: SimplifiableReturningIfViolation

.. autoclass:: BareRaiseViolation
"""

from typing_extensions import final
Expand Down Expand Up @@ -1233,3 +1234,34 @@ def some_function():

error_template = 'Found simplifiable returning `if` condition in a function'
code = 531


@final
class BareRaiseViolation(ASTViolation):
"""
Forbid bare ``raise`` outside of ``except`` block.

Reasoning:
One could call a function from an except and have a bare raise
inside but it is considered bad practice to have a
bare raise outside of an except block.
skarzi marked this conversation as resolved.
Show resolved Hide resolved

Solution:
Always use a raise statement inside a parent except block.
skarzi marked this conversation as resolved.
Show resolved Hide resolved

Example::

# good
def smth():
try:
...
except:
raise

# bad
def smth():
raise
"""

error_template = 'Detect bare raise outside of except block'
skarzi marked this conversation as resolved.
Show resolved Hide resolved
code = 532
14 changes: 14 additions & 0 deletions wemake_python_styleguide/visitors/ast/keywords.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
IncorrectYieldFromTargetViolation,
MultipleContextManagerAssignmentsViolation,
)
from wemake_python_styleguide.violations.refactoring import BareRaiseViolation
from wemake_python_styleguide.visitors.base import BaseNodeVisitor
from wemake_python_styleguide.visitors.decorators import alias

Expand All @@ -51,15 +52,23 @@ class WrongRaiseVisitor(BaseNodeVisitor):
'BaseException',
))

_bad_returning_nodes: ClassVar[AnyNodes] = (
ast.Return,
ast.Raise,
ast.Break,
)
skarzi marked this conversation as resolved.
Show resolved Hide resolved

def visit_Raise(self, node: ast.Raise) -> None:
"""
Checks how ``raise`` keyword is used.

Raises:
RaiseNotImplementedViolation
BareRaiseViolation

"""
self._check_exception_type(node)
self._check_bare_raise(node)
self.generic_visit(node)

def _check_exception_type(self, node: ast.Raise) -> None:
Expand All @@ -71,6 +80,11 @@ def _check_exception_type(self, node: ast.Raise) -> None:
BaseExceptionRaiseViolation(node, text=exception_name),
)

def _check_bare_raise(self, node: ast.Raise) -> None:
parent = walk.get_closest_parent(node, ast.ExceptHandler)
if not parent:
skarzi marked this conversation as resolved.
Show resolved Hide resolved
self.add_violation(BareRaiseViolation(node))


@final
@alias('visit_any_function', (
Expand Down