Coverage for sources/absence/adapters.py: 100%

6 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-08-08 06:42 +0000

1# vim: set filetype=python fileencoding=utf-8: 

2# -*- coding: utf-8 -*- 

3 

4#============================================================================# 

5# # 

6# Licensed under the Apache License, Version 2.0 (the "License"); # 

7# you may not use this file except in compliance with the License. # 

8# You may obtain a copy of the License at # 

9# # 

10# http://www.apache.org/licenses/LICENSE-2.0 # 

11# # 

12# Unless required by applicable law or agreed to in writing, software # 

13# distributed under the License is distributed on an "AS IS" BASIS, # 

14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # 

15# See the License for the specific language governing permissions and # 

16# limitations under the License. # 

17# # 

18#============================================================================# 

19 

20 

21''' Helpers for adapting dataclass instances to Absential parameters.''' 

22 

23 

24from . import __ 

25from .exceptions import OperationValidityError as _OperationValidityError 

26 

27 

28def adapt_dataclass( 

29 obj: __.typx.Annotated[ 

30 object, 

31 __.ddoc.Doc( ''' Dataclass instance to adapt. ''' ), 

32 ], 

33 *, 

34 skip_value: __.typx.Annotated[ 

35 object, 

36 __.ddoc.Doc( ''' Field value to omit from result. ''' ), 

37 ] = None, 

38) -> dict[ str, __.typx.Any ]: 

39 ''' Extracts fields from a dataclass instance, skipping sentinel values. 

40 

41 Useful for bridging CLI dataclasses (which use None for "not 

42 provided") to functions with Absential parameters (which default 

43 to absent). Fields whose value matches skip_value by identity are 

44 omitted, allowing function defaults to apply. 

45 ''' 

46 if not __.dcls.is_dataclass( obj ) or isinstance( obj, type ): 

47 raise _OperationValidityError( 'adapt_dataclass' ) 

48 return { 

49 field.name: getattr( obj, field.name ) 

50 for field in __.dcls.fields( obj ) 

51 if getattr( obj, field.name ) is not skip_value 

52 }