Good question, slots can definitely help in some situations, but it’s not always worth using. By default, Python gives every object a dynamic dict, which allows you to add attributes at runtime, but that also uses more memory. When you define slots, you tell Python exactly which attributes an object can have, and it skips creating the dict, which can lead to significant memory savings, especially if you’re creating thousands or millions of instances. That said, there are tradeoffs. You lose the ability to add new attributes unless you explicitly include dict in the slots, and using slots can make inheritance a bit trickier, especially when combining it with other classes that also define slots. Also worth noting: if you’re using dataclasses, you’ll need to explicitly enable slots via @DataClass(slots=True) (available in Python 3.10+). In general, slots makes sense in performance-critical systems, like compilers, interpreters, or memory-heavy data processing pipelines, but for most everyday Python code, the benefits are usually too small to matter.

🌐
Reddit
reddit.com › r/python › full support for slots in dataclasses
r/Python on Reddit: Full support for slots in dataclasses
January 30, 2023 -

Many years ago I've made a small library to provide the __slots__ attribute to dataclasses: dataslots. It's stable, well-tested, and supports type checking. Additional features to python implementation:

  • Support for python 3.7 - 3.12 (python 3.10/3.11 added base support for slots).

  • Support for dynamic assignment for new variables (__dict__ in __slots__).

  • Pickling frozen dataclasses (fixed in python 3.10).

  • Support for data descriptors and slots simultaneously.

If you are using older versions of python or need more from dataclasses give it a try.

Github: https://github.com/starhel/dataslots PyPI: https://pypi.org/project/dataslots/

Discussions

dataclass(slots=True) does not account for slots in base classes
BPO 46382 Nosy @ericvsmith, @hynek, @serhiy-storchaka, @TeamSpen210, @sobolevn, @AlexWaygood, @ariebovenberg PRs #31980 Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state... More on github.com
🌐 github.com
19
January 14, 2022
dataclass, slots, __post_init__ and super
Bug report Bug description: Using super() in __post_init__ on a dataclass with slots fails. This code: from dataclasses import dataclass @dataclass(slots=True) class Base: def __post_init__(self): ... More on github.com
🌐 github.com
5
October 30, 2023
`dataclasses` plugins does not respect `slots=True` argument
Since 3.10 now has slots=True argument for @dataclass decorator, we need to support it, since #10864 is merged. Failing case right now: from dataclasses import dataclass @dataclass(slots=True) clas... More on github.com
🌐 github.com
2
November 6, 2021
Optimize dataclasses with __slots__
Adding __slots__ to a class improves memory usage and performance of attribute access, at the expense of not being able to set arbitrary attributes on the resulting objects. This project demonstrat... More on github.com
🌐 github.com
8
May 21, 2020
🌐
GitHub
github.com › ericvsmith › dataclasses › issues › 28
Support __slots__? · Issue #28 · ericvsmith/dataclasses
September 6, 2017 - Currently the draft PEP specifies and the code supports the optional ability to add __slots__. This is the one place where @dataclass cannot just modify the given class and return it: because __slots__ must be specified at class creation time, it's too late by the time the dataclass decorator gets control.
Author   ericvsmith
🌐
GitHub
github.com › starhel › dataslots
GitHub - starhel/dataslots: __slots__ for dataclasses
November 6, 2021 - If you prefer using the newest dataclasses.dataclass interface you can use dataslots.dataclass wrapper to provide a consistent interface regardless of the python version. Notice: Wrapper always uses dataslots to make all additional features available and slots=True is obligatory.
Starred by 23 users
Forked by 2 users
Languages   Python 100.0% | Python 100.0%
🌐
GitHub
github.com › python › cpython › issues › 90540
dataclass(slots=True) does not account for slots in base classes · Issue #90540 · python/cpython
January 14, 2022 - 3.10only security fixesonly security fixes3.11only security fixesonly security fixesstdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or error ... Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state. ... assignee = 'https://github.com/ericvsmith' closed_at = <Date 2022-03-19.21:01:51.297> created_at = <Date 2022-01-14.19:31:43.335> labels = ['type-bug', 'library', '3.10', '3.11'] title = 'dataclass(slots=True) does not account for slots in base classes' updated_at = <Date 2022-03-19.21:01:51.297> user = 'https://github.com/ariebovenberg'
Author   ariebovenberg
🌐
GitHub
github.com › python › cpython › issues › 111500
dataclass, slots, __post_init__ and super · Issue #111500 · python/cpython
October 30, 2023 - from dataclasses import dataclass @dataclass(slots=True) class Base: def __post_init__(self): pass @dataclass(slots=True) class Thing(Base): a: int b: int c: int = 0 def __post_init__(self): self.c = self.a + self.b super().__post_init__() t = Thing(1,3)
Author   voidspace
Find elsewhere
🌐
GitHub
github.com › python › mypy › issues › 11482
`dataclasses` plugins does not respect `slots=True` argument · Issue #11482 · python/mypy
November 6, 2021 - Since 3.10 now has slots=True argument for @dataclass decorator, we need to support it, since #10864 is merged. Failing case right now: from dataclasses import dataclass @dataclass(slots=True) class Some: x: int def __init__(self, x: int...
Author   sobolevn
🌐
GitHub
github.com › danielgtaylor › python-betterproto › issues › 50
Optimize dataclasses with __slots__ · Issue #50 · danielgtaylor/python-betterproto
May 21, 2020 - This project demonstrates how dataclasses can be augmented to use slots, whilst still having class attributes set (normally adding the slots attribute to a class definition would cause an error with dataclassess that declare default values).
Published   May 21, 2020
Author   nat-n
🌐
GitHub
github.com › starhel › dataslots › releases
Releases · starhel/dataslots
Drop support for python 3.6. ... with_slots is renamed to dataslots (with_slots is marked as deprecated and will be erased in future releases) fixed creating class with custom metaclass defined · added workaround for pickling dataclasses with slots (https://bugs.python.org/issue36424)
Author   starhel
🌐
GitHub
github.com › biqqles › dataclassy
GitHub - biqqles/dataclassy: A fast and flexible reimplementation of data classes · GitHub
This can be used to destructure a data class instance, as with a Scala case class or a Python namedtuple. If true, add **kwargs to the end of the parameter list for __init__. This simplifies data class instantiation from dictionaries that may have keys in addition to the fields of the data class (i.e. SomeDataClass(**some_dict)). If true, generate a __slots__ attribute for the class.
Starred by 85 users
Forked by 9 users
Languages   Python
🌐
Python
bugs.python.org › issue42269
Issue 42269: Add ability to set __slots__ in dataclasses - Python tracker
This issue tracker has been migrated to GitHub, and is currently read-only.
🌐
GitHub
github.com › python › cpython › issues › 115879
Slots does not work with typing.Final dataclass attribute · Issue #115879 · python/cpython
February 24, 2024 - Bug report Bug description: Hi, I discovered a bug when using the Final attribute along with slots=True in dataclasses. The bug is more described in this stackoverflow post where someone with more knowledge has explained to me why this h...
Author   NicoHood
🌐
Python
docs.python.org › 3 › library › dataclasses.html
dataclasses — Data Classes
3 weeks ago - Changed in version 3.11: If a field name is already included in the __slots__ of a base class, it will not be included in the generated __slots__ to prevent overriding them. Therefore, do not use __slots__ to retrieve the field names of a dataclass. Use fields() instead.
🌐
GitHub
github.com › python › mypy › issues › 17121
Spurious error for dataclass(slots=True) · Issue #17121 · python/mypy
April 13, 2024 - I get a spurious top/fid/yod.py:6: error: "File" both defines "__slots__" and is used with "slots=True" [misc]. Similar to #11821 / #11827, but a more involved repro. I found it not trivial to minimise the repro beyond the following script: rm -rf top mkdir top echo 'from . import fid' > top/__init__.py mkdir top/fid echo 'from .dug import X from .fun import * from .yod import File' > top/fid/__init__.py echo 'from dataclasses import dataclass import top.fid.fun as T @dataclass class X(T.MB): ...' > top/fid/dug.py echo 'from dataclasses import dataclass from top import does_not_exist # type: ignore @dataclass class MB: ...' > top/fid/fun.py echo 'from dataclasses import dataclass import top @dataclass(slots=True) class File: path: str' > top/fid/yod.py mypy top
Author   hauntsaninja
🌐
GitHub
github.com › python › cpython › issues › 104035
Frozen dataclasses with slots cannot override __getstate__ or __setstate__ · Issue #104035 · python/cpython
May 1, 2023 - The dataclass decorator should probably treat this way that it does other methods—only add a method if it is not already present. gh-104035: Do not ignore user-defined __{get,set}state__ in slotted frozen dataclasses #104041
Author   drhagen
🌐
GitHub
github.com › pydantic › pydantic › issues › 6783
Creating dataclass(slots=True) instance fails with defaults · Issue #6783 · pydantic/pydantic
May 23, 2023 - Traceback (most recent call last): File "x.py", line 7, in <module> A() File "venv/lib/python3.11/site-packages/pydantic/_internal/_dataclasses.py", line 124, in __init__ s.__pydantic_validator__.validate_python(ArgsKwargs(args, kwargs), self_instance=s) AttributeError: 'A' object attribute 'a' is read-only · It does work with non-pydantic dataclasses. from pydantic import dataclasses @dataclasses.dataclass(slots=True) class A: a: int = 0 A()
Author   bluetech
🌐
GitHub
github.com › pydantic › pydantic › issues › 3791
Pure-python implementation of `dataclasses` module has differences regarding slots · Issue #3791 · pydantic/pydantic
# test.py import typing from pydantic.dataclasses import dataclass @dataclass class Foo: pass print(typing.get_type_hints(Foo.__pydantic_model__)) $ pip install pydantic $ python test.py {} $ pip uninstall pydantic $ SKIP_CYTHON=1 pip install --no-binary pydantic pydantic $ python test.py {'__slots__': typing.Tuple[str, ...]}
🌐
GitHub
github.com › python › cpython › issues › 105866
dataclasses: implicitly defined __dict__ and __weakref__ slots of inherited classes are ignored. · Issue #105866 · python/cpython
June 16, 2023 - Bug report The weakref slot is redefined when inherited from a class which didn't specify slots at all (and thus has a dict and weakref slots). from dataclasses import dataclass class A: pass @dataclass(slots=True, weakref_slot=True) cla...
Published   Jun 16, 2023
🌐
GitHub
github.com › python › mypy › issues › 11827
False error for dataclass slots when class is referenced earlier · Issue #11827 · python/mypy
December 22, 2021 - Please consider import dataclasses as dtc import asyncio PublishedMessagesVar = dict[int, 'PublishedMessages'] @dtc.dataclass(frozen=True, slots=True) class PublishedMessages: task: asyncio.Future[int] left: int right: int then $ mypy t2...
Author   wrobell