cl0ne / dataslots

dataslots decorator for dataclasses feature in Python 3.7

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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__

About

dataslots decorator for dataclasses feature in Python 3.7

License:MIT License


Languages

Language:Python 100.0%