Jun-20-2018, 01:13 AM
As of Python 3.6.5, what is the correct way to create an immutable object? Would you simply use a namedtuple? Or inherit from a namedtuple?
Correct way to implement immutable class
|
Jun-20-2018, 01:13 AM
As of Python 3.6.5, what is the correct way to create an immutable object? Would you simply use a namedtuple? Or inherit from a namedtuple?
Jun-20-2018, 02:24 AM
Python doesn't have great facilities for building your own immutable things, unfortunately. I'm not sure you'd get much from inheriting from namedtuple, though you're welcome to try (and report back any successes), but using them directly is probably one of the closer things you can do to get immutability.
namedtuple is a factory - not a class, but you can inherit from a tuple class you create. Point = collections.namedtuple('Point', 'x y')creates a class Point - that you may inherit. Some metaprogramming may help (definitely not a master at that).This is a small example I've whipped on the fly (well, based on some code I've written before) - just to give you an idea You can expand it the way you want.PS That example, of course, is not inheritance - it's very basic metaprogramming Allow me to introduce the real Python constructor __new__ ![]()
Test everything in a Python shell (iPython, Azure Notebook, etc.)
Jun-20-2018, 07:34 PM
Can use attrs if don't want to implements this self.
Test frozen class. attrs Wrote:Please note that true immutability is impossible in Python but it will get you 99% there. pip install attrs Test: import attr @attr.s(frozen=True) class Foo: x = attr.ib() y = 5 >>> o = Foo(100) >>> o.x 100 >>> o.x = 99 Traceback (most recent call last): File "<string>", line 449, in runcode File "<interactive input>", line 1, in <module> File "C:\python36\lib\site-packages\attr\_make.py", line 388, in _frozen_setattrs raise FrozenInstanceError() attr.exceptions.FrozenInstanceError # Can make new instance with attr.evolve() >>> o_new = attr.evolve(o, x=99) >>> o_new.x 99 >>> o.y 5 >>> o.y = 'hello' Traceback (most recent call last): File "<string>", line 449, in runcode File "<interactive input>", line 1, in <module> File "C:\python36\lib\site-packages\attr\_make.py", line 388, in _frozen_setattrs raise FrozenInstanceError() attr.exceptions.FrozenInstanceError |
|
Possibly Related Threads… | |||||
Thread | Author | Replies | Views | Last Post | |
How to implement class register? | AlekseyPython | 0 | 2,478 |
Feb-14-2019, 06:19 AM Last Post: AlekseyPython |
|
Immutable Book Class | QueenSvetlana | 10 | 7,992 |
Nov-27-2017, 07:31 PM Last Post: buran |