Validation API Reference¶
Data filters and validation decorators.
Filters¶
Base Filter¶
dspu.validation.filters.Filter
¶
Bases: ABC
Base class for all filters.
Filters are transformation functions that take an input value and return a modified version. They can be chained together using FilterChain.
Example
class MyFilter(Filter): ... def apply(self, value: Any) -> Any: ... return str(value).upper()
f = MyFilter() f("hello") 'HELLO'
Functions¶
apply
abstractmethod
¶
Apply the filter transformation to a value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
The input value to transform |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The transformed value |
then
¶
then(other: Filter) -> FilterChain
Chain this filter with another.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Filter
|
The filter to chain after this one |
required |
Returns:
| Type | Description |
|---|---|
FilterChain
|
A FilterChain combining both filters |
Example
strip = StripWhitespaceFilter() lower = LowercaseFilter() chain = strip.then(lower) chain(" HELLO ") 'hello'
Source code in src/dspu/validation/filters.py
Built-in Filters¶
dspu.validation.filters.StripWhitespaceFilter
¶
Bases: Filter
Remove leading and trailing whitespace from strings.
Example
f = StripWhitespaceFilter() f(" hello ") 'hello' f("\n\t test \n") 'test'
Functions¶
apply
¶
Strip whitespace from string value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Input value (converted to string) |
required |
Returns:
| Type | Description |
|---|---|
Any
|
String with whitespace stripped |
then
¶
then(other: Filter) -> FilterChain
Chain this filter with another.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Filter
|
The filter to chain after this one |
required |
Returns:
| Type | Description |
|---|---|
FilterChain
|
A FilterChain combining both filters |
Example
strip = StripWhitespaceFilter() lower = LowercaseFilter() chain = strip.then(lower) chain(" HELLO ") 'hello'
Source code in src/dspu/validation/filters.py
dspu.validation.filters.LowercaseFilter
¶
Bases: Filter
Convert strings to lowercase.
Example
f = LowercaseFilter() f("HELLO World") 'hello world'
Functions¶
apply
¶
Convert value to lowercase string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Input value (converted to string) |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Lowercase string |
then
¶
then(other: Filter) -> FilterChain
Chain this filter with another.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Filter
|
The filter to chain after this one |
required |
Returns:
| Type | Description |
|---|---|
FilterChain
|
A FilterChain combining both filters |
Example
strip = StripWhitespaceFilter() lower = LowercaseFilter() chain = strip.then(lower) chain(" HELLO ") 'hello'
Source code in src/dspu/validation/filters.py
dspu.validation.filters.UppercaseFilter
¶
Bases: Filter
Convert strings to uppercase.
Example
f = UppercaseFilter() f("hello world") 'HELLO WORLD'
Functions¶
apply
¶
Convert value to uppercase string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Input value (converted to string) |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Uppercase string |
then
¶
then(other: Filter) -> FilterChain
Chain this filter with another.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Filter
|
The filter to chain after this one |
required |
Returns:
| Type | Description |
|---|---|
FilterChain
|
A FilterChain combining both filters |
Example
strip = StripWhitespaceFilter() lower = LowercaseFilter() chain = strip.then(lower) chain(" HELLO ") 'hello'
Source code in src/dspu/validation/filters.py
dspu.validation.filters.TruncateFilter
¶
Bases: Filter
Truncate strings to a maximum length.
Attributes:
| Name | Type | Description |
|---|---|---|
max_length |
Maximum length of output string |
|
suffix |
Optional suffix to add to truncated strings |
Example
f = TruncateFilter(max_length=10) f("Hello World!") 'Hello Worl'
f = TruncateFilter(max_length=10, suffix="...") f("Hello World!") 'Hello W...'
Initialize truncate filter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_length
|
int
|
Maximum length of output string |
required |
suffix
|
str
|
Optional suffix to add when truncating (default: "") |
''
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If max_length is not positive |
Source code in src/dspu/validation/filters.py
Functions¶
apply
¶
Truncate string to maximum length.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Input value (converted to string) |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Truncated string |
Source code in src/dspu/validation/filters.py
then
¶
then(other: Filter) -> FilterChain
Chain this filter with another.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Filter
|
The filter to chain after this one |
required |
Returns:
| Type | Description |
|---|---|
FilterChain
|
A FilterChain combining both filters |
Example
strip = StripWhitespaceFilter() lower = LowercaseFilter() chain = strip.then(lower) chain(" HELLO ") 'hello'
Source code in src/dspu/validation/filters.py
dspu.validation.filters.RemoveSpecialCharsFilter
¶
Bases: Filter
Remove special characters from strings.
Keeps only alphanumeric characters and specified allowed characters.
Attributes:
| Name | Type | Description |
|---|---|---|
allowed_chars |
Set of additional characters to allow (besides alphanumeric) |
|
replacement |
Character to replace special characters with |
Example
f = RemoveSpecialCharsFilter() f("hello@world!") 'helloworld'
f = RemoveSpecialCharsFilter(allowed_chars={" ", "-"}) f("hello-world!") 'hello-world'
f = RemoveSpecialCharsFilter(replacement="") f("hello@world!") 'hello_world'
Initialize remove special chars filter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
allowed_chars
|
set[str] | None
|
Set of additional characters to allow (default: None) |
None
|
replacement
|
str
|
Character to replace special characters with (default: "") |
''
|
Source code in src/dspu/validation/filters.py
Functions¶
apply
¶
Remove special characters from string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Input value (converted to string) |
required |
Returns:
| Type | Description |
|---|---|
Any
|
String with special characters removed or replaced |
Source code in src/dspu/validation/filters.py
then
¶
then(other: Filter) -> FilterChain
Chain this filter with another.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Filter
|
The filter to chain after this one |
required |
Returns:
| Type | Description |
|---|---|
FilterChain
|
A FilterChain combining both filters |
Example
strip = StripWhitespaceFilter() lower = LowercaseFilter() chain = strip.then(lower) chain(" HELLO ") 'hello'
Source code in src/dspu/validation/filters.py
dspu.validation.filters.EmailNormalizationFilter
¶
Bases: Filter
Normalize email addresses.
Converts email to lowercase and removes dots from Gmail addresses (as Gmail ignores dots in the username part).
Example
f = EmailNormalizationFilter() f("John.Doe@Example.COM") 'johndoe@example.com'
f("test.user+tag@gmail.com") 'testuser@gmail.com'
Functions¶
apply
¶
Normalize email address.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Email address string |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Normalized email address |
Raises:
| Type | Description |
|---|---|
ValueError
|
If value is not a valid email format |
Source code in src/dspu/validation/filters.py
then
¶
then(other: Filter) -> FilterChain
Chain this filter with another.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Filter
|
The filter to chain after this one |
required |
Returns:
| Type | Description |
|---|---|
FilterChain
|
A FilterChain combining both filters |
Example
strip = StripWhitespaceFilter() lower = LowercaseFilter() chain = strip.then(lower) chain(" HELLO ") 'hello'
Source code in src/dspu/validation/filters.py
dspu.validation.filters.SlugifyFilter
¶
Bases: Filter
Convert strings to URL-friendly slugs.
Converts text to lowercase, replaces spaces and special characters with hyphens, and removes consecutive hyphens.
Attributes:
| Name | Type | Description |
|---|---|---|
separator |
Character to use as separator (default: "-") |
|
lowercase |
Whether to convert to lowercase (default: True) |
Example
f = SlugifyFilter() f("Hello World!") 'hello-world'
f(" Multiple Spaces ") 'multiple-spaces'
f = SlugifyFilter(separator="_", lowercase=False) f("Hello World!") 'Hello_World'
Initialize slugify filter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
separator
|
str
|
Character to use as separator (default: "-") |
'-'
|
lowercase
|
bool
|
Whether to convert to lowercase (default: True) |
True
|
Source code in src/dspu/validation/filters.py
Functions¶
apply
¶
Convert string to slug.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Input value (converted to string) |
required |
Returns:
| Type | Description |
|---|---|
Any
|
URL-friendly slug |
Source code in src/dspu/validation/filters.py
then
¶
then(other: Filter) -> FilterChain
Chain this filter with another.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Filter
|
The filter to chain after this one |
required |
Returns:
| Type | Description |
|---|---|
FilterChain
|
A FilterChain combining both filters |
Example
strip = StripWhitespaceFilter() lower = LowercaseFilter() chain = strip.then(lower) chain(" HELLO ") 'hello'
Source code in src/dspu/validation/filters.py
dspu.validation.filters.RegexReplaceFilter
¶
Bases: Filter
Replace text matching a regex pattern.
Attributes:
| Name | Type | Description |
|---|---|---|
pattern |
Regex pattern to match |
|
replacement |
String to replace matches with |
|
count |
Maximum number of replacements (0 = unlimited) |
Example
f = RegexReplaceFilter(r"\d+", "X") f("I have 123 apples and 456 oranges") 'I have X apples and X oranges'
f = RegexReplaceFilter(r"\d+", "X", count=1) f("I have 123 apples and 456 oranges") 'I have X apples and 456 oranges'
Initialize regex replace filter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern
|
str
|
Regex pattern to match |
required |
replacement
|
str
|
String to replace matches with |
required |
count
|
int
|
Maximum number of replacements (default: 0 = unlimited) |
0
|
Source code in src/dspu/validation/filters.py
Functions¶
apply
¶
Replace text matching regex pattern.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
Input value (converted to string) |
required |
Returns:
| Type | Description |
|---|---|
Any
|
String with replacements applied |
Source code in src/dspu/validation/filters.py
then
¶
then(other: Filter) -> FilterChain
Chain this filter with another.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Filter
|
The filter to chain after this one |
required |
Returns:
| Type | Description |
|---|---|
FilterChain
|
A FilterChain combining both filters |
Example
strip = StripWhitespaceFilter() lower = LowercaseFilter() chain = strip.then(lower) chain(" HELLO ") 'hello'
Source code in src/dspu/validation/filters.py
Filter Chain¶
dspu.validation.filters.FilterChain
¶
FilterChain(filters: list[Filter])
Bases: Filter
Chain multiple filters together.
Applies filters in sequence, passing the output of each filter as the input to the next.
Attributes:
| Name | Type | Description |
|---|---|---|
filters |
List of filters to apply in order |
Example
chain = FilterChain([ ... StripWhitespaceFilter(), ... LowercaseFilter(), ... TruncateFilter(max_length=10) ... ]) chain(" HELLO WORLD ") 'hello worl'
Initialize filter chain.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filters
|
list[Filter]
|
List of filters to apply in sequence |
required |
Source code in src/dspu/validation/filters.py
Functions¶
apply
¶
Apply all filters in sequence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Any
|
The input value to transform |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The transformed value after all filters applied |
Source code in src/dspu/validation/filters.py
then
¶
then(other: Filter) -> FilterChain
Add another filter to the chain.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Filter
|
The filter to add to the end of the chain |
required |
Returns:
| Type | Description |
|---|---|
FilterChain
|
A new FilterChain with the additional filter |
Source code in src/dspu/validation/filters.py
Pydantic Integration¶
dspu.validation.validators.pydantic_filter_validator
¶
pydantic_filter_validator(
filter_func: Filter | FilterChain,
) -> Callable[[Any], Any]
Create a Pydantic field validator from a filter.
This allows using dspu filters as Pydantic field validators.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filter_func
|
Filter | FilterChain
|
Filter or FilterChain to use for validation |
required |
Returns:
| Type | Description |
|---|---|
Callable[[Any], Any]
|
Pydantic validator function |
Raises:
| Type | Description |
|---|---|
ImportError
|
If Pydantic is not installed |
Example
from pydantic import BaseModel, field_validator
class User(BaseModel): ... email: str ... name: str ... ... _validate_email = field_validator("email", mode="before")( ... pydantic_filter_validator(EmailNormalizationFilter()) ... ) ... _validate_name = field_validator("name", mode="before")( ... pydantic_filter_validator( ... FilterChain([StripWhitespaceFilter(), TruncateFilter(50)]) ... ) ... )
user = User(email="John.Doe@GMAIL.COM", name=" John Doe ") user.email 'johndoe@gmail.com' user.name 'John Doe'
Source code in src/dspu/validation/validators.py
dspu.validation.validators.FilteredModel
¶
Bases: BaseModel
Base Pydantic model with filter support.
Subclass this to automatically apply filters to fields using
a _filters class attribute.
Example
class User(FilteredModel): ... email: str ... name: str ... ... _filters = { ... "email": EmailNormalizationFilter(), ... "name": FilterChain([ ... StripWhitespaceFilter(), ... TruncateFilter(max_length=50) ... ]) ... }
user = User(email="John.Doe@GMAIL.COM", name=" John Doe ") user.email 'johndoe@gmail.com'
Functions¶
apply_filters_wrap
classmethod
¶
Apply filters before validation using wrap mode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
Any
|
Input values |
required |
handler
|
Any
|
Validation handler |
required |
Returns:
| Type | Description |
|---|---|
Any
|
Validated model instance |
Raises:
| Type | Description |
|---|---|
ImportError
|
If Pydantic is not installed |
Source code in src/dspu/validation/validators.py
Decorators¶
dspu.validation.validators.validate_field
¶
validate_field(
*filters: Filter, field_name: str | None = None
) -> Callable[[F], F]
Decorator to validate and transform a specific function argument.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*filters
|
Filter
|
Filters to apply to the field value |
()
|
field_name
|
str | None
|
Name of the parameter to validate (if None, validates first param) |
None
|
Returns:
| Type | Description |
|---|---|
Callable[[F], F]
|
Decorated function that applies filters to the specified field |
Example
@validate_field(StripWhitespaceFilter(), LowercaseFilter()) ... def process_email(email: str) -> str: ... return email
process_email(" USER@EXAMPLE.COM ") 'user@example.com'
Source code in src/dspu/validation/validators.py
dspu.validation.validators.validate
¶
validate(
*,
input_filters: dict[str, Filter | FilterChain]
| None = None,
output_filter: Filter | FilterChain | None = None,
) -> Callable[[F], F]
Decorator to validate function inputs and outputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_filters
|
dict[str, Filter | FilterChain] | None
|
Dict mapping parameter names to filters |
None
|
output_filter
|
Filter | FilterChain | None
|
Filter to apply to function return value |
None
|
Returns:
| Type | Description |
|---|---|
Callable[[F], F]
|
Decorated function with validation applied |
Example
@validate( ... input_filters={ ... "email": EmailNormalizationFilter(), ... "name": FilterChain([ ... StripWhitespaceFilter(), ... TruncateFilter(max_length=50) ... ]) ... }, ... output_filter=StripWhitespaceFilter() ... ) ... def create_user(email: str, name: str) -> str: ... return f"{name} <{email}>"
create_user("John.Doe@GMAIL.COM", " John Doe ") 'John Doe johndoe@gmail.com'
Source code in src/dspu/validation/validators.py
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 | |
Usage¶
from dspu.validation import StripWhitespaceFilter, LowercaseFilter, EmailNormalizationFilter
# Compose filters
email_filter = (
StripWhitespaceFilter()
.then(LowercaseFilter())
.then(EmailNormalizationFilter())
)
# Apply
clean_email = email_filter(" Alice@GMAIL.COM ")
# Result: "alice@gmail.com"
# Pydantic integration
from pydantic import BaseModel
class User(BaseModel):
email: str
_email_filter = pydantic_filter_validator("email", email_filter)
user = User(email=" ALICE@EXAMPLE.COM ")
# Automatically cleaned: "alice@example.com"