[Python] Does PEP 412 make __slots__ redundant?

Discussão em 'Python' iniciado por Stack, Junho 21, 2025.

  1. Stack

    Stack Membro Participativo

    PEP 412, implemented in Python 3.3, introduces improved handling of attribute dictionaries, effectively reducing the memory footprint of class instances. __slots__ was designed for the same purpose, so is there any point in using __slots__ any more?

    In an attempt to find out the answer myself, I run the following test, but the results don't make much sense:

    class Slots(object):
    __slots__ = ['a', 'b', 'c', 'd', 'e']
    def __init__(self):
    self.a = 1
    self.b = 1
    self.c = 1
    self.d = 1
    self.e = 1

    class NoSlots(object):
    def __init__(self):
    self.a = 1
    self.b = 1
    self.c = 1
    self.d = 1
    self.e = 1


    Python 3.3 Results:

    >>> sys.getsizeof([Slots() for i in range(1000)])
    Out[1]: 9024
    >>> sys.getsizeof([NoSlots() for i in range(1000)])
    Out[1]: 9024


    Python 2.7 Results:

    >>> sys.getsizeof([Slots() for i in range(1000)])
    Out[1]: 4516
    >>> sys.getsizeof([NoSlots() for i in range(1000)])
    Out[1]: 4516


    I would have expected the size to differ at least for Python 2.7, so I assume there is something wrong with the test.

    Continue reading...

Compartilhe esta Página