Coverage for pydantic / plugin / _loader.py: 95.24%

30 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-11-21 11:56 +0000

1from __future__ import annotations 1abcdefghijklsmnopqr

2 

3import os 1abcdefghijklsmnopqr

4import warnings 1abcdefghijklsmnopqr

5from collections.abc import Iterable 1abcdefghijklsmnopqr

6from importlib.metadata import entry_points 1abcdefghijklsmnopqr

7from typing import TYPE_CHECKING, Final 1abcdefghijklsmnopqr

8 

9if TYPE_CHECKING: 1abcdefghijklsmnopqr

10 from . import PydanticPluginProtocol 

11 

12 

13PYDANTIC_ENTRY_POINT_GROUP: Final[str] = 'pydantic' 1abcdefghijklsmnopqr

14 

15# cache of plugins 

16_plugins: dict[str, PydanticPluginProtocol] | None = None 1abcdefghijklsmnopqr

17# return no plugins while loading plugins to avoid recursion and errors while importing plugins 

18# this means that if plugins use pydantic 

19_loading_plugins: bool = False 1abcdefghijklsmnopqr

20 

21 

22def get_plugins() -> Iterable[PydanticPluginProtocol]: 1abcdefghijklsmnopqr

23 """Load plugins for Pydantic. 

24 

25 Plugins are discovered using the `pydantic` entry point group, as documented in 

26 https://packaging.python.org/en/latest/guides/creating-and-discovering-plugins/#using-package-metadata. 

27 """ 

28 disabled_plugins = os.getenv('PYDANTIC_DISABLE_PLUGINS') 1abcdefghijklsmnopqr

29 global _plugins, _loading_plugins 

30 if _loading_plugins: 30 ↛ 32line 30 didn't jump to line 32 because the condition on line 30 was never true1abcdefghijklsmnopqr

31 # this happens when plugins themselves use pydantic, we return no plugins 

32 return () 

33 elif disabled_plugins in ('__all__', '1', 'true'): 1abcdefghijklsmnopqr

34 return () 1abcdefghijklmnopqr

35 elif _plugins is None: 1abcdefghijklsmnopqr

36 _plugins = {} 1abcdefghijklsmnopqr

37 # set _loading_plugins so any plugins that use pydantic don't themselves use plugins 

38 _loading_plugins = True 1abcdefghijklsmnopqr

39 try: 1abcdefghijklsmnopqr

40 for entry_point in entry_points(group=PYDANTIC_ENTRY_POINT_GROUP): 1abcdefghijklsmnopqr

41 if entry_point.value in _plugins: 1abcdefghijklmnopqr

42 continue 1abcdefghijklmnopqr

43 if disabled_plugins is not None and entry_point.name in disabled_plugins.split(','): 1abcdefghijklmnopqr

44 continue 1abcdefghijklmnopqr

45 try: 1abcdefghijklmnopqr

46 _plugins[entry_point.value] = entry_point.load() 1abcdefghijklmnopqr

47 except (ImportError, AttributeError) as e: 1abcdefghijklmnopqr

48 warnings.warn( 1abcdefghijklmnopqr

49 f'{e.__class__.__name__} while loading the `{entry_point.name}` Pydantic plugin, ' 

50 f'this plugin will not be installed.\n\n{e!r}', 

51 stacklevel=2, 

52 ) 

53 finally: 

54 _loading_plugins = False 1abcdefghijklsmnopqr

55 

56 return _plugins.values() 1abcdefghijklsmnopqr