Immutable object: Difference between revisions

Content deleted Content added
m Python: Update Python example code from deprecated Python 2 to Python 3
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.
Line 305:
__delattr__ = __setattr__
 
def __init__(self, x, y) -> None:
# We can no longer use self.value = value to store the instance data
# so we must explicitly call the superclass
Line 312:
</syntaxhighlight>
 
The standard library helperhelpers [https://docs.python.org/3.3/library/collections.html#collections.namedtuple collections.namedtuple] createsand [https://docs.python.org/3/library/typing.html#typing.NamedTuple typing.NamedTuple], 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">
from typing import NamedTuple
import collections
 
Point = collections.namedtuple('Point', ['x', 'y'])
 
# the following creates a similar namedtuple to the above
class Point(NamedTuple):
x: int
y: int
</syntaxhighlight>
 
Introduced in Python 3.7, [https://docs.python.org/3/library/dataclasses.html dataclasses] allow developers to emulate immutability with [https://docs.python.org/3/library/dataclasses.html#frozen-instances frozen instances]. If a frozen dataclass is built, dataclasses will override __setattr__() and __delattr__() to raise FrozenInstanceError if invoked.
is roughly equivalent to the above, plus some tuple-like features.
 
<syntaxhighlight lang="python">
from dataclasses import dataclass
 
@dataclass(frozen=True)
class Point:
x: int
y: int
</syntaxhighlight>
 
=== JavaScript ===