Python etc / dict as __slots__

Published: 05 November 2020, 18:00

__slots__ can be used to save memory. You can use any iterable as __slots__ value, including dict. And starting from Python 3.8, you can use dict to specify docstrings for slotted attributes __slots__:

class Channel:
  "Telegram channel"
  __slots__ = {
    'slug': 'short name, without @',
    'name': 'user-friendly name',
  }
  def __init__(self, slug, name):
    self.slug = slug
    self.name = name

inspect.getdoc(Channel.name)
# 'user-friendly name'

Also, help(Channel) lists docs for all slotted attributes:

class Channel(builtins.object)
 |  Channel(slug, name)
 |
 |  Telegram channel
 |
 |  Methods defined here:
 |
 |  __init__(self, slug, name)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  name
 |      user-friendly name
 |
 |  slug
 |      short name, without @