Fields API Reference¶
This page provides API documentation for the pydapter.fields
module.
Installation¶
Overview¶
The fields module provides tools for building robust, reusable model definitions:
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Field │ │ FieldTemplate │ │ FieldFamilies │
│ (Descriptor) │ │ (Reusable) │ │ (Collections) │
└─────────────────┘ └─────────────────┘ └─────────────────┘
┌─────────────────┐ ┌─────────────────┐
│DomainModelBuilder│ │ValidationPatterns│
│ (Fluent API) │ │ (Validators) │
└─────────────────┘ └─────────────────┘
Quick Start¶
from pydapter.fields import DomainModelBuilder, FieldTemplate
# Build models with field families
User = (
DomainModelBuilder("User")
.with_entity_fields() # id, created_at, updated_at
.with_audit_fields() # created_by, updated_by, version
.add_field("name", FieldTemplate(base_type=str))
.add_field("email", FieldTemplate(base_type=str))
.build()
)
Field Templates¶
from pydapter.fields import FieldTemplate
# Reusable field configuration
email_template = FieldTemplate(
base_type=str,
description="Email address",
validator=lambda cls, v: v.lower()
)
# Create variations
user_email = email_template.create_field("user_email")
optional_email = email_template.as_nullable()
email_list = email_template.as_listable()
Field Families¶
from pydapter.fields import FieldFamilies
# Pre-defined collections
entity_fields = FieldFamilies.ENTITY # id, created_at, updated_at
audit_fields = FieldFamilies.AUDIT # created_by, updated_by, version
soft_delete_fields = FieldFamilies.SOFT_DELETE # deleted_at, is_deleted
Model Creation¶
from pydapter.fields import create_model, Field
# Create models with field lists
fields = [
Field(name="id", annotation=str),
Field(name="name", annotation=str),
Field(name="email", annotation=str)
]
User = create_model("User", fields=fields)
API Reference¶
Core Types¶
pydapter.fields.types
¶
Classes¶
Field
¶
Field descriptor for Pydantic models.
Source code in src/pydapter/fields/types.py
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 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 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 |
|
Functions¶
__init__(name, annotation=Undefined, default=Undefined, default_factory=Undefined, title=Undefined, description=Undefined, examples=Undefined, exclude=Undefined, frozen=Undefined, validator=Undefined, validator_kwargs=Undefined, alias=Undefined, immutable=False, **extra_info)
¶
Initialize a field descriptor.
Source code in src/pydapter/fields/types.py
as_listable(strict=False, **kwargs)
¶
Create a copy of a field descriptor with a listable annotation.
This method does not check whether the field is already listable. If strict is True, the annotation will be converted to a list of the current annotation. Otherwise, the list is an optional type.
Source code in src/pydapter/fields/types.py
as_nullable(**kwargs)
¶
Create a copy of a field descriptor with a nullable annotation and None as default value.
WARNING: the new_field will have no default value, nor default_factory.
Source code in src/pydapter/fields/types.py
Functions¶
create_model(model_name, config=None, doc=None, base=None, fields=None, frozen=False)
¶
Create a new pydantic model basing on fields and base class.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_name
|
str
|
Name of the new model. |
required |
config
|
dict[str, Any]
|
Configuration dictionary for the model. |
None
|
doc
|
str
|
Documentation string for the model. |
None
|
base
|
type[BaseModel]
|
Base class to inherit from. |
None
|
fields
|
list[Field] | dict[str, Field | FieldTemplate]
|
List of fields or dict of field names to Field/FieldTemplate instances. |
None
|
frozen
|
bool
|
Whether the model should be immutable (frozen). |
False
|
Source code in src/pydapter/fields/types.py
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 |
|
pydapter.fields.template
¶
Classes¶
FieldTemplate
¶
Template for creating reusable field definitions with naming flexibility.
FieldTemplate provides a way to define field configurations that can be reused across multiple models with different field names. It supports Pydantic v2 Annotated types and provides compositional methods for creating nullable and listable variations.
Examples:
>>> # Create a reusable email field template
>>> email_template = FieldTemplate(
... base_type=EmailStr,
... description="Email address",
... title="Email"
... )
>>>
>>> # Use the template in different models with different names
>>> user_email = email_template.create_field("user_email")
>>> contact_email = email_template.create_field("contact_email")
>>>
>>> # Create variations
>>> optional_email = email_template.as_nullable()
>>> email_list = email_template.as_listable()
Source code in src/pydapter/fields/template.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 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 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 |
|
Functions¶
__init__(base_type, default=Undefined, default_factory=Undefined, title=Undefined, description=Undefined, examples=Undefined, exclude=Undefined, frozen=Undefined, validator=Undefined, validator_kwargs=Undefined, alias=Undefined, immutable=False, **pydantic_field_kwargs)
¶
Initialize a field template.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
base_type
|
type | Any
|
The base type for the field (can be Annotated) |
required |
default
|
Any
|
Default value for the field |
Undefined
|
default_factory
|
Callable | UndefinedType
|
Factory function for default value |
Undefined
|
title
|
str | UndefinedType
|
Title for the field |
Undefined
|
description
|
str | UndefinedType
|
Description for the field |
Undefined
|
examples
|
list | UndefinedType
|
Examples for the field |
Undefined
|
exclude
|
bool | UndefinedType
|
Whether to exclude the field from serialization |
Undefined
|
frozen
|
bool | UndefinedType
|
Whether the field is frozen |
Undefined
|
validator
|
Callable | UndefinedType
|
Validator function for the field |
Undefined
|
validator_kwargs
|
dict[Any, Any] | UndefinedType
|
Keyword arguments for the validator |
Undefined
|
alias
|
str | UndefinedType
|
Alias for the field |
Undefined
|
immutable
|
bool
|
Whether the field is immutable |
False
|
**pydantic_field_kwargs
|
Any
|
Additional Pydantic FieldInfo arguments |
{}
|
Source code in src/pydapter/fields/template.py
as_listable(strict=False)
¶
Create a listable version of this template.
Returns a new FieldTemplate where the base type can accept either a single value or a list of values (flexible mode), or only lists (strict mode).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
strict
|
bool
|
If True, only lists are accepted. If False (default), both single values and lists are accepted. |
False
|
Returns:
Type | Description |
---|---|
Self
|
A new FieldTemplate instance that accepts lists |
Examples:
>>> str_template = FieldTemplate(base_type=str)
>>> # Flexible mode: accepts "value" or ["value1", "value2"]
>>> flexible_list = str_template.as_listable(strict=False)
>>> # Strict mode: only accepts ["value1", "value2"]
>>> strict_list = str_template.as_listable(strict=True)
Source code in src/pydapter/fields/template.py
as_nullable()
¶
Create a nullable version of this template.
Returns a new FieldTemplate where the base type is modified to accept None values. The default value is set to None and any existing default_factory is removed. If the template has a validator, it's wrapped to handle None values.
Returns:
Type | Description |
---|---|
Self
|
A new FieldTemplate instance that accepts None values |
Examples:
>>> int_template = FieldTemplate(base_type=int, default=0)
>>> nullable_int = int_template.as_nullable()
>>> # nullable_int will have type Union[int, None] with default=None
Source code in src/pydapter/fields/template.py
copy(**kwargs)
¶
Create a copy of the template with updated values.
Source code in src/pydapter/fields/template.py
create_field(name, **overrides)
¶
Create a Field instance with the given name.
This method creates a new Field instance using the template's configuration combined with any overrides provided. The resulting Field can be used in pydapter's create_model function.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
The name for the field. Must be a valid Python identifier. |
required |
**overrides
|
Any
|
Keyword arguments to override template settings. Supported overrides include all Field constructor parameters like default, description, title, validator, etc. |
{}
|
Returns:
Type | Description |
---|---|
Field
|
A Field instance configured with the template settings and overrides. |
Raises:
Type | Description |
---|---|
ValueError
|
If the field name is not a valid Python identifier. |
TypeError
|
If there are conflicts between template settings and overrides. |
RuntimeError
|
If attempting to override a frozen field property. |
Examples:
>>> template = FieldTemplate(base_type=str, description="A string field")
>>> field = template.create_field("username", title="User Name")
>>> # field will have description from template and title from override
Source code in src/pydapter/fields/template.py
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 |
|
Specialized Fields¶
pydapter.fields.execution
¶
Classes¶
Execution
¶
Bases: BaseModel
Represents the execution state of an event.
Source code in src/pydapter/fields/execution.py
ExecutionStatus
¶
Bases: str
, Enum
Status states for tracking action execution progress.
Source code in src/pydapter/fields/execution.py
Field Collections¶
pydapter.fields.families
¶
Field Families - Predefined collections of field templates for core database patterns.
This module provides pre-configured field families that group commonly used fields together for database models. These families focus on core abstractions like entity tracking, soft deletion, and audit trails.
Classes¶
FieldFamilies
¶
Collection of predefined field template groups for core database patterns.
This class provides field families that represent common database patterns like entity tracking, soft deletion, and audit trails. These are foundational patterns that align with pydapter's core abstractions.
Source code in src/pydapter/fields/families.py
Functions¶
create_field_dict(*families, **overrides)
¶
Create a field dictionary by merging multiple field families.
This function takes multiple field families and merges them into a single dictionary of Pydantic fields. Later families override fields from earlier ones if there are naming conflicts.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*families
|
dict[str, FieldTemplate]
|
Variable number of field family dictionaries to merge |
()
|
**overrides
|
FieldTemplate
|
Individual field templates to add or override |
{}
|
Returns:
Type | Description |
---|---|
dict[str, Field]
|
Dict[str, Field]: A dictionary mapping field names to Pydantic Field instances |
Example
Source code in src/pydapter/fields/families.py
pydapter.fields.protocol_families
¶
Protocol Field Families - Field templates for protocol integration.
This module provides field families that correspond to pydapter protocols, enabling easy creation of models that implement specific protocol interfaces.
Classes¶
ProtocolFieldFamilies
¶
Field families for pydapter protocol compliance.
This class provides field template collections that match the requirements of various pydapter protocols. Using these families ensures your models will be compatible with protocol mixins and functionality.
Source code in src/pydapter/fields/protocol_families.py
Functions¶
create_protocol_model(name, *protocols, timezone_aware=True, base_fields=None, **extra_fields)
¶
Create a model with fields required by specified protocols (structural compliance).
This function creates a Pydantic model with fields required by the specified protocols. It provides STRUCTURAL compliance by including the necessary fields, but does NOT add behavioral methods from protocol mixins.
Note: This function only adds the fields required by protocols. If you need the behavioral methods (e.g., update_timestamp() from TemporalMixin), you must explicitly inherit from the corresponding mixin classes when defining your final model class.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
Name for the generated model class |
required |
*protocols
|
str | ProtocolType
|
Protocol names to implement. Supported values: - "identifiable" or IDENTIFIABLE: Adds id field - "temporal" or TEMPORAL: Adds created_at and updated_at fields - "embeddable" or EMBEDDABLE: Adds embedding field - "invokable" or INVOKABLE: Adds execution field - "cryptographical" or CRYPTOGRAPHICAL: Adds sha256 field |
()
|
timezone_aware
|
bool
|
If True, uses timezone-aware datetime fields (default: True) |
True
|
base_fields
|
dict[str, FieldTemplate] | None
|
Optional base field family to start with |
None
|
**extra_fields
|
FieldTemplate
|
Additional field templates to include |
{}
|
Returns:
Type | Description |
---|---|
type
|
A new Pydantic model class with protocol-compliant fields (structure only) |
Examples:
from pydapter.protocols import IDENTIFIABLE, TEMPORAL, EMBEDDABLE
# Create a model with ID and timestamps using constants
TrackedEntity = create_protocol_model(
"TrackedEntity",
IDENTIFIABLE,
TEMPORAL,
)
# Create an embeddable document
Document = create_protocol_model(
"Document",
IDENTIFIABLE,
TEMPORAL,
EMBEDDABLE,
title=NAME_TEMPLATE,
content=FieldTemplate(base_type=str),
)
# For event-like models, use the Event class directly:
from pydapter.protocols import Event
class CustomEvent(Event):
user_id: str
action: str
# To add behavioral methods, inherit from the mixins:
from pydapter.protocols import IdentifiableMixin, TemporalMixin
# First create the structure
_UserStructure = create_protocol_model(
"UserStructure",
"identifiable",
"temporal",
username=FieldTemplate(base_type=str)
)
# Then add behavioral mixins
class User(_UserStructure, IdentifiableMixin, TemporalMixin):
pass
# Now the model has both fields AND methods
user = User(username="test")
user.update_timestamp() # Method from TemporalMixin
Source code in src/pydapter/fields/protocol_families.py
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 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 |
|
Builders and Utilities¶
pydapter.fields.builder
¶
Domain Model Builder - Fluent API for creating models with field families.
This module provides a builder pattern implementation for creating database models using core field families and templates. It offers a fluent API that makes model creation more intuitive and less error-prone.
Classes¶
DomainModelBuilder
¶
Fluent builder for creating database models with field families.
This class provides a fluent API for building Pydantic models by composing core field families and individual field templates. It supports method chaining for a clean, readable syntax.
Examples:
# Create an entity with soft delete and audit fields
TrackedEntity = (
DomainModelBuilder("TrackedEntity")
.with_entity_fields(timezone_aware=True)
.with_soft_delete(timezone_aware=True)
.with_audit_fields()
.add_field("name", FieldTemplate(base_type=str, description="Entity name"))
.build()
)
# Create a simple versioned model
VersionedModel = (
DomainModelBuilder("VersionedModel")
.with_entity_fields()
.with_audit_fields()
.add_field("data", FieldTemplate(base_type=dict, default_factory=dict))
.build()
)
Source code in src/pydapter/fields/builder.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 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 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 |
|
Functions¶
__init__(model_name, **model_config)
¶
Initialize the builder with a model name.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_name
|
str
|
Name for the generated model class |
required |
**model_config
|
Any
|
Additional Pydantic model configuration options (e.g., orm_mode=True, validate_assignment=True) |
{}
|
Source code in src/pydapter/fields/builder.py
add_field(name, template, replace=True)
¶
Add or update a single field.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
Field name |
required |
template
|
FieldTemplate
|
FieldTemplate instance for the field |
required |
replace
|
bool
|
If True (default), replaces existing field with same name. If False, raises ValueError if field already exists. |
True
|
Returns:
Type | Description |
---|---|
DomainModelBuilder
|
Self for method chaining |
Raises:
Type | Description |
---|---|
ValueError
|
If field exists and replace=False |
Source code in src/pydapter/fields/builder.py
build(**extra_config)
¶
Build the Pydantic model with all configured fields.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
**extra_config
|
Any
|
Additional model configuration to merge with the configuration provided in init |
{}
|
Returns:
Type | Description |
---|---|
type[BaseModel]
|
A new Pydantic model class |
Raises:
Type | Description |
---|---|
ValueError
|
If no fields have been added to the builder |
Source code in src/pydapter/fields/builder.py
preview()
¶
Preview the fields that will be included in the model.
Returns:
Type | Description |
---|---|
dict[str, str]
|
Dictionary mapping field names to their descriptions |
Source code in src/pydapter/fields/builder.py
remove_field(name)
¶
Remove a field from the builder.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
name
|
str
|
Field name to remove |
required |
Returns:
Type | Description |
---|---|
DomainModelBuilder
|
Self for method chaining |
Raises:
Type | Description |
---|---|
KeyError
|
If field doesn't exist |
Source code in src/pydapter/fields/builder.py
remove_fields(*names)
¶
Remove multiple fields from the builder.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*names
|
str
|
Field names to remove |
()
|
Returns:
Type | Description |
---|---|
DomainModelBuilder
|
Self for method chaining |
Source code in src/pydapter/fields/builder.py
with_audit_fields()
¶
Add audit/tracking fields (created_by, updated_by, version).
Returns:
Type | Description |
---|---|
DomainModelBuilder
|
Self for method chaining |
with_entity_fields(timezone_aware=False)
¶
Add basic entity fields (id, created_at, updated_at).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
timezone_aware
|
bool
|
If True, uses timezone-aware datetime fields |
False
|
Returns:
Type | Description |
---|---|
DomainModelBuilder
|
Self for method chaining |
Source code in src/pydapter/fields/builder.py
with_family(family)
¶
Add a custom field family.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
family
|
dict[str, FieldTemplate]
|
Dictionary mapping field names to FieldTemplate instances |
required |
Returns:
Type | Description |
---|---|
DomainModelBuilder
|
Self for method chaining |
Source code in src/pydapter/fields/builder.py
with_soft_delete(timezone_aware=False)
¶
Add soft delete fields (deleted_at, is_deleted).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
timezone_aware
|
bool
|
If True, uses timezone-aware datetime for deleted_at |
False
|
Returns:
Type | Description |
---|---|
DomainModelBuilder
|
Self for method chaining |
Source code in src/pydapter/fields/builder.py
Functions¶
pydapter.fields.validation_patterns
¶
Validation Patterns - Common validation patterns for field templates.
This module provides pre-built validation patterns and constraint builders for creating field templates with consistent validation rules.
Classes¶
ValidationPatterns
¶
Common validation patterns for field templates.
This class provides regex patterns and validation functions for common field types like emails, URLs, phone numbers, etc. These can be used with FieldTemplate to create consistently validated fields.
Source code in src/pydapter/fields/validation_patterns.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 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 |
|
Functions¶
lowercase()
staticmethod
¶
Create a validator that converts strings to lowercase.
Source code in src/pydapter/fields/validation_patterns.py
normalize_whitespace()
staticmethod
¶
Create a validator that normalizes whitespace in strings.
Source code in src/pydapter/fields/validation_patterns.py
strip_whitespace()
staticmethod
¶
Create a validator that strips leading/trailing whitespace.
Source code in src/pydapter/fields/validation_patterns.py
titlecase()
staticmethod
¶
Create a validator that converts strings to title case.
Source code in src/pydapter/fields/validation_patterns.py
uppercase()
staticmethod
¶
Create a validator that converts strings to uppercase.
Source code in src/pydapter/fields/validation_patterns.py
validate_pattern(pattern, error_message)
staticmethod
¶
Create a validator function for a regex pattern.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pattern
|
Pattern[str]
|
Compiled regex pattern |
required |
error_message
|
str
|
Error message to show on validation failure |
required |
Returns:
Type | Description |
---|---|
Callable[[str], str]
|
A validator function that checks the pattern |
Source code in src/pydapter/fields/validation_patterns.py
Functions¶
create_pattern_template(pattern, base_type=str, description='Pattern-validated field', error_message=None, **kwargs)
¶
Create a FieldTemplate with pattern validation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pattern
|
str | Pattern[str]
|
Regex pattern (string or compiled Pattern) |
required |
base_type
|
type
|
Base type for the field (default: str) |
str
|
description
|
str
|
Field description |
'Pattern-validated field'
|
error_message
|
str | None
|
Custom error message for validation failures |
None
|
**kwargs
|
Any
|
Additional arguments for FieldTemplate |
{}
|
Returns:
Type | Description |
---|---|
FieldTemplate
|
A FieldTemplate with pattern validation |
Examples:
# Create a field for US phone numbers
us_phone = create_pattern_template(
ValidationPatterns.US_PHONE,
description="US phone number",
error_message="Invalid US phone number format"
)
# Create a field for slugs
slug_field = create_pattern_template(
r"^[a-z0-9]+(?:-[a-z0-9]+)*$",
description="URL-friendly slug",
error_message="Slug must contain only lowercase letters, numbers, and hyphens"
)
Source code in src/pydapter/fields/validation_patterns.py
create_range_template(base_type, *, gt=None, ge=None, lt=None, le=None, description='Range-constrained numeric field', **kwargs)
¶
Create a FieldTemplate with numeric range constraints.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
base_type
|
type[int] | type[float]
|
Either int or float |
required |
gt
|
int | float | None
|
Greater than constraint |
None
|
ge
|
int | float | None
|
Greater than or equal constraint |
None
|
lt
|
int | float | None
|
Less than constraint |
None
|
le
|
int | float | None
|
Less than or equal constraint |
None
|
description
|
str
|
Field description |
'Range-constrained numeric field'
|
**kwargs
|
Any
|
Additional arguments for FieldTemplate |
{}
|
Returns:
Type | Description |
---|---|
FieldTemplate
|
A FieldTemplate with range constraints |
Examples:
# Create a percentage field (0-100)
percentage = create_range_template(
float,
ge=0,
le=100,
description="Percentage value"
)
# Create an age field (0-150)
age = create_range_template(
int,
ge=0,
le=150,
description="Person's age"
)
# Create a temperature field (-273.15 to infinity)
temperature_celsius = create_range_template(
float,
gt=-273.15,
description="Temperature in Celsius"
)