osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Question about implementing immutability


czw., 22 lis 2018 o 11:14 Thomas Jollans <tjol at tjol.eu> napisa?(a):
> [..] this allows other classes' __init__s to set attributes.

Fair point.

> I might try setting a self._fixed flag at the end of init and do a check
>
> if getattr(self, '_fixed', False):
>     raise TypeError(f"'{type(self)}' is immutable")
>
> but this presumably comes with other problems.

Yes, I think so. For example, in order to allow mutations
in own __init__, this would require unsetting the flag before the
call and setting it afterwards. Naive implementation wouldn't work
with super-classes because of recursion, i.e. I would unset the flag,
call super and super would set the flag back on its way out.

Sincerely,
Iwo Herka