[Python-Dev] A metaclass for immutability

Tschijnmo Tschau tschijnmotschau at gmail.com
Wed Dec 17 08:37:09 CET 2014


Hi all,

Recently when I am writing a computer algebra system for a very special
purpose, it is found that being able to have objects of user-defined
classes immutable can be very nice. It would greatly enhance the safety of
the code. For example in the code that I were writing, objects hold a lot
of references to other objects of user-defined class. If other parts of the
code mutates the objects that is referenced, quite expected things could
happen.

As a result, an initial tentative implementation of a metaclass for making
objects of user-defined classes immutable is written and put into a Github
repository https://github.com/tschijnmo/immutableclass. Since I am not a
python expert yet, could you please help me

1. If such a metaclass is Pythonic? Is it considered a good practice to use
such a metaclass in a code that needs frequent maintenance?

2. Is this metaclass of interest to other Python developers as well? I mean
is it worth-while to try to put this, or something like this, into the
standard Python library?

3. If the answer to the above questions are affirmative, is my current
implementation Pythonic? Especially if it is better implemented as a class
decorator rather than a metaclass?

Most of the code should be quite straightforward. It is mimicked after the
named tuple in the collections library. Just for the initialization,
basically what I did is to make a mutable proxy class for every immutable
class. This proxy class is attempted to carry as much behaviour of the
immutable class as possible, except it is mutable.Then the initializer
defined by users are in fact called with self being an instance of the
proxy class, then the actual immutable object is built out of it.

This is my first time posting to this list. Any feedback is greatly
appreciated. Thank you!

Regards,

Jinmo
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20141217/5c1eabd5/attachment.html>


More information about the Python-Dev mailing list