Decorator to add __slots__ in dataclasses
Project description
dataslots
Decorator for adding slots
In python 3.7 dataclasses module was introduced for faster class creation (PEP 557).
Unfortunately there's no support for __slots__
(basic support was added in 3.10). If you want to create more memory
efficient instances, you need to do it by yourself or use @dataslots
decorator.
Usage
Simple example
@dataslots
@dataclass
class Point2D:
x: int
y: int
Inheritance
As described in docs, in derived class __dict__
is created, because base class does not have __slots__
.
Slots are created from all defined properties (returned by dataclasses.fields()
function).
@dataclass
class Base:
a: int
@dataslots
@dataclass
class Derived(Base):
c: int
d: int
Dynamic assignment of new variables
@dataslots(add_dict=True)
@dataclass
class Point2D:
x: int
y: int
point = Point2D(10, 20)
point.length = math.sqrt(point.x ** 2 + point.y ** 2)
Weakref
@dataslots(add_weakref=True)
@dataclass
class Point2D:
x: int
y: int
point = Point2D(10, 20)
r = weakref.ref(point)
Read-only class variables
With __slots__
it's possible to define read-only class variables. When using dataclasses you cannot provide type
for attribute or use typing.ClassVar
to declare one.
@dataslots
@dataclass
class A:
x = 5
y: ClassVar[set] = set()
Pickling frozen dataclass
Because of an issue 36424 you need custom __setstate__
method. In dataslots
there is implemented default version, and it is used if decorated class has no __getstate__
and __setstate__
function declared.
Added in 1.0.2
Data descriptors
Data descriptors are supported by
inheritance from DataDescriptor
(base class with required interface) or DataslotsDescriptor
(class with
additional features to simplify descriptor definition).
Check example directory for basic usage.
Added in 1.1.0
More about __slots__
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for dataslots-1.1.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 7b757fcd96cb9bd165fd68a0a04fb6ac88a656f93f0f58bcce2f9fa585594b93 |
|
MD5 | 3e7bf3586769b5a334f94e87a1ae2ab1 |
|
BLAKE2b-256 | 7e1b7d5571bae8919bde3417642e246ab86fe394aba84b480296289087b00a3f |