Dictless classes

Duncan Booth duncan.booth at invalid.invalid
Tue Jul 3 05:38:05 EDT 2012


Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:

> You can create instances without a __dict__ by setting __slots__:

That is a necessary but not a sufficient condition. An instance of a class 
can be created without a dict only if (either you set __slots__ or you 
implement it in C without a __dict__ attribute) AND none of its base 
classes require a dict.

Setting __slots__ when a base class requires that its instances have a 
__dict__ doesn't prevent creation of the __dict__.

> 
> But the class itself still has a __dict__:

The class is an instance of 'type'. Instances of 'type' require a dict 
therefore every class requires a dict. Except of course for old style 
classes in Python 2.x but they have a __dict__ too.

Also you cannot create a subclass of 'type' with non-empty slots (it throws 
a type error "nonempty __slots__ not supported for subtype of 'type'"). 
However I don't think that's really relevant as even if they did allow you 
to use __slots__ it wouldn't prevent the creation of a __dict__ for the 
'type' base class.

> I don't have a use-case for this. But I have some code which assumes
> that every class will have a __dict__, and I wonder whether that is a
> safe assumption.

I believe so.

-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list