Skip to content

FieldSpec

The internal field declaration object that all field factories (String(), Integer(), etc.) return. A FieldSpec holds the field type, constraints, and configuration until the element class is finalized.

Domain-native field declaration carrier.

A FieldSpec records the user's intent (String(max_length=50)) and translates it into a Pydantic Annotated[type, Field(...)] during class creation. It is not a descriptor (it has no __get__ or __set__) and is discarded after the class is built.

Source code in src/protean/fields/spec.py
 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
def __init__(
    self,
    python_type: type,
    *,
    # Field kind marker (for adapter-layer discrimination)
    field_kind: str = "standard",  # "standard", "text", "identifier", "auto"
    # Common arguments
    required: bool = False,
    default: Any = _UNSET,
    identifier: bool = False,
    unique: bool = False,
    choices: type[Enum]
    | list[Any]
    | tuple[Any, ...]
    | None = None,  # supports Enum classes too
    description: str = "",
    referenced_as: str | None = None,
    # Type-specific constraints
    max_length: int | None = None,
    min_length: int | None = None,
    max_value: float | decimal.Decimal | None = None,
    min_value: float | decimal.Decimal | None = None,
    # Decimal-specific, mapped to NUMERIC with this precision and scale
    precision: int | None = None,
    scale: int | None = None,
    # Container-specific
    content_type: Any = None,  # For List fields
    # Sanitization — tri-state for String/Text: True (always clean),
    # False (never), None (unset → consult the domain-level
    # ``[field_defaults] sanitize`` default, which itself defaults to
    # False). Other field kinds never expose this and stay unset.
    sanitize: bool | None = None,  # For String/Text — runs bleach.clean()
    # Lifecycle timestamps (DateTime/Date only) — Django-parity flags that
    # let the persistence layer stamp the field on save.
    auto_now_add: bool = False,  # set to now() on the CREATE save
    auto_now: bool = False,  # set to now() on every save (create + update)
    # Validators
    validators: Iterable[Callable[..., Any]] = (),  # Per-field validator callables
    # Error messages
    error_messages: dict[str, str] | None = None,
    # Status transitions
    transitions: dict[Any, Any]
    | None = None,  # For Status fields — {state: [allowed_targets]}
    # Deprecation metadata
    deprecated: str | dict[str, Any] | None = None,
    # Old field name(s) this field was renamed from
    renamed_from: str | list[str] | tuple[str, ...] | None = None,
) -> None:
    self.python_type = python_type
    self.field_kind = field_kind
    self.required = required
    self.default = default
    self.identifier = identifier
    self.unique = unique
    self.choices = choices
    self.description = description
    self.referenced_as = referenced_as
    self.max_length = max_length
    self.min_length = min_length
    self.max_value = max_value
    self.min_value = min_value
    self.precision = precision
    self.scale = scale
    self.content_type = content_type
    self.sanitize = sanitize
    self.auto_now_add = auto_now_add
    self.auto_now = auto_now
    self.validators = list(validators)
    self.error_messages = error_messages
    self.transitions = (
        self._normalize_transitions(transitions) if transitions else None
    )
    self._auto_generated = False
    self.deprecated = _normalize_deprecated(deprecated)
    self.renamed_from = normalize_field_renamed_from(renamed_from)

    # Warn if required=True with an explicit default
    if self.required and self.default is not _UNSET:
        warnings.warn(
            "Field declared with required=True and an explicit default. "
            "The default will be honored; the field is effectively not required.",
            stacklevel=3,
        )

    # auto_now / auto_now_add are Django-parity, save-time stamps and only
    # apply to temporal fields. They are mutually exclusive.
    if self.auto_now or self.auto_now_add:
        if self.python_type not in (_dt.datetime, _dt.date):
            raise ProteanValidationError(
                {
                    "auto_now": [
                        (
                            "auto_now/auto_now_add are only supported on "
                            "DateTime and Date fields"
                        )
                    ]
                }
            )
        if self.auto_now and self.auto_now_add:
            raise ProteanValidationError(
                {
                    "auto_now": [
                        (
                            "auto_now and auto_now_add are mutually exclusive: "
                            "auto_now stamps on every save, auto_now_add only on "
                            "create"
                        )
                    ]
                }
            )
        if self.required:
            raise ProteanValidationError(
                {
                    "auto_now": [
                        (
                            "auto_now/auto_now_add fields cannot be required: the "
                            "value is stamped at save time, so the field must be "
                            "optional (drop required=True)"
                        )
                    ]
                }
            )

resolve_type

resolve_type() -> Any

Return the Python type annotation for Pydantic.

Handles choices → Literal, and optional wrapping.

Source code in src/protean/fields/spec.py
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
def resolve_type(self) -> Any:
    """Return the Python type annotation for Pydantic.

    Handles choices → Literal, and optional wrapping.
    """
    resolved: Any = self.python_type

    # If choices is set, replace with Literal
    if self.choices is not None:
        if isinstance(self.choices, type) and issubclass(self.choices, Enum):
            choices_values = tuple(item.value for item in self.choices)
        else:
            choices_values = tuple(self.choices)
        resolved = Literal[choices_values]

    # A custom field carries its type's validators and serializers on the
    # spec; attach them here so Pydantic gets a type it can parse.
    custom_metadata = getattr(self, "_custom_metadata", ())
    if custom_metadata:
        resolved = Annotated[(resolved, *custom_metadata)]

    # Wrap in Optional when not required, no explicit default, and not identifier.
    # Auto-increment identifiers are also Optional since the DAO assigns
    # the actual integer value at persistence time.
    is_increment_id = self.identifier and getattr(self, "_increment", False)
    if (
        not self.required
        and self.default is _UNSET
        and (not self.identifier or is_increment_id)
    ):
        resolved = resolved | None

    return resolved

resolve_field_kwargs

resolve_field_kwargs() -> dict[str, Any]

Return the kwargs dict for pydantic.Field(...).

Source code in src/protean/fields/spec.py
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
def resolve_field_kwargs(self) -> dict[str, Any]:
    """Return the kwargs dict for ``pydantic.Field(...)``."""
    kwargs: dict[str, Any] = {}
    json_extra: dict[str, Any] = {}

    _add_length_and_value_bounds(self, kwargs)
    _add_decimal_precision(self, kwargs, json_extra)
    _add_identifier_default(self, kwargs, json_extra)
    _add_default(self, kwargs)

    # Description
    if self.description:
        kwargs["description"] = self.description

    _add_protean_metadata(self, json_extra)

    if json_extra:
        kwargs["json_schema_extra"] = json_extra

    return kwargs

resolve_annotated

resolve_annotated() -> Any

Combine resolved type and field kwargs into Annotated[type, Field(...)].

Per-field validators are appended as AfterValidator wrappers on the Annotated metadata. A sanitization AfterValidator is appended for an explicit sanitize=True and for a String/Text field that leaves sanitize unset: the unset field cannot decide at build time whether it sanitizes, because that depends on the domain-level [field_defaults] sanitize default, which is only known at validation time. So the unset field carries the validator and the validator returns the value untouched when the domain default is off. Only an explicit sanitize=False gets no validator at all.

Source code in src/protean/fields/spec.py
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
def resolve_annotated(self) -> Any:
    """Combine resolved type and field kwargs into ``Annotated[type, Field(...)]``.

    Per-field ``validators`` are appended as ``AfterValidator`` wrappers on
    the ``Annotated`` metadata. A sanitization ``AfterValidator`` is appended
    for an explicit ``sanitize=True`` *and* for a String/Text field that
    leaves ``sanitize`` unset: the unset field cannot decide at build time
    whether it sanitizes, because that depends on the domain-level
    ``[field_defaults] sanitize`` default, which is only known at validation
    time. So the unset field carries the validator and the validator returns
    the value untouched when the domain default is off. Only an explicit
    ``sanitize=False`` gets no validator at all.
    """
    resolved_type = self.resolve_type()
    field_kwargs = self.resolve_field_kwargs()
    pydantic_field = PydanticField(**field_kwargs)

    extra_validators: list[Any] = _type_coercion_validators(self)

    sanitize_validator = _sanitize_after_validator(self)
    if sanitize_validator is not None:
        extra_validators.append(sanitize_validator)

    # Per-field validators via AfterValidator
    if self.validators:
        extra_validators.append(
            AfterValidator(_make_protean_validators_runner(list(self.validators)))
        )

    if extra_validators:
        return Annotated[
            resolved_type,
            pydantic_field,
            *extra_validators,
        ]
    return Annotated[resolved_type, pydantic_field]