Skip to content

assert

Improper Check Using assert Function

Assertions are typically used during the development phase to catch logic errors and conditions that should never occur. However, relying on assertions for security checks or other critical runtime validations is not recommended because:

  • Assertions can be disabled in Python with the -O (optimize) and -OO flags, which remove assert statements and sometimes docstrings. If critical checks are implemented using assertions, this could lead to security vulnerabilities being exposed in production environments where optimizations are enabled.

  • Assertions throw exceptions if the condition fails, which, if not properly handled, can lead to crashes or other unintended behavior in the application.

Using assertions for non-critical checks during development is common, but for production code, especially for input validation, error handling, or other security-sensitive operations, it's important to use proper error handling mechanisms and validations that do not get removed during optimization.

Examples

assert.py
1
2
3
4
5
def foobar(a: str = None):
    assert a is not None
    return f"Hello {a}"

foobar("World")
Example Output
> precli tests/unit/rules/python/stdlib/assert/examples/assert.py
⚠️  Warning on line 2 in tests/unit/rules/python/stdlib/assert/examples/assert.py
PY001: Improper Check or Handling of Exceptional Conditions
Assert statements are disabled when optimizations are enabled.

Remediation

Use proper error handling mechanism appropriate for production code.

assert.py
1
2
3
4
5
def foobar(a: str = None):
    if a is not None:
        return f"Hello {a}"

foobar("World")

Default Configuration

enabled = false
level = "warning"

See also

New in version 0.3.8