[issue46246] importlib.metadata.DeprecatedList appears to be missing __slots__
Arie Bovenberg
report at bugs.python.org
Tue Jan 4 02:57:52 EST 2022
Arie Bovenberg <a.c.bovenberg at gmail.com> added the comment:
@jaraco thanks for your quick response.
In short: __slots__ allows class layout to be optimized by replacing the class __dict__ with specific descriptors. This results in a class where only specific attributes can be get/set.
However, you only really get the savings from __slots__ if all base classes also implement it.
An example:
from pympler.asizeof import asizeof # checks complete size of objects in memory
class EmptyNoSlots: pass
class EmptyWithSlots: __slots__ = ()
class NoSlots:
def __init__(self, a, b): self.a, self.b = a, b
class WithSlots:
__slots__ = ("a", "b")
def __init__(self, a, b): self.a, self.b = a, b
print(asizeof(EmptyNoSlots())) # 152
print(asizeof(EmptyWithSlots())) # 32
print(asizeof(NoSlots(1, 2))) # 328
print(asizeof(WithSlots(1, 2))) # 112
# Let's look at inheritance:
class WithSlotsAndProperBaseClass(EmptyWithSlots):
__slots__ = ("a", "b")
def __init__(self, a, b): self.a, self.b = a, b
class NoSlotsAtAll(EmptyNoSlots):
def __init__(self, a, b): self.a, self.b = a, b
class WithSlotsAndBadBaseClass(EmptyNoSlots):
__slots__ = ("a", "b")
def __init__(self, a, b): self.a, self.b = a, b
print(asizeof(WithSlotsAndProperBaseClass(1, 2))) # 112
print(asizeof(NoSlotsAtAll(1, 2))) # 328
print(asizeof(WithSlotsAndBadBaseClass(1, 2))) # 232 -- oh no!
In importlib:
list <- has slots (builtin)
DeprecatedList(list) <- no __slots__ defined
EntryPoints(DeprecatedList) <- defines __slots__
Besides the lost memory savings, because `DeprecatedList` has no slots, you can still do:
EntryPoints().foo = 6 # setting a random attribute, not the intention.
Further reading: https://stackoverflow.com/a/28059785
----------
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue46246>
_______________________________________
More information about the Python-bugs-list
mailing list