Skip to content

Commit

Permalink
v0.23.9: fix(commons): made superclass' init __slots__ aware [#11]
Browse files Browse the repository at this point in the history
Suggested in:
#11 (comment)
  • Loading branch information
rmlibre committed Jun 29, 2024
1 parent f8269ef commit 3bd087b
Showing 1 changed file with 15 additions and 8 deletions.
23 changes: 15 additions & 8 deletions aiootp/commons/slots.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,14 +65,21 @@ def __init__(
self, mapping: t.Mapping[t.Hashable, t.Any] = {}, /, **kw: t.Any
) -> None:
"""
Maps the user-defined kwargs to the instance attributes. If a
subclass defines a `__slots__` list, then only variables with
names in the list can be admitted to the instance. Defining
classes with `__slots__` can greatly increase memory efficiency
if a system instantiates many objects of the class.
"""
for name, value in {**dict(mapping), **kw}.items(): # flexible. subclasses
self[name] = value # should prefer specific
Maps user-defined kwargs to instance attributes. If a subclass
defines a `__slots__`, then only the names declared within can
be admitted to the instance. Unless `"__dict__"` is also added.
Defining classes with slots improves a system's memory efficiency,
especially when many instances are created. Having an instance
dictionary offers flexibility, though the interplay with slots
can cause problems. This initializer avoids setting the names
declared in `__slots__` within the a potential instance dict.
"""
slots = set(self.__slots__) # flexible init. not great
for name, value in {**dict(mapping), **kw}.items(): # performance. subclasses
if name in slots: # should prefer specificity
object.__setattr__(self, name, value) # ie. self.a = a
else: # self.b = b
self.__dict__[name] = value # ...

def __dir__(self, /) -> t.List[t.Hashable]:
"""
Expand Down

0 comments on commit 3bd087b

Please sign in to comment.