This rule raises an issue when a data validation method that is expected to transform or validate field values has a code path that does not explicitly return a value.
In Python, this specifically applies to Pydantic’s field_validator decorator methods.
In data validation frameworks, validation methods are functions or methods (marked by framework-specific decorators or annotations) that validate and optionally transform field values during object construction. These frameworks use the validator’s return value as the final field value.
When a validation method does not explicitly return a value, the language runtime implicitly returns a null/None value. The framework then stores this null/None as the field value, regardless of the field’s type annotation or declaration. This happens silently - no error is raised, no warning is emitted, and the object appears to construct successfully.
This creates a silent data corruption bug. A field declared as string, integer, or any other non-nullable type will contain null/None at runtime, violating its type contract without any indication to the caller.
The issue commonly occurs in two scenarios:
Because the bug is silent at construction time, it only surfaces later when code that relies on the correct type encounters the unexpected null/None value.
Fields that should never be null silently become null, breaking the data model’s integrity. Downstream code that trusts the type declaration will fail or produce incorrect results.
For example, a name field declared as a non-nullable string type might become null, causing string operations to raise type-related
errors or conditional checks to behave incorrectly.
When serializing the model using standard serialization methods, fields will be serialized as None instead of their expected types.
This breaks API contracts, database constraints, and data interchange formats.
External systems receiving this data may reject it or, worse, accept it and propagate the corruption.
Because no exception is raised during model construction, the bug manifests far from its source. You might see failures in business logic that expects valid data types.
Tracing these failures back to the missing return statement in a validator can be time-consuming.
In Python with Pydantic, this specifically occurs when using model_dump() or model_dump_json() serialization methods.
Always explicitly return the validated value from a field_validator method. If you modify the value, return the modified version. If
you only validate without transformation, return the original value.
from pydantic import BaseModel, field_validator
class UserModel(BaseModel):
name: str
@field_validator("name")
@classmethod
def clean_name(cls, v):
v = v.lower().strip() # Noncompliant
from pydantic import BaseModel, field_validator
class UserModel(BaseModel):
name: str
@field_validator("name")
@classmethod
def clean_name(cls, v):
return v.lower().strip()