Skip to content

Commit 2b1cc3d

Browse files
authored
Feat: Checker for usage of assert in Python code (#118)
Avoid assert to enforce constraints. Assert statements are removed in optimised bytecode and can lead to confusing errors and vulnerabilities.
1 parent 7c30ae7 commit 2b1cc3d

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

checkers/python/avoid_assert.test.py

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
def divide(a, b):
2+
# <expect-error>
3+
assert b != 0
4+
return a / b
5+
6+
# <expect-error>
7+
assert 1 == 1
8+
# <expect-error>
9+
assert 1 == 2

checkers/python/avoid_assert.yml

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
language: python
2+
name: avoid-assert
3+
message: "Avoid assert to enforce constraints. Assert statements are removed in optimised bytecode."
4+
category: bug-risk
5+
severity: info
6+
7+
pattern: >
8+
(
9+
assert_statement
10+
) @avoid-assert
11+
12+
exclude:
13+
- "test/**"
14+
- "*_test.py"
15+
- "tests/**"
16+
- '*test_*.py'
17+
18+
description: |
19+
Using assert statements for enforcing constraints is risky because they are removed when Python is run in optimized mode (`python -O`).
20+
This can lead to unintended behavior, especially for security checks and critical logic.
21+
Instead, use explicit condition checks with exceptions (e.g., `if not condition: raise ValueError(...)`).

0 commit comments

Comments
 (0)