I've been programming in Python for a long time, but I still can't understand why classes base their attribute lookup on the __dict__
dictionary by default instead of the faster __slots__
tuple.
Wouldn't it make more sense to use the more efficient and less flexible __slots__
method as the default implementation and instead make the more flexible, but slower __dict__
method optional?
Also, if a class uses __slots__
to store its attributes, there's no chance of mistakenly creating new attributes like this:
class Object:
__slots__ = ("name",)
def __init__(self, name):
self.name = name
obj = Object()
# Note the typo here
obj.namr = "Karen"
So, I was wondering if there's a valid reason why Python defaults to accessing instance attributes through __dict__
instead of through __slots__
.