Decorator to add __slots__ in dataclasses
Project description
dataslots
Decorator for adding slots
Python3.7 provides dataclasses module for faster class creation (PEP 557). Unfortunately there's no support for __slots__. If you want to create more memory efficient instances, you need to do it by yourself or use dataslots.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.
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.0.2-py2.py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 4fe302ab59c86e01a4fafe516776a198cd8a42dc696dcc9d525e2ec8ee0fe773 |
|
MD5 | aa8075201eba64938a16361e741a901b |
|
BLAKE2b-256 | b2b22f9f4ea849a076effa673dd9b7e67bedb9358ad0875c30cd4ae0ad6298bc |