Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds docs about new __slots__ feature #11186

Merged
merged 6 commits into from
Oct 4, 2021
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
30 changes: 30 additions & 0 deletions docs/source/class_basics.rst
Original file line number Diff line number Diff line change
Expand Up @@ -315,3 +315,33 @@ class, including an abstract method defined in an abstract base class.

You can implement an abstract property using either a normal
property or an instance variable.

Slots
*****

When a class has explicitly defined
`__slots__ <https://docs.python.org/3/reference/datamodel.html#slots>`_
mypy will check that all attributes assigned to are members of `__slots__`.

.. code-block:: python

class Album:
__slots__ = ('name', 'year')

def __init__(self, name: str, year: int) -> None:
self.name = name
self.year = year
self.released = True # E: Trying to assign name "released" that is not in "__slots__" of type "Album"

my_album = Album('Songs about Python', 2021)

We have several rules when we count classes as "slotted"
(the rules are the same as in CPython):

1. All base classes (except builtin ones) must have explicit ``__slots__`` defined
2. ``__slots__`` must not include ``__dict__``. For example, ``__slots__ = ("__dict__", ...)`` is not valid.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pretty sure CPython allows __slots__ to include __dict__.

If dynamic assignment of new variables is desired, then add 'dict' to the sequence of strings in the slots declaration.

So this would fall under custom rules, right?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is very debatable whether slotted class with __dict__ is still a slotted class 🤔
Probably it can be in any category.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, I see where I got confused, suggested some phrasing changes :-)

Because it allows to set any possible attribute, almost as when no ``__slots__`` is defined
sobolevn marked this conversation as resolved.
Show resolved Hide resolved

And we have a custom rule:
all values in ``__slots__`` must be statically known.
For example, no variables: only string literals.
sobolevn marked this conversation as resolved.
Show resolved Hide resolved