搜索

PythonReactSEOPDF
GitHub Skill

pydantic-basesettings-class-attributes

Use when defining constants or mappings in Pydantic BaseSettings or BaseModel subclasses results in "non-annotated attribute" errors requiring ClassVar annotations or module-level constants.

dragonkid☆ 1 仓库 Stars1 仓库 Forks

安装与使用

请根据来源仓库和你的 AI 工具说明安装此技能。先阅读技能文件和依赖要求,再添加到工作流。

查看来源 ↗使用指南

技能说明

Pydantic BaseSettings Class Attributes Pitfall

Overview

When defining class attributes in Pydantic BaseSettings classes, Pydantic treats them as model fields and raises an error. Move constants outside the class as module-level private constants or use ClassVar annotation.

When to Use

  • Defining constants in Pydantic BaseSettings or BaseModel subclasses
  • Refactoring hardcoded mappings/configs into reusable data structures
  • Encountering "non-annotated attribute" errors

The Problem

Pydantic treats class attributes as model fields:

PydanticUserError: A non-annotated attribute was detected: `MAPPING = {...}`.
All model fields require a type annotation; if `MAPPING` is not meant to be a field,
you may be able to resolve this error by annotating it as a `ClassVar`

Solution

Recommended: Move constants outside the class as module-level private constants

# Correct approach
_APOLLO_MAPPING = {
    "grok.api.key": "grok_api_key",
    "remote.timeout": "timeout_seconds",
}

_BOOLEAN_FIELDS = ["debug", "enabled"]

class Settings(BaseSettings):
    grok_api_key: str = ""
    timeout_seconds: int = 30

    @model_validator(mode="before")
    @classmethod
    def load_from_apollo(cls, data):
        for apollo_key, field in _APOLLO_MAPPING.items():
            ...

Alternative: Use ClassVar type annotation (works but less clean)

from typing import ClassVar

class Settings(BaseSettings):
    MAPPING: ClassVar[dict[str, str]] = {...}

Common Mistakes

  • Defining mappings/constants directly in Pydantic classes without annotation
  • Using ClassVar when module-level constants would be cleaner
  • Forgetting that Pydantic validates all class attributes by default

使用示例

查看来源仓库中的使用示例与配置说明。

查看来源 ↗

来源历史

收录时间
2026-03-11
索引更新时间
2026-03-11
Branch
main

收录与同步日期属于本站记录。源码修改历史请查看来源仓库。

GitHub ↗

chat Comments (0)

chat_bubble_outline

No comments yet. Be the first to share your thoughts!