Immutable object: Difference between revisions

Content deleted Content added
m Python: Python has new options for building immutable objects, including typing.NamedTuple and dataclasses. Add new code examples with references, and refactor old code examples.
m Python: Reformat text with code highlighting
Line 312:
</syntaxhighlight>
 
The standard library helpers [https://docs.python.org/3/library/collections.html#collections.namedtuple <code>collections.namedtuple</code>] and [https://docs.python.org/3/library/typing.html#typing.NamedTuple <code>typing.NamedTuple</code>], available from Python 3.6 onward, create simple immutable classes. The following example is roughly equivalent to the above, plus some tuple-like features:
 
<syntaxhighlight lang="python">
Line 326:
</syntaxhighlight>
 
Introduced in Python 3.7, [https://docs.python.org/3/library/dataclasses.html <code>dataclasses</code>] allow developers to emulate immutability with [https://docs.python.org/3/library/dataclasses.html#frozen-instances frozen instances]. If a frozen dataclass is built, <code>dataclasses</code> will override <code>__setattr__()</code> and <code>__delattr__()</code> to raise <code>FrozenInstanceError</code> if invoked.
 
<syntaxhighlight lang="python">