Coverage for sources/frigid/modules.py: 100%

15 statements  

« prev     ^ index     » next       coverage.py v7.6.8, created at 2024-12-05 03:04 +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''' Immutable modules. 

22 

23 Provides a module type that enforces complete attribute immutability. 

24 This helps ensure that module-level constants remain constant and that 

25 module interfaces remain stable during runtime. 

26 

27 The module implementation is derived from :py:class:`types.ModuleType` and 

28 adds immutability. This makes it particularly useful for: 

29 

30 * Ensuring constants remain constant 

31 * Preventing modification of module interfaces 

32 

33 Also provides a convenience function: 

34 

35 * ``reclassify_modules``: Converts existing modules to immutable modules. 

36''' 

37 

38 

39from . import __ 

40 

41 

42class Module( __.Module ): 

43 ''' Immutable modules. ''' 

44 

45 def __delattr__( self, name: str ) -> None: 

46 from .exceptions import AttributeImmutabilityError 

47 raise AttributeImmutabilityError( name ) 

48 

49 def __setattr__( self, name: str, value: __.a.Any ) -> None: 

50 from .exceptions import AttributeImmutabilityError 

51 raise AttributeImmutabilityError( name ) 

52 

53Module.__doc__ = __.generate_docstring( 

54 Module, 'description of module', 'module attributes immutability' ) 

55 

56 

57def reclassify_modules( 

58 attributes: __.cabc.Mapping[ str, __.a.Any ], 

59 to_class: type[ Module ] = Module 

60) -> None: 

61 ''' Reclassifies modules in dictionary with custom module type. ''' 

62 from inspect import ismodule 

63 for attribute in attributes.values( ): 

64 if not ismodule( attribute ): continue 

65 if isinstance( attribute, to_class ): continue 

66 attribute.__class__ = to_class