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.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


Download files

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

Files for dataslots, version 1.0.1
Filename, size File type Python version Upload date Hashes
Filename, size dataslots-1.0.1.tar.gz (2.7 kB) File type Source Python version None Upload date Hashes View

Supported by

Pingdom Pingdom Monitoring Google Google Object Storage and Download Analytics Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page