Pickling slotted instances

Martin v. Löwis loewis at informatik.hu-berlin.de
Mon Sep 16 03:25:05 EDT 2002


Andrew McNamara <andrewm at object-craft.com.au> writes:

> >1. How to determine all slots? It has been proposed that __slots__
> >   should return a tuple that includes base slots as well;
> >   alternatively, iterate over base types yourself. Alternatively,
> >   return slots in __dict__.
> 
> How is this handled in an instance now? Does an instance have slots
> for all it's direct slots as well as the slots defined by it's base
> classes? If so, it should probably be serialised in exactly this manner?

I don't understand the question. By "instance", do you mean an object
of type InstanceType, or something else? Instances don't have slots.

Or do you mean the attributes of an instance? The attributes of an
instance are all kept in the instance's __dict__, regardless of the
class in which they are assigned.

Or, do you mean, by "instance", an object of a certain type which has
slots? If so, inst.attr is the same as 

getattr(inst.__class__, 'attr').__get__(inst)

(if not inst.__dict__.has_key('attr')). So 'attr' will be searched in
the class, using the method resolution order. This happens to return 
a member descriptor, namely <member 'attr' of `inst.__class` objects>.


> >   has not assigned the slot, requesting the slot value raises an
> >   AttributeError.
> 
> It would seem simple enough to include a "not set" token in the serial
> stream.

You need to specify how exactly that token is represented.

> I'm sort of surprised that slots were added without having all the
> bases covered, but I'm presuming that they are really a manifestation
> of the internal machinery that was added for class/type unification,
> and have been exposed in the language itself so people can see if it's
> a useful feature.

"The bases", for me, would put "proper syntax" before support for
automatic pickling, e.g. via

class X(object):
  def foo              # defines a slot foo.
  def bar[transient]   # defines a transient slot.

New-style classes are really the same as traditional types. In the
past, you could not pickle arbitrary types unless you have special
machinery (such as copy_reg manipulation); so it is not surprising
that you can't pickle certain cases of new-style classes
automatically. Notice that you *can* pickle them - just define the
__getstate__.

Regards,
Martin



More information about the Python-list mailing list