Skip to main content

Decorator to add __slots__ in dataclasses

Project description

dataslots

Build Status codecov

PyPI - Python Version PyPI - Status license

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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

dataslots-1.0.2rc2.tar.gz (7.5 kB view hashes)

Uploaded Source

Built Distribution

dataslots-1.0.2rc2-py2.py3-none-any.whl (4.1 kB view hashes)

Uploaded Python 2 Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page