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.with_slots decorator.
Usage
Simple example
@with_slots
@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
@with_slots
@dataclass
class Derived(Base):
c: int
d: int
Dynamic assignment of new variables
@with_slots(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
@with_slots(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.
@with_slots
@dataclass
class A:
x = 5
y: ClassVar[set] = set()
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.