Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Immutable object
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== Python === In [[Python (programming language)|Python]], some built-in types (numbers, Booleans, strings, tuples, frozensets) are immutable, but custom classes are generally mutable. To simulate immutability in a class, one could override attribute setting and deletion to raise exceptions: <syntaxhighlight lang="python"> class ImmutablePoint: """An immutable class with two attributes 'x' and 'y'.""" __slots__ = ['x', 'y'] def __setattr__(self, *args): raise TypeError("Can not modify immutable instance.") __delattr__ = __setattr__ def __init__(self, x, y): # We can no longer use self.value = value to store the instance data # so we must explicitly call the superclass super().__setattr__('x', x) super().__setattr__('y', y) </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"> 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 <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"> from dataclasses import dataclass @dataclass(frozen=True) class Point: x: int y: int </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)