Skip to content

Commit 5a939d0

Browse files
sobolevnIvan Levkivskyi
authored and
Ivan Levkivskyi
committed
Docs for new __slots__ feature (#11186)
1 parent ab62307 commit 5a939d0

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

docs/source/class_basics.rst

+26
Original file line numberDiff line numberDiff line change
@@ -315,3 +315,29 @@ class, including an abstract method defined in an abstract base class.
315315

316316
You can implement an abstract property using either a normal
317317
property or an instance variable.
318+
319+
Slots
320+
*****
321+
322+
When a class has explicitly defined
323+
`__slots__ <https://docs.python.org/3/reference/datamodel.html#slots>`_
324+
mypy will check that all attributes assigned to are members of `__slots__`.
325+
326+
.. code-block:: python
327+
328+
class Album:
329+
__slots__ = ('name', 'year')
330+
331+
def __init__(self, name: str, year: int) -> None:
332+
self.name = name
333+
self.year = year
334+
self.released = True # E: Trying to assign name "released" that is not in "__slots__" of type "Album"
335+
336+
my_album = Album('Songs about Python', 2021)
337+
338+
Mypy will only check attribute assignments against `__slots__` when the following conditions hold:
339+
340+
1. All base classes (except builtin ones) must have explicit ``__slots__`` defined (mirrors CPython's behaviour)
341+
2. ``__slots__`` does not include ``__dict__``, since if ``__slots__`` includes ``__dict__``
342+
it allows setting any attribute, similar to when ``__slots__`` is not defined (mirrors CPython's behaviour)
343+
3. All values in ``__slots__`` must be statically known. For example, no variables: only string literals.

0 commit comments

Comments
 (0)