Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_no_init(self) -> None:
@frozen_after_init
class Test:
pass
test = Test()
with self.assertRaises(FrozenInstanceError):
test.x = 1 # type: ignore[attr-defined]
def test_add_new_field_after_init(self) -> None:
@frozen_after_init
class Test:
def __init__(self, x: int) -> None:
self.x = x
test = Test(x=0)
with self.assertRaises(FrozenInstanceError):
test.y = "abc" # type: ignore[attr-defined]
def test_derived_is_immutable(a, a2):
d = D(a, a2)
with pytest.raises(FrozenInstanceError):
d.a = a
with pytest.raises(FrozenInstanceError):
d.a2 = a2
def test_is_immutable(a):
c = C(a)
with pytest.raises(FrozenInstanceError):
c.a = a
def test_typic_klass_passes_params():
with pytest.raises(dataclasses.FrozenInstanceError):
objects.FrozenTypic(1).var = 2
def new_setattr(self, key: str, value: Any) -> None:
if getattr(self, "_is_frozen", False):
raise FrozenInstanceError(
f"Attempting to modify the attribute {key} after the object {self} was created."
)
prev_setattr(self, key, value) # type: ignore[call-arg]
def _frozen_get_del_attr(cls, fields):
# XXX: globals is modified on the first call to _create_fn, then
# the modified version is used in the second call. Is this okay?
globals = {'cls': cls,
'FrozenInstanceError': FrozenInstanceError}
if fields:
fields_str = '(' + ','.join(repr(f.name) for f in fields) + ',)'
else:
# Special case for the zero-length tuple.
fields_str = '()'
return (_create_fn('__setattr__',
('self', 'name', 'value'),
(f'if type(self) is cls or name in {fields_str}:',
' raise FrozenInstanceError(f"cannot assign to field {name!r}")',
f'super(cls, self).__setattr__(name, value)'),
globals=globals),
_create_fn('__delattr__',
('self', 'name'),
(f'if type(self) is cls or name in {fields_str}:',
' raise FrozenInstanceError(f"cannot delete field {name!r}")',
f'super(cls, self).__delattr__(name)'),
def __setattr__(self, key: str, value: Any) -> None:
if hasattr(self, "_is_frozen") and key == "lib_name":
raise FrozenInstanceError(
f"Attempting to modify the attribute {key} with value {value} on {self}."
)
super().__setattr__(key, value)