コンテンツにスキップ

Pydantic Plugins

Experimental feature

プラグインのサポートは実験的なものであり、マイナーリリースで変更される可能性があります。 プラグインの開発は、機能が安定するまでお勧めしません。

Pydanticでは、ユーザーがライブラリの機能を拡張するために使用できるプラグインを作成できる。

プラグインはPythonのエントリポイントを介してインストールされます。 エントリポイントの詳細については、Python Packaging AuthorityのEntry points specificationを参照してください。

my-pydantic-pluginという名前のプロジェクトがある場合は、pyproject.tomlに以下を追加してプラグインを作成できます。

[project.entry-points.pydantic]
my_plugin = "my_pydantic_plugin:plugin"

エントリポイントグループはpydanticmy_pluginはプラグインの名前、my_pydantic_pluginはプラグインオブジェクトをロードするモジュール、pluginはロードするオブジェクトの名前です。

プラグインは検出された順序でロードされ、検出された順序は保証されません。

ユーザは、plugin_settingsModel Config引数またはクラスキーワード引数を使用して、BaseModel内のプラグインの動作を変更できます。 この引数は、すべてのプラグインにそのまま渡される設定のディクショナリを取ります。 プラグインは、これらの設定を使用して動作を変更できます。 プラグインの設定は、plugin_settingsディクショナリ内のプラグイン固有のキー内の専用キーに分離することをお勧めします。

from pydantic import BaseModel


class Foo(BaseModel, plugin_settings={'my-plugin': {'observe': 'all'}}): ...

Build a plugin

API Documentation

pydantic.plugin

Pydanticはプラグインを作成するためのAPIを提供しています。このAPIはpydantic.pluginモジュールを介して公開されます。

プラグインでは、次のメソッドを_wrap_できます。

  • validate_python: Pythonオブジェクトからのデータを検証するために使用します。
  • validate_json: JSON文字列からデータを検証するために使用されます。
  • validate_strings: 文字列からデータを検証するために使用されます。

各メソッドに対して、次のコールバックを実装できます。

  • on_enter: フィールドの検証が始まる前に呼び出されます。
  • on_success: フィールドの検証が成功したときに呼び出されます。
  • on_error: フィールドの検証が失敗したときに呼び出されます。

SchemaValidatorvalidate_pythonメソッドを_ラップ_するプラグインの例を見てみましょう。

from typing import Any, Dict, Optional, Union

from pydantic_core import CoreConfig, CoreSchema, ValidationError

from pydantic.plugin import (
    NewSchemaReturns,
    PydanticPluginProtocol,
    SchemaKind,
    SchemaTypePath,
    ValidatePythonHandlerProtocol,
)


class OnValidatePython(ValidatePythonHandlerProtocol):
    def on_enter(
        self,
        input: Any,
        *,
        strict: Optional[bool] = None,
        from_attributes: Optional[bool] = None,
        context: Optional[Dict[str, Any]] = None,
        self_instance: Optional[Any] = None,
    ) -> None:
        print(input)

    def on_success(self, result: Any) -> None:
        print(result)

    def on_error(self, error: ValidationError) -> None:
        print(error.json())


class Plugin(PydanticPluginProtocol):
    def new_schema_validator(
        self,
        schema: CoreSchema,
        schema_type: Any,
        schema_type_path: SchemaTypePath,
        schema_kind: SchemaKind,
        config: Union[CoreConfig, None],
        plugin_settings: Dict[str, object],
    ) -> NewSchemaReturns:
        return OnValidatePython(), None, None


plugin = Plugin()

Using Plugin Settings

"observer"という設定というプラグインがあるとします。次のように使用できます。

from pydantic import BaseModel


class Foo(BaseModel, plugin_settings={'observer': 'all'}): ...

検証の呼び出しごとに、イベント用に登録された呼び出し可能オブジェクトにplugin_settingsが渡されます。

Disabling Plugins

環境変数PYDANTIC_DISABLE_PLUGINSを使用して、すべてまたは特定のプラグインを無効にすることができます。

Environment Variable Allowed Values Description
PYDANTIC_DISABLE_PLUGINS __all__, 1, true Disables all plugins
Comma-separated string (e.g. my-plugin-1,my-plugin2) Disables specified plugin(s)