Coverage for pycommons / ds / immutable_map.py: 100%

11 statements  

« prev     ^ index     » next       coverage.py v7.13.0, created at 2025-12-11 03:04 +0000

1"""An immutable version of the :class:`typing.Mapping` interface.""" 

2from types import MappingProxyType 

3from typing import Mapping, TypeVar 

4 

5from pycommons.types import type_error 

6 

7#: the type variable for mapping keys 

8K = TypeVar("K") 

9#: the type variable for mapping values 

10V = TypeVar("V") 

11 

12 

13def immutable_mapping(a: Mapping[K, V]) -> Mapping[K, V]: 

14 """ 

15 Create an immutable view of a `Mapping`. 

16 

17 :param a: the input `Mapping` 

18 :returns: an immutable view on the `Mapping` `a` (the view will change 

19 if `a` is changed, but you cannot change `a` via the view) 

20 

21 >>> x = {1: 1, 2: 7, 3: 8} 

22 >>> y = immutable_mapping(x) 

23 >>> x is y 

24 False 

25 >>> x == y 

26 True 

27 >>> x[1] == y[1] 

28 True 

29 >>> x[2] == y[2] 

30 True 

31 >>> x[3] == y[3] 

32 True 

33 >>> z = immutable_mapping(x) 

34 >>> x is z 

35 False 

36 >>> x == z 

37 True 

38 >>> y is z 

39 False 

40 >>> z = immutable_mapping(y) 

41 >>> x is z 

42 False 

43 >>> y is z 

44 True 

45 >>> x == z 

46 True 

47 >>> x[9] = 23 

48 >>> y[9] == x[9] 

49 True 

50 

51 >>> try: 

52 ... y[1] = 2 

53 ... except TypeError as te: 

54 ... print(te) 

55 'mappingproxy' object does not support item assignment 

56 

57 >>> try: 

58 ... immutable_mapping(5) 

59 ... except TypeError as e: 

60 ... print(e) 

61 a should be an instance of typing.Mapping but is int, namely 5. 

62 """ 

63 if not isinstance(a, Mapping): 

64 raise type_error(a, "a", Mapping) 

65 if isinstance(a, MappingProxyType): 

66 return a 

67 return MappingProxyType(a)