Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pydantic/plugin/_loader.py: 66%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

32 statements  

1from __future__ import annotations 

2 

3import os 

4import warnings 

5from collections.abc import Iterable 

6from importlib.metadata import entry_points 

7from typing import TYPE_CHECKING, Final 

8 

9if TYPE_CHECKING: 

10 from . import PydanticPluginProtocol 

11 

12 

13PYDANTIC_ENTRY_POINT_GROUP: Final[str] = 'pydantic' 

14 

15# cache of plugins 

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

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 

20 

21 

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

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') 

29 global _plugins, _loading_plugins 

30 if _loading_plugins: 

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

32 return () 

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

34 return () 

35 elif _plugins is None: 

36 _plugins = {} 

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

38 _loading_plugins = True 

39 try: 

40 for entry_point in entry_points(group=PYDANTIC_ENTRY_POINT_GROUP): 

41 if entry_point.value in _plugins: 

42 continue 

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

44 continue 

45 try: 

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

47 except (ImportError, AttributeError) as e: 

48 warnings.warn( 

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 

55 

56 return _plugins.values()