Skip to content

Commit

Permalink
Merge pull request #6 from tjkuson/ruf018
Browse files Browse the repository at this point in the history
Add RUF018
  • Loading branch information
tjkuson authored Feb 17, 2024
2 parents f83a25d + 7c10166 commit 9ac450f
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 0 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## 0.2.0 (2024-02-17)

- Add `RUF018` check.

## 0.1.0 (2024-02-17)

- Add `RUF020` and `RUF025` checks.
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,25 @@ to enable the plugin.

## Checks

### RUF018 Avoid assignment expressions in `assert` statements

Checks for named assignment expressions in `assert` statements. When Python is
run with the `-O` option, the `assert` statement is ignored, and the assignment
expression is not executed. This can lead to unexpected behavior.

For example, replace

```python
assert (result := foo()) is not None
```

with

```python
result = foo()
assert result is not None
```

### RUF020 `typing.Never | T` is equivalent to `T`

Checks for `typing.Never` and `typing.NoReturn` in union types, which is
Expand Down
9 changes: 9 additions & 0 deletions src/flake8_ruff/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import ast
import typing

RUF018 = "RUF018 Avoid assignment expressions in assert statements"
RUF020 = "RUF020 {} | T is equivalent to T"
RUF025 = "RUF025 Unnecessary dict comprehension for iterable; use dict.fromkeys instead"

Expand Down Expand Up @@ -76,6 +77,14 @@ def visit_Subscript(self, node: ast.Subscript) -> None:
RUF020.format(never_like),
))

def visit_Assert(self, node: ast.Assert) -> None:
if isinstance(node.test, ast.NamedExpr):
self.errors.append((
node.lineno,
node.col_offset,
RUF018,
))


class Plugin:
name = "flake8-ruff"
Expand Down
8 changes: 8 additions & 0 deletions tests/test_flake8_ruff.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,14 @@ def run(source: str) -> list[tuple[int, int, str]]:
return [(line, col, msg) for (line, col, msg, type_) in Plugin(tree).run()]


def test_ruf018() -> None:
src = """\
assert (x := 1), "message"
"""
expected = [(1, 0, "RUF018 Avoid assignment expressions in assert statements")]
assert expected == run(src)


def test_ruf020_never() -> None:
src = """\
from typing import Never
Expand Down

0 comments on commit 9ac450f

Please sign in to comment.