new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Pydantic · Concepts · all subjects

strict mode

19 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Strict mode conversion rules

Pydantic distinguishes between strict and lax validation modes when performing type conversions. The conversion table shows which conversions are permitted in each mode through a Strict column with checkmarks indicating allowed conversions in Strict Mode.

strict parameter for field validation

The strict parameter of Field() specifies whether a field should be validated in strict mode. Example: name: str = Field(strict=True) validates strictly, while age: int = Field(strict=False) validates in lax mode and accepts strings like '42'. strict=False is the default.

Strict mode behavior differs between model_validate_json and model_validate

When strict mode is enabled, model_validate_json will coerce JSON types (strings to dates, arrays to tuples), but model_validate will reject the same Python values and raise validation errors. JSON parsing has special coercion rules even in strict mode.

Strict mode example: int validation fails on string

When validating {'x': '123'} with strict=True on an int field, Pydantic raises a ValidationError with message 'Input should be a valid integer [type=int_type, input_value='123', input_type=str]', whereas in lax mode it converts the string to 123.

Strict mode enabled at validation call level

Strict mode can be enabled on a per-validation-call basis when using validation methods on Pydantic models and type adapters, such as with model_validate(strict=True) or TypeAdapter.validate_python(strict=True).

Strict mode example: date validation from string

TypeAdapter(date).validate_python('2000-01-01') succeeds in lax mode returning 2000-01-01, but fails in strict mode with ValidationError. However, TypeAdapter(date).validate_json('"2000-01-01"', strict=True) succeeds because strict mode is looser when validating from JSON.

Field-level strict mode with Field()

Strict mode can be enabled on specific fields by setting the strict parameter of the Field() function to True. Strict mode will be applied for such fields even when validation methods are called in lax mode.

Annotated pattern for field-level strict mode

The strict constraint can also be applied using the annotated pattern: Annotated[int, Field(strict=True)].

Strict metadata class for annotated pattern

Pydantic provides the Strict metadata class meant to be used with the annotated pattern as an alternative to the Field() function. It also provides convenience aliases for common types: StrictBool, StrictInt, StrictFloat, StrictStr, and StrictBytes.

Strict metadata usage example

Example: from typing import Annotated; from pydantic import BaseModel, Strict, StrictInt; class User(BaseModel): id: Annotated[UUID, Strict()]; age: StrictInt. StrictInt is equivalent to Annotated[int, Strict()].

Model-level strict mode configuration

Strict mode behavior can be controlled at the configuration level using ConfigDict(strict=True). When used on a Pydantic model, strictness can still be overridden at the field level.

Model-level strict mode with field override example

Example: class User(BaseModel): model_config = ConfigDict(strict=True); name: str; age: int = Field(strict=False). This enables strict mode globally but disables it for the age field, allowing User(name='John', age='18') to succeed with age coerced to 18.

JSON input less strict than Python input in strict mode

Date and time types allow strings even in strict mode when validating from JSON, whereas they reject strings when validating from Python objects in strict mode.

Three ways to enable strict mode

Strict mode can be enabled in three ways: as a validation parameter (such as when using model_validate(strict=True)), at the field level (using Field(strict=True) or Annotated with Strict()), and at the configuration level (using ConfigDict(strict=True)).

Field-level strict mode example

Example: class User(BaseModel): name: str; age: int = Field(strict=True). When creating another_user = User(name='John', age='42'), it raises ValidationError because age field is strict and rejects string '42'.

Default Pydantic behavior: type coercion

By default, Pydantic attempts to coerce values to the desired type when possible. For example, the string '123' can be passed as input for an int type and will be converted to the value 123.

Strict mode reduces coercion leniency

When strict mode is enabled, Pydantic will be much less lenient when coercing data and will instead error if the data is not of the correct type. Most of the time, strict mode will only allow instances of the type to be provided, although looser rules may apply to JSON input.

validate_call strict mode configuration

Type coercion by validate_call can be disabled by enabling strict mode through custom configuration, which can be useful when coercion is not desired or might be confusing.

Type coercion in non-strict mode

Unless using strict mode, Pydantic applies type coercion in most cases. For example, a field typed as int accepts strings like '123', and list[str] accepts tuples and sets.

Give your agent this brain