Coverage for src/bioimageio/core/_common_annotations.py: 100%

19 statements  

« prev     ^ index     » next       coverage.py v7.14.2, created at 2026-06-22 16:54 +0000

1from __future__ import annotations 

2 

3from types import MappingProxyType 

4from typing import ( 

5 Annotated, 

6 Any, 

7 Hashable, 

8 Mapping, 

9 TypeVar, 

10) 

11 

12import pydantic 

13from pydantic_core.core_schema import ( 

14 CoreSchema, 

15 chain_schema, 

16 is_instance_schema, 

17 json_or_python_schema, 

18 no_info_plain_validator_function, 

19 plain_serializer_function_ser_schema, 

20) 

21from typing_extensions import get_args 

22 

23from .common import PerMember 

24 

25_K = TypeVar("_K", bound=Hashable) 

26_V = TypeVar("_V") 

27 

28 

29def _validate_from_mapping(d: Mapping[_K, _V]) -> MappingProxyType[_K, _V]: 

30 return MappingProxyType(dict(d)) 

31 

32 

33class PydanticMappingProxyAnnotation: 

34 @classmethod 

35 def __get_pydantic_core_schema__( 

36 cls, source_type: Any, handler: pydantic.GetCoreSchemaHandler 

37 ) -> CoreSchema: 

38 

39 k_type, v_type = get_args(source_type) 

40 mapping_proxy_schema = chain_schema( 

41 [ 

42 handler.generate_schema(dict[k_type, v_type]), 

43 no_info_plain_validator_function(_validate_from_mapping), 

44 is_instance_schema(MappingProxyType), 

45 ] 

46 ) 

47 return json_or_python_schema( 

48 json_schema=mapping_proxy_schema, 

49 python_schema=mapping_proxy_schema, 

50 serialization=plain_serializer_function_ser_schema(dict), 

51 ) 

52 

53 

54_T = TypeVar("_T") 

55 

56PerMemberAnno = Annotated[PerMember[_T], PydanticMappingProxyAnnotation]