| Total Complexity | 4 |
| Total Lines | 24 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 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 |