structured_data._cant_modify.cant_modify()   A
last analyzed

Complexity

Conditions 2

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 9
rs 10
c 0
b 0
f 0
cc 2
nop 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