3

Recently I learned about __slots__, and started using them on my codes.
And I came up with this idea of using annotations for slots.

class Foo:
    bar: int
    baz: str
    __slots__ = __annotations__.keys()

This allows me to change attributes without caring about __slots__.
But none of the codes I've seen so far uses this technique,
and just uses straightfoward __slots__ = ('attr1', 'attr2').

So I began wondering if there is a flaw/drawback to this useful trick.
Perhaps the type of __slots__ affect performance? Everyone seems to be using tuple of str.

WieeRd
  • 792
  • 1
  • 7
  • 17
  • 2
    It's a little kinky, but hey, if it does what you want, we're all consenting adults here. – martineau Aug 01 '21 at 15:24
  • 1
    linters and type checkers will likely be unhappy with that idea (`mypy` for instance complains) – anthony sottile Aug 01 '21 at 15:34
  • @AnthonySottile, looks like you can get MyPy to stop complaining just by putting `__annotations__: dict[str, Any]` right above `__slots__ = __annotations__.keys()`. – Alex Waygood Aug 01 '21 at 15:59
  • 1
    that might work today, but iirc mypy is working on better validation of `__slots__` and it's going to have no idea what you mean by `__annotations__.keys()` (also it's arguably a bug that mypy doesn't know that `__annotations__` is in scope there and once that's fixed you'd get a redefinition error) – anthony sottile Aug 01 '21 at 16:12
  • @AnthonySottile fair enough — that's useful information, thanks. Agree that the current behaviour wrt `__annotations__` seems arguably a bit of a bug. – Alex Waygood Aug 01 '21 at 19:44

0 Answers0