Making immutable instances
Ben Finney
bignose+hates-spam at benfinney.id.au
Wed Nov 23 20:41:11 EST 2005
Mike Meyer <mwm at mired.org> wrote:
> "Giovanni Bajo" <noway at sorry.com> writes:
> > In short, you can't. I usually try harder to derive from tuple to
> > achieve this (defining a few read-only properties to access item
> > through attributes). Using __slots__ is then required to avoid
> > people adding attributes to the instance.
>
> Note that this property of __slots__ is an implementation detail.
> You can't rely on it working in the future.
That's one thing I meant when I asked about caveats: implementation
warnings. Thanks.
Are there other, more dependable, ways of making immutable objects?
> I'm curious as to why you care if people add attributes to your
> "immutable" class. Personally, I consider that instances of types
> don't let me add attributes to be a wart.
And this is another meaning: style caveats. I genuinely want to
understand these issues.
I refer you to a similar question: do you consider it a wart that you
can't add attributes to instances of Python's built-in types?
>>> foo = ("spam", "eggs")
>>> foo.comment = "I love it."
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'tuple' object has no attribute 'comment'
>>> bar = 1
>>> bar.base = 10
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: 'int' object has no attribute 'base'
Is this a wart? Why?
If it's not a wart, why would it be a wart for user-defined types to
have the same behaviour?
--
\ "I spilled spot remover on my dog. Now he's gone." -- Steven |
`\ Wright |
_o__) |
Ben Finney
More information about the Python-list
mailing list