The future of "frozen" types as the number of CPU cores increases

sjdevnull at yahoo.com sjdevnull at yahoo.com
Wed Feb 17 17:17:47 EST 2010


On Feb 17, 2:35 am, Steven D'Aprano
<ste... at REMOVE.THIS.cybersource.com.au> wrote:
> On Tue, 16 Feb 2010 21:09:27 -0800, John Nagle wrote:
> >     Yes, we're now at the point where all the built-in mutable types
> > have "frozen" versions.  But we don't have that for objects.  It's
> > generally considered a good thing in language design to offer, for user
> > defined types, most of the functionality of built-in ones.
>
> It's not hard to build immutable user-defined types. Whether they're
> immutable enough is another story :)
>
> >>> class FrozenMeta(type):
>
> ...     def __new__(meta, classname, bases, classDict):
> ...         def __setattr__(*args):
> ...             raise TypeError("can't change immutable class")
> ...         classDict['__setattr__'] = __setattr__
> ...         classDict['__delattr__'] = __setattr__
> ...         return type.__new__(meta, classname, bases, classDict)
> ...
>
> >>> class Thingy(object):
>
> ...     __metaclass__ = FrozenMeta
> ...     def __init__(self, x):
> ...         self.__dict__['x'] = x
> ...
>
> >>> t = Thingy(45)
> >>> t.x
> 45
> >>> t.x = 42
>
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "<stdin>", line 4, in __setattr__
> TypeError: can't change immutable class
>
> It's a bit ad hoc, but it seems to work for me. Unfortunately there's no
> way to change __dict__ to a "write once, read many" dict.

Which makes it not really immutable, as does the relative ease of
using a normal setattr:

... t.__dict__['x'] = "foo"
... print t.x
foo
... object.__setattr__(t, "x", 42)
... print t.x
42



More information about the Python-list mailing list