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

19 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-20 09:46 +0000

1from __future__ import annotations 

2 

3from collections.abc import Hashable, Mapping 

4from types import MappingProxyType 

5from typing import ( 

6 Annotated, 

7 Any, 

8 TypeVar, 

9 get_args, 

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) 

21 

22from .common import PerMember 

23 

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

25_V = TypeVar("_V") 

26 

27 

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

29 return MappingProxyType(dict(d)) 

30 

31 

32class PydanticMappingProxyAnnotation: 

33 @classmethod 

34 def __get_pydantic_core_schema__( 

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

36 ) -> CoreSchema: 

37 

38 k_type, v_type = get_args(source_type) 

39 mapping_proxy_schema = chain_schema( 

40 [ 

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

42 no_info_plain_validator_function(_validate_from_mapping), 

43 is_instance_schema(MappingProxyType), 

44 ] 

45 ) 

46 return json_or_python_schema( 

47 json_schema=mapping_proxy_schema, 

48 python_schema=mapping_proxy_schema, 

49 serialization=plain_serializer_function_ser_schema(dict), 

50 ) 

51 

52 

53_T = TypeVar("_T") 

54 

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