immutable¶
-
lsst.utils.classes.
immutable
(cls: _T) → _T¶ Decorate a class to simulate a simple form of immutability.
A class decorated as
immutable
may only set each of its attributes once; any attempts to set an already-set attribute will raiseAttributeError
.Notes
Subclasses of classes marked with
@immutable
are also immutable.Because this behavior interferes with the default implementation for the
pickle
modules,immutable
provides implementations of__getstate__
and__setstate__
that override this behavior. Immutable classes can then implement pickle via__reduce__
or__getnewargs__
.Following the example of Python’s built-in immutable types, such as
str
andtuple
, theimmutable
decorator provides a__copy__
implementation that just returnsself
, because there is no reason to actually copy an object if none of its shared owners can modify it.Similarly, objects that are recursively (i.e. are themselves immutable and have only recursively immutable attributes) should also reimplement
__deepcopy__
to returnself
. This is not done by the decorator, as it has no way of checking for recursive immutability.