structured_data._cant_modify   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 24
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 4
eloc 14
dl 0
loc 24
rs 10
c 0
b 0
f 0

2 Functions

Rating   Name   Duplication   Size   Complexity  
A guard() 0 4 2
A cant_modify() 0 9 2
1
"""Helper funtion for common pseudo-immutable use case."""
2
3
import inspect
4
import typing
5
6
MISSING = object()
7
8
9
def cant_modify(self: typing.Any, name: str) -> None:
10
    """Prevent attempts to modify an attr of the given name."""
11
    class_repr = repr(self.__class__.__name__)
12
    name_repr = repr(name)
13
    if inspect.getattr_static(self, name, MISSING) is MISSING:
14
        format_msg = "{class_repr} object has no attribute {name_repr}"
15
    else:
16
        format_msg = "{class_repr} object attribute {name_repr} is read-only"
17
    raise AttributeError(format_msg.format(class_repr=class_repr, name_repr=name_repr))
18
19
20
def guard(instance: typing.Any, name: str) -> None:
21
    """Wrap up the common logic for using cant_modify."""
22
    if not inspect.isdatadescriptor(inspect.getattr_static(instance, name, MISSING)):
23
        cant_modify(instance, name)
24