Skip to main content

Improper Check Using assert Function

PY001
improper_check
CWE-703
⚠️ Warning

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.

Example

def foobar(a: str = None):
assert a is not None
return f"Hello {a}"

foobar("World")

Remediation

Use proper error handling mechanism appropriate for production code.

def foobar(a: str = None):
if a is not None:
return f"Hello {a}"

foobar("World")

False Positives

In the case of a false positive the rule can be suppressed. Simply add a trailing or preceding comment line with either the rule ID (PY001) or rule category name (improper_check).

Fix Iconfix
def foobar(a: str = None):
# suppress: PY001
assert a is not None
return f"Hello {a}"

foobar("World")

See also