[Python] Pydantic model fails with doctest on timestamp

Discussão em 'Python' iniciado por Stack, Junho 10, 2025.

  1. Stack

    Stack Membro Participativo

    that model may be pydantic correct

    """
    This module defines the User model using Pydantic's BaseModel.

    Example:
    >>> user_model = UserModel(id=1, name='Alice')
    >>> print(user_model)
    id=1 name='Alice'
    """
    from datetime import datetime
    from pydantic import BaseModel, Field, field_validator

    DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%f" # Format with microseconds

    class UserModel(BaseModel):
    """User model representing a user with an id and name.

    Attributes:
    id (int): The unique identifier for the user.
    name (str): The name of the user. Defaults to 'Jane Doe'.
    timestamp (str): Timestamp of the event in the format
    '%Y-%m-%dT%H:%M:%S.%f'. If None, the current time is used. Defaults
    to None.

    Example:
    >>> user_model = UserModel(
    ... id=1,
    ... name='Alice'
    ... )
    >>> user_model.model_dump_json()
    '{"id":1,"name":"Alice","timestamp":"..."}'
    """
    id: int
    name: str = 'Jane Doe'
    timestamp: str = Field(default_factory=lambda: datetime.now().strftime(DATETIME_FORMAT))

    @field_validator("timestamp")
    @classmethod
    def check_datetime_format(cls, value: str) -> str:
    """Validates the format of the timestamp.

    Ensures that the 'timestamp' value conforms to the defined DATETIME_FORMAT.

    Args:
    value: The timestamp string to validate.

    Returns:
    The validated timestamp string if the format is correct.

    Raises:
    ValueError: If the timestamp does not match the expected format.
    """
    try:
    datetime.strptime(value, DATETIME_FORMAT)
    return value
    except ValueError as exc:
    raise ValueError(
    f"The 'timestamp' field must have the format '{DATETIME_FORMAT}', received: '{value}'") from exc


    but fails with doctest as the timestamp is always different in the output for doctest. Is there a way to have proper doctstring with timestamp output which works also for doctest ?

    Continue reading...

Compartilhe esta Página