Making immutable instances

Mike Meyer mwm at mired.org
Wed Nov 30 23:04:50 EST 2005


bonono at gmail.com writes:
> Mike Meyer wrote:
>> bonono at gmail.com writes:
>> > I am puzzled, and could have read what you want wrong. Are you saying
>> > you want something like this :
>> > a={}
>> > a.something = "I want to hang my stuff here, outside the intended use
>> > of dict"
>> Exactly. For a use case, consider calling select.select on lists of
>> file objects. If the processing is simple enough, the clearest way to
>> associate a handler with each socket is just to add it as an
>> attribute. But that doesn't work - sockets are bulitin types. So you
>> consider less light-weight solutions, like subclassing socket (now
>> that that's possible), or a dictionary of handlers keyed by socket.
>> This works by default with classes written in Python. That it doesn't
>> work for builtins is inconsistent, non-orthogonal, and
>> incomplete. However, it's easy to work around, and the obvious fix -
>> adding a dictionary to every builtin - is rather costly. So we'll live
>> with it since practicality beats purity.
> While I agree with the use case(I want it sometimes too), it seems that
> the language creator may also deliberately disallow that, not because
> it is not doable or costly. So how, the built-in types still need to
> have some form of dictionary or else how would dir(a) of the above
> dictionary work ?

Built-in types don't have a real dictionary. They have a C struct that
holds the various methods.  The entries in the struct are called
"slots", hence the __slots__ magic attribute. That __slots__ makes it
impossible to add an attribute is documented as an implementation
detail. This makes me think that the same restriction on the builtin
types is the same.

FWIW, dir returns a list built from a number of source. But if you
look at, for example, list.__dict__, you'll notice that it's not a
dict.

        <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list